如何在jquery插件上存储设置?

时间:2014-06-16 21:35:13

标签: jquery jquery-plugins

我是写jquery插件的新手。我有这样的代码 - 只有ilustrate,真正的代码必须存储许多变量。

<input type="button" name="firstbutton" />
<input type="button" name="secondbutton" />

和js:

$.fn.pluginname = function (options) {
    var opts = $.extend($.fn.pluginname.defaults, options);
    return this.each(function () {
       $.fn.pluginname.init($(this), opts);
    });
};
$.fn.pluginname.init = function (obj, opts) {
    this.sfobj = obj;
    this.sfopts = opts;
};
$.fn.pluginname.send = function () {
    //some logic to get right url, something like this
    var sendurl = this.sfopts.url;
};

并希望使用:

//init first button
$("#firstbutton").pluginname({
  'url': "firsturl.com"
});
//init second button
$("#secondbutton").pluginname({
  'url': "secondurl.com"
});

//call when needed
$("#secondbutton").pluginname.send();

问题是,当我初始化第二个按钮时,init方法重写sfopts变量。存储插件的init设置的最佳实践是什么?并且可以像最后一行代码一样调用方法并恢复设置吗?感谢

1 个答案:

答案 0 :(得分:1)

在jQuery插件中设置默认值的最佳和最简单的方法是:

var setting = $.extend({
    url: 'www.example.com',
    anotherSettingOption: 'another value'
}, options);

当你需要调用它时,你只需使用:

setting.urlsetting.anotherSettingOption