I’m trying to develop a plugin that takes a callback as the first argument on init. I’ve tried to modify the plugin code from the official tutorial. I can’t figure out why what’s wrong here:
The plugin:
(function( $ ){
var methods = {
init : function( callback, options ) {
// Create some defaults, extending them with any options that were provided
var settings = $.extend( {
'location' : 'top',
'background-color' : 'blue'
}, options);
return this.each(function() {
$this.click(function(e) {
e.stopPropagation();
var $target = $(e.target);
if (callback)
callback($target);
});
});
},
};
$.fn.myplugin = function( method ) {
// 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 on jQuery.myplugin' );
}
};
})( jQuery );
Calling the plugin:
// Create callback function
var callback = function(){alert('hey');};
$('#my-control').myplugin(callback,{'width':'600px'});
The Error:
Method function (){alert(‘hey’);} does not exist on jQuery.myplugin
This line:
Is causing the
$.errorcondition (in the nextelseclause) to fire off, since you’re checking for a method name or options object and didn’t account for passing in an argument of type function.I would recommend making the
callbackoption part of youroptionsobject instead:Usage:
Example: http://jsfiddle.net/n66mU/