這個問題困擾了我一段時間,這是工作的一個我找到了。適用於我。英語不是我的第一語言,所以如果我沒有清楚解釋,請原諒我。
這是我之前爲切換開關創建的一個插件。
在init
方法中,我將插件選項保存到jQuery.data()
,然後稍後我可以用新選項調用simpleSwitchUpdate
函數。如您所見,我檢索爲元素保存的舊選項,並致電$.extend
撰寫新選項,並撥打$.fn.simpleSwitch
和newOptions
。我一直在使用這種模式創建可更新的插件一段時間,它對我來說工作得很好。
/**
* A plugin for switch
*/
(function($) {
var Switch = {
init : function(options, elm) {
var self = this;
self.$elm = $(elm);
self.$elm.empty();
self.options = $.extend({}, $.fn.simpleSwitch.options, options);
self.$elm.data("switchData", self.options);
self.$elm.append(self.createSwitch());
},
createSwitch : function() {
//logic to create your plugin
}
};
$.fn.simpleSwitch = function(options) {
return this.each(function() {
var simpleSwitch = Object.create(Switch);
simpleSwitch.init(options, this);
});
};
$.fn.simpleSwitchUpdate = function(options) {
var switchData = this.data("switchData");
var newOptions;
if (switchData) {
newOptions = $.extend({}, switchData, options);
} else {
newOptions = $.extend({}, $.fn.simpleSwitch.options, options);
}
return this.simpleSwitch(newOptions);
};
$.fn.simpleSwitch.options = {
width : 25,
height : 15,
on : true,
onDirection : "right",
easing : "easeOutQuint",
roundBorder : true,
onColor : "orange",
offColor : "lightgray",
onToggle : null
};
})(jQuery);
JSFIDDLE LINK
通常情況下,插件將有這樣的一種方式。這是哪個插件,還是你創建的東西? – 2011-05-15 01:38:12
這是我創建的一個。好吧,有點。我正在創建一個。 我只是抓住了我能找到的第一個簡單例子。 – coffeemonitor 2011-05-15 01:45:36
它的插件。你可以隨時調整你想要的。 – Jeff 2011-05-15 02:15:35