jQuery Plugin: Adding Callback functionality
Just execute the callback in the plugin:
$.fn.myPlugin = function(options, callback) {
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this); // brings the scope to the callback
}
};
You can also have the callback in the options object:
$.fn.myPlugin = function() {
// extend the options from pre-defined values:
var options = $.extend({
callback: function() {}
}, arguments[0] || {});
// call the callback and apply the scope:
options.callback.call(this);
};
Use it like this:
$('.elem').myPlugin({
callback: function() {
// some action
}
});
I don't know if I understand your question correctly. But for the second version: This would call anotherFunction
immediately.
Basically your plugin should be some kind of function that looks like this:
var myPlugin = function(options, callback) {
//do something with options here
//call callback
if(callback) callback();
}
You have to provide a function object as callback, so either function(){...}
or anotherFunction
(without ()
).
Bringing back a blast from the past.
Worth noting that if you have two arguments passed, for example:
$.fn.plugin = function(options, callback) { ... };
Then you call the plugin without the options argument but with a callback then you'll run into issues:
$(selector).plugin(function() {...});
I use this to make it a little more flexible:
if($.isFunction(options)) { callback = options }