[英]Calling functions within prototype in jQuery plugin
嘗試學習可擴展的jQuery插件開發。 我完全迷住了如何從jQuery插件包裝器調用類中的函數。
我主要是從這里為我的代碼創建包裝器的,並且試圖理解/使用它,但是運氣不高。
以下代碼的重要部分。 我想要它,所以我可以調用(例如) $(something).carousel(5)
並將其傳遞給Carousel類中的slide
函數。 同為字符串,所以$(something).carousel('go')
將運行go
在類中。
我該如何使用這種結構?
(function(window, $){
var Carousel = function(elem, options){
this.elem = elem;
this.$elem = $(elem);
this.options = options;
};
Carousel.prototype = {
defaults: {
[...]
},
init: function() {
this.config = $.extend({}, this.defaults, this.options);
this.create();
return this;
},
create: function() {
[...]
},
slide: function(num) {
[...]
}
};
Carousel.defaults = Carousel.prototype.defaults;
$.fn.carousel = function(options) {
return this.each(function() {
var carousel = new Carousel(this, options);
if (!options || typeof options == 'object') carousel.init();
else if (typeof options == 'number') carousel.slide(options);
else if (typeof options == 'string') carousel.options;
});
};
window.Carousel = Carousel;
})(window, jQuery);
您或多或少都在正確的道路上,主要問題是調用carousel.options
將只訪問您的Carousel
實例的options
屬性。 您想要做的是在實例上動態調用該函數:
$.fn.carousel = function(options) {
return this.each(function() {
var carousel = new Carousel(this, options);
// do a loose comparison with null instead of !options; !0 == true
if (options != null || typeof options === 'object')
carousel.init();
else if (typeof options === 'number')
carousel.slide(options);
// make sure options is the name of a function on carousel
else if (typeof options === 'string' && typeof carousel[options] === 'function') {
carousel[options](); // call the function by name
}
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.