Louis
Louis

Reputation: 4210

Reference Object calling function in Javascript

I have a makeshift events system in JS and the attacher looks like this:

events.attach(events.NEW_TASK,this.update);

Where this.update is a callback/handler/function. The problem is, when the dispatcher tries to call this handler, it loses it's original context. How can I bind the handler with the context of the object that calls the attach function without passing this as an argument and using that?

Edit: I should also mention that it will be somewhat of a framework so it has to be simple for other developers so preferably not needing to store the context in another variable.

Upvotes: 0

Views: 402

Answers (3)

Tim Down
Tim Down

Reputation: 324567

Until ECMAScript 5 has wide adoption in browsers, you could use your own implementation of Function.prototype.bind:

function bind(func, thisObj) {
    return function() {
        func.apply(thisObj, arguments);
    };
}

events.attach(events.NEW_TASK, bind(this.update, this));

Upvotes: 1

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827316

Another option, using the Function.prototype.bind method, part of the new ECMAScript Standard:

events.attach(events.NEW_TASK, this.update.bind(this));

Upvotes: 2

Kunal
Kunal

Reputation: 362

You could store the reference of "this" in a local variable and try calling the function using it

var that = this;

events.attach( events.NEW_TASK, function( ) { that.update(); } );

Upvotes: 0

Related Questions