views:

19

answers:

1

Hello,

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.

+1  A: 

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.

Tomalak
But syntactic sugar is so sweet!! =) Thanks for this, I'll give it a try.
Mega Matt
Would this work? `if ($.isFunction(options.beforeListItemSelect) }`
Mega Matt
@MegaMatt: Sure would. If you add the missing paren, and the `!`, since you are checking for `false`. ;-) JavaScript is flexible. But as I said, straight-forward code is preferable over clever code, every second you needlessly have to stop and think while reading/maintaining code is one second of your life wasted.
Tomalak
Lesson learned, thanks for the help
Mega Matt