之前我已经编写了基本的jQuery插件,但我很难理解更复杂的东西。我想模仿jQuery UI的API,它的工作原理如下:
$('#mydiv').sortable({name: 'value'}); // constructor, options
$('#mydiv').sortable("serialize"); // call a method, with existing options
$('#mydiv').sortable('option', 'axis', 'x'); // get an existing option
我尝试了以下内容:
(function($){
$.fn.myPlugin = function(cmd){
var config = {
default: 'defaultVal'
};
if(typeof cmd === 'object'){
$.extend(config, cmd);
}
function _foo(){
console.log(config.default);
}
if(cmd==='foo'){
return _foo();
}
this.each(function(){
// do default stuff
});
}
})(jQuery);
$('#myElement').myPlugin({default: 'newVal'});
$('#myElement').myPlugin('foo');
我想在这里看到的是'newval'被记录,但我看到的是'defaultVal';每当我在元素上调用.myPlugin()时,就会调用插件并从头开始。
我也尝试过使用_foo.call(this)和其他一些变体。没有快乐。
在某种程度上,我理解为什么会这样,但我知道必须以与jQuery UI相同的方式来实现。我只是看不出来!
(我很欣赏jQuery UI使用widget工厂来处理所有这些,但我不想让它成为插件的要求。)
答案 0 :(得分:4)
也许你想要的是......
(function($){
var config = {
default: 'defaultVal'
};
$.fn.myPlugin = function(cmd){
if(typeof cmd === 'object'){
$.extend(config, cmd);
}
function _foo(){
console.log(config.default);
}
if(cmd==='foo'){
return _foo();
}
this.each(function(){
// do default stuff
});
}
})(jQuery);
$('#myElement').myPlugin({default: 'newVal'});
$('#myElement').myPlugin('foo');
将config
变量移到myPlugin
函数之外。此更改将导致config
仅初始化一次:创建插件函数时。
答案 1 :(得分:2)
您在调用函数期间声明 config ,而不是作为其使用的闭包。试试这个:
(function($){
var config = {
default: 'defaultVal'
};
$.fn.myPlugin = function(cmd){
if(typeof cmd === 'object'){
$.extend(config, cmd);
}
function _foo(){
console.log(config.default);
}
if(cmd==='foo'){
return _foo();
}
this.each(function(){
// do default stuff
});
}
})(jQuery);
$('#myElement').myPlugin({default: 'newVal'});
$('#myElement').myPlugin('foo');
此外,您可以查看jQuery data API缓存数据,特别是如果您不打算每页只有一个实例。