MegaMatt
MegaMatt

Reputation: 23763

Writing jQuery plugins: how to set up callback to terminate plugin execution when false returned

I'm writing a jQuery plugin that has a couple of callbacks, and am at the point where I need to allow one of the callbacks to run. The callback in question is 'beforeListItemSelect', so naturally I'd like the plugin code after the callback to not run if the callback function returns false. So the following is a section of my plugin code:

$listItems.live('click', function() {
    $.isFunction(options.beforeListItemSelect) && options.beforeListItemSelect.call(this);

    // perform select action (apply css, etc)

    $.isFunction(options.afterListItemSelect) && options.afterListItemSelect.call(this);
});

So if I'm calling the plugin (myPlugin), and I've defined the beforeListItemSelect callback like this:

$('#someDiv').myPlugin({
    beforeListItemSelect: function() {
        return false;
    }
});

I would want the plugin to terminate after the beforeListItemSelect callback. Does anyone have an idea of how I can set up the plugin to not proceed if false is returned from the callback?

Thanks very much.

Upvotes: 0

Views: 365

Answers (1)

Tomalak
Tomalak

Reputation: 338316

Less syntactic sugar, and things start to get easy again:

var result;

if ($.isFunction(options.beforeListItemSelect))
  result = options.beforeListItemSelect.call(this);
}
if (result === false) return;

You can of course still use all the syntactic sugar you like:

$.isFunction(options.beforeListItemSelect) && result = options.beforeListItemSelect.call(this);

but this does not exactly contribute to code legibility or enhance anything. It's just ... possible. However, not everything that's possible should be done.

Upvotes: 1

Related Questions