2012-10-12 9 views
5

Basit jQuery eklentisi yazdım, ama daha gelişmiş yüzden gibi şeyler yapabiliriz yapmak istiyorum:

$.myplugin.close(); 
$.myplugin.open(); 
$.myplugin.next(); 
$.myplugin.prev(); 

böyle nasıl çağrılabilir bir eklenti yazabilirim?

------------------------- Güncelleme -------------------- -----

Teşekkür @Craig MacGregor, bunu takdir ediyorum.

Ama şöyle

$(this).myplugin.load(); 
+2

Bu kötü biçimidir ve gerektiği asla b e bu şekilde inşa edildi. Tüm işlevlere $ ('ele') gibi bir yöntem olarak erişilmelidir. Myplugin ('close/open/next/prev'); – Ohgodwhy

+2

Birçok upvot ... garip. O zaman ı olarak yazmaya gerek detaylı olarak fazla olması benim seçeneklerini ayarlamak gerekiyorsa – gdoron

+0

@Ohgodwhy '$ (' ele. ') myplugin ({eylemi:.' 'yakın xxx: xxx ......}) ; ' – user1740052

cevap

3

Sen "myplugin" bir nesneyi atayabilirsiniz aşağıda gibi olması gerekir işlevi çağırmak için:

$.myplugin = { 
    close: function(){ 
     //code 
    }, 
    open: function(){ 
     //code 
    }, 
    next: function(){ 
     //code 
    }, 

    prev: function(){ 
     //code 
    } 
}; 
2

Hemen Bir Örnek:

(funciton($) { 
    var methods = { 
    init: function() {}, 
    close: function() {}, 
    open: function() {}, 
    prev: function() {}, 
    next: function() {}, 
    }; 

    $.fn.myplugin = function (method) { 
    if (methods[method]) { 
     return methods[method].apply(this, [].slice.call(arguments, 1)); 
    } else if (typeof method == 'object' || !method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     $.error('Method ' + method + ' does not exist on myplugin'); 
    }  
    }; 

}(jQuery)); 

//usage 
$(selector).myplugin(); 

// call methods 
$(selector).myplugin('close'); 
$(selector).myplugin('open'); 
$(selector).myplugin('next'); 
$(selector).myplugin('prev');