Question

If I have a chunk of code like this:

.hover(
        function () {
            hoverState($("#navbar a").index(this),1);
        },
        function () {
            hoverState($("#navbar a").index(this),-1);
});

Is there any way to get rid of the anonymous functions and just say:

.hover(
    hoverState($("#navbar a").index(this),1),
    hoverState($("#navbar a").index(this),-1);
);
Was it helpful?

Solution

No, because otherwise your call:

hoverState($("#navbar a").index(this),1)

would evaluate at the same time as the call to the hover function itself. Since Javascript supports closures and first-class functions, you could make a wrapper function:

function wrapper(position){
    function _f(){
        hoverState($("#navbar a").index(this), position);
    }
    return _f;
}

And then use:

.hover(
    wrapper(1),
    wrapper(-1),
)

But the gains of such an approach are questionable.

OTHER TIPS

The reason for the anonymous function is to defer the call to hoverState until the hover event happens. Without some function reference there, you end up calling hoverState and the result of the function call becomes the parameter to the hover method, which is certainly not what you want. The alternative would be to have a named function, but that's really no better and, in some ways, actually worse.

There's a way to do something like this, with the jLambda plugin.

// Without plugin:
$('.foo').click(
            function() {
                $(this).hide();
                $('p').show();
                $('a').width(20);
            });

// With plugin:
$('.foo').click($l.hide().$('p').show().$('a').width(20));

My answer can seem stupid but here goes... you can use simple functions :}

function hoverStateProxy1() {
        hoverState($("#navbar a").index(this),1);
}


function hoverStateProxy2() {
        hoverState($("#navbar a").index(this),-1);
}

.hover(hoverStateProxy1, hoverStateProxy2);

As long as you passing reference to function you are OK. It can be both anonymous or not.

You could use JavaScript's "Apply" Function. Here is an example taken from the Prototype.js framework (bind implementation, though it should probably be renamed if not being used from within the framework).

EDIT: Corrected, see This Post

if (!Object.bind) {
    Function.prototype.bind= function(owner) {
        var that= this;
        var args= Array.prototype.slice.call(arguments, 1);
        return function() {
            return that.apply(owner,
                args.length===0? arguments : arguments.length===0? args :
                args.concat(Array.prototype.slice.call(arguments, 0))
            );
        };
    };
}

Usage:

.hover(
    hoverState.bind(this,$("#navbar a").index(this),1),
    hoverState.bind(this,$("#navbar a").index(this),-1)
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top