James Camerson
James Camerson

Reputation: 43

How do I bind parameters to callbacks?

In C++, you have a bind function that allows you to bind parameters to functions. When you call the function, it will be called with those parameters. Similarly, MySQL has an ability to bind parameters to queries where it will substitute question marks with the variable. In Javascript and jQuery, the bind function has a confusingly different meaning. It makes the passed parameter the this variable, which is not at all what I want. Here's an example of what I want to achieve:

    var outerVariable;
    var callbacks = [
        some_object.event,
        some_object.differentEvent.bind(outerVariable)
    ];
    // func() will automatically have outerVariable in scope
    $.map(callbacks, function(func) { func(); });

Upvotes: 4

Views: 141

Answers (3)

Paul S.
Paul S.

Reputation: 66334

I don't think there is an easy way to use bind without playing around with this, if you want to bind arguments only you may be better writing a wrapper

function bindArgs(fn) {
    var slice = Array.prototype.slice,
        bound_args = slice.call(arguments, 1);
    return function () {
        var args = slice.call(arguments, 0);
        return fn.apply(this, bound_args.concat(args));
    }
}

Now

function foo(a, b) {
    console.log(this, a, b);
}
var bar = bindArgs(foo, 'bar');
var obj = {baz: bar};
obj.baz('baz'); // logs obj, "bar", "baz"

Upvotes: 2

Jonathan Apodaca
Jonathan Apodaca

Reputation: 5788

The only difference between the C++ and JavaScript bind is that the JavaScript bind takes one extra argument: thisArg, which will bind the keyword this for the bound function to whatever you pass in. If you do not want to re-bind the this-argument, then pass null as the first parameter, and the rest should look familiar to the C++ variant you speak of:

function add(a, b) {
    return a + b
}

var three = add(1, 2)
var makeThree = add.bind(null, 1, 2)
three = makeThree()

Upvotes: 1

Esteban Felix
Esteban Felix

Reputation: 1561

Do this instead:

var callbacks = [
    some_object.event,
    some_object.differentEvent.bind(some_object, outerVariable)
];

Upvotes: 1

Related Questions