jquery plugin method return value
I am writing a plugin for some common tasks for the drop down. Selected Index method needs to return a value to me. How can i accomplish this inside a plugi开发者_开发问答n where some methods may or may not return a value? For methods that do not return a value, i want to maintain chainability.
jQuery.fn.dropdownHelper = function(method) {
var methods = {
init: function(){ },
empty: function(){
if (this.tagName == 'SELECT')
this.options.length = 0;
},
selectedIndex: function(){
var index = this.selectedIndex;
if(index == 'undefined')
index = -1;
alert (index);
return index;
}
};
return this.each(function() {
// Method calling logic
if ( methods[method] )
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
else if ( typeof method === 'object' || ! method )
return methods.init.apply( this, arguments );
else
$.error( 'Method ' + method + ' does not exist' );
});
};
"Unless you're returning an intrinsic value from your plugin, always have your plugin's function return the this keyword to maintain chainability." -Plugins/Authoring on docs.jquery.com
This means that you return index (intrinsic value) from your selectedIndex function, like you are currently are. Then for all other functions for which you are not currently specifying any return value, you return the this keyword to maintain chainability. For example, to maintain chainability when calling .dropdownHelper('empty'), try the following.
empty: function(){
if (this.tagName == 'SELECT')
this.options.length = 0;
return this;
},
If that doesn't work, try returning $(this) instead.
精彩评论