2

Can we call() or apply() method instead of bind() for event handlers.

I know we can usenbind() to pass in the context when using the event handler.

var user = {

    data : [{name:"first person wood" , age : 45},{name :"Edwards" , age:34}],
    click : function(event){
        var randomNumber = ((Math.random() * 2 | 0) + 1) -1;
        $('input').val(this.data[randomNumber].name + " ," 
            + this.data[randomNumber].age);
    }
 };

  $('button').click(user.click.bind(user));

In the above example we are using bind to pass the user context when the button is clicked. can we use the call() or the apply() to do the same ? If yes, how would we achieve it ?

2 Answers 2

2

can we use the call() or the apply() to do the same ?

You can do something similar, but you still have to create a function (which is what bind does):

$('button').click(function() {
    return user.click.apply(user, arguments);
});

(For clarity: The arguments above is the JavaScript arguments pseudo-variable, which is available inside functions and is a pseudo-array of the arguments for that call to the function. Using apply like this then calls the function with those arguments.)

The disadvantage to this compared with bind is that the function above maintains a reference to the context in which it's created (it's a closure over that context), which in turn references all of the variables in that context (whether or not the function uses them). So in theory, if you have some variable pointing at something large and temporary that's in that context, creating a function keeps that large and temporary thing lying around when it might otherwise have been eligible for garbage collection (because, again, the function references the context, which references the large temporary thing). Engines are allowed to optimize this provided any side-effects are unobservable, and so some may and others may not. Using bind means that issue doesn't come up. And it's simpler.

Sign up to request clarification or add additional context in comments.

Comments

1

No.

You have to pass a function to click.

bind creates a new function (which calls another function with a specific context when it is called).

apply and call a function (with a specific context) immediately.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.