views:

563

answers:

3

I have a class:

function RustEditor() {

this.init = function() {

 var saveButton = this.container.find("button.saveButton");
 saveButton.click(function(){this.save();});

};
...

When I click the button, it complains that this.save is not a function. This is because "this" does not refer to the instance of RustEditor here, but to the button. What variable can I use inside that callback closure to point to the instance of RustEditor? I could use rust.editor (it's name in the global scope) but that's smelly code.

+12  A: 

Common practice is to enclose the this value like so:

 function RustEditor() {

 this.init = function() {
    var self = this;

    var saveButton = this.container.find("button.saveButton");
    saveButton.click(function(){self.save();});

 };

Update with suggestion from tvanfosson: this gets rebound when the event handler is invoked and thus you need to capture the reference to the class at the time the object is created with a variable that will retain that reference in the closure.

seth
Hairy bastard beat me to it!!!
Janie
My hirsuteness had nothing to do with it! It's the first time it's happened. :)
seth
It would improve your answer if you would explain why this needs to happen, to wit, _this_ gets rebound when the event handler is invoked and thus you need to capture the reference to the class at the time the object is created with a variable that will retain that reference in the closure.
tvanfosson
@tvanfosson - Thanks for suggestion. Hope you don't mind I quoted you verbatim. You said it much better than I.
seth
+1  A: 

Within RustEditor() you could first copy a reference to the button and use that.

Janie
+2  A: 

here is a very good article on 'this' and jQuery: jQuery's this: demystified

Jon Erickson