2014-06-16 20 views
0

Iam新寫jQuery插件。我有這樣的代碼 - 僅用於ilustrate,真正的代碼必須存儲許多變量。如何在jquery插件上存儲設置?

<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變量。什麼是存儲插件初始化設置的最佳實踐?有可能像最後一行代碼和恢復設置一樣調用方法?由於

回答

1

設置在一個jQuery插件默認的最佳和最簡單的方法是這樣的:

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

,當你需要調用它,你只需使用:

setting.urlsetting.anotherSettingOption

+1

謝謝,但默認不是問題。問題是firstbutton和secondbutton的不同設置,並在調用插件的某些方法時恢復它。 – user181685