jQuery Plugin: Adding Callback functionality

dclowd9901 picture dclowd9901 · Mar 28, 2010 · Viewed 62.5k times · Source

I'm trying to give my plugin callback functionality, and I'd like for it to operate in a somewhat traditional way:

myPlugin({options}, function() {
    /* code to execute */
});

or

myPlugin({options}, anotherFunction());

How do I handle that parameter in the code? Is it treated as one full entity? I'm pretty sure I know where I'd place the executory code, but how do I get the code to execute? I can't seem to find a lot of literature on the topic.

Answer

David Hellsing picture David Hellsing · Mar 28, 2010

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
    }
});