I'm trying t开发者_运维百科o tweak a jquery plugin (https://raw.github.com/loopj/jquery-tokeninput/master/src/jquery.tokeninput.js) to add a method that would update a particular default setting (the hintText).
There are already some methods provided:
var methods = {
init: function(url_or_data_or_function, options) {
var settings = $.extend({}, DEFAULT_SETTINGS, options || {});
return this.each(function () {
$(this).data("tokenInputObject", new $.TokenList(this, url_or_data_or_function, settings));
});
},
clear: function() {
this.data("tokenInputObject").clear();
return this;
},
add: function(item) {
this.data("tokenInputObject").add(item);
return this;
},
remove: function(item) {
this.data("tokenInputObject").remove(item);
return this;
},
get: function() {
return this.data("tokenInputObject").getTokens();
}
}
And I added this:
updateHintText: function (hintText) {
DEFAULT_SETTINGS.hintText = hintText;
}
This does update it, BUT, it does not work on an already created instance. For example, I call this method like this:
$("#textbox1").tokenInput("updateHintText", 'updated hint');
But when the hint dropdown is displayed the next time, it still shows the original hint:
function show_dropdown_hint () {
if(settings.hintText) {
dropdown.html("<p>"+settings.hintText+"</p>");
show_dropdown();
}
}
So even though DEFAULT_SETTINGS.hintText gets updated, settings.hintText still refers to the original setting passed in when instantiating the plugin--which does make sense.
So, how would you change my updateHintText() method so that settings.hintText would return the new setting? Right now the workaround I did was to create a new variable which would hold the new setting value, and modified the show_dropdown_hint() method to use this new variable instead of settings.hintText if it is non-empty. But I'd prefer to just use the settings object.
Thanks.
It seems like this is because you are attaching to the default settings, rather than the actually settings hash that was extended from this line in the init function.
var settings = $.extend({}, DEFAULT_SETTINGS, options || {});
The problem is that this settings hash is outside of the scope of your method so you are unable to access it.
Try and move the instantiation of settings outside of the init method, so you have access to it. Then you can use your function to modify it:
// Additional public (exposed) methods
var settings = {};
var methods = {
init: function(url_or_data_or_function, options) {
settings = $.extend({}, DEFAULT_SETTINGS, options || {});
return this.each(function () {
$(this).data("tokenInputObject", new $.TokenList(this, url_or_data_or_function, settings));
});
},
updateHintText: function (hintText) {
settings.hintText = hintText;
}
//..other methods...
精彩评论