【发布时间】:2013-03-21 09:35:30
【问题描述】:
我想创建带有配置的 jQuery 插件(例如插件 myplugin)。
比调用 $(elem).myplugin(config); 之后,我想从这个插件调用方法,比如 $(elem).myplugin().method() 已经存储的配置。
我的报价是这样的:
(function($) {
$.fn.myplugin = function(options) {
var $this = $(this);
var getOptions = function() {
return $this.data('myplugin');
};
var initOptions = function(opt) {
$this.data('myplugin', opt);
};
var setOption = function(key, value) {
$this.data('myplugin')[key] = value;
}
var updateBorderWidth = function() {
$this.css('border-width',
getOptions().borderWidth * getOptions().coeficient);
};
var init = function(opt) {
initOptions(opt);
updateBorderWidth();
}
function changeBorder(width) {
setOption('borderWidth', width)
updateBorderWidth();
}
if(options) {
init(options);
}
return {
changeBorder : changeBorder
};
}
})(jQuery);
及用法:
$(function() {
var item1 = $('#test1').myplugin({ coeficient: 1, borderWidth: 1 });
var item1 = $('#test2').myplugin({ coeficient: 2, borderWidth: 1 });
$('#btn').click(updateBorder);
});
function updateBorder() {
$('#test1').myplugin().changeBorder($('#inpt').val());
$('#test2').myplugin().changeBorder($('#inpt').val());
}
示例:http://jsfiddle.net/inser/zQumX/4/
我的问题:这样做是个好习惯吗?
可能是方法不正确。你能提供更好的解决方案吗?
【问题讨论】:
标签: javascript jquery plugins