Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how to access parent function "this" from inside anonymous function?

...
$.fn.annotateEdit = function(image, note) {
    if (note) {
        this.note = note;
    } else {
        var newNote = new Object();
        newNote.id = "new";
        this.note = newNote;
    }
}
...
var mynote = this.note;

form.find(':radio').change(function() {
    var vacancy = $(this).attr('value');
    mynote.vacancy = vacancy;
});
...

Is it possible to access "this.note" from the change() handler without defining "mynote"?

like image 228
lkraav Avatar asked Feb 05 '12 16:02

lkraav


4 Answers

I use a pattern like this so I can access anything in the enclosing scope:

var that = this;
...

form.find(':radio').change(function () {
    that.note.vacancy = $(this).attr('value');
});

I am a fan of this pattern because it makes the code a little more readable. In my opinion, it is clear what it being accessed is part of the enclosing scope (as long as the usage of that is consistent).

like image 63
Alec Gorge Avatar answered Oct 16 '22 16:10

Alec Gorge


Use $.proxy to bind it to a function...

   // Returns a function-------v
form.find(':radio').change( $.proxy(function() {

    var vacancy = $(this).attr('value');
    mynote.vacancy = vacancy;

}, this) );
//   ^---- ...that has its "this" value set as this argument.
like image 27
user1106925 Avatar answered Oct 16 '22 15:10

user1106925


There is no dedicated language mechanism for it. The common pattern is to store the this in local (closure) variable (often named self or that) of the outer function:

var self = this;
var innerFunction = function() {
    self.x = 1;
};
like image 3
Xion Avatar answered Oct 16 '22 14:10

Xion


Check this - http://api.jquery.com/bind/ and "Passing event data" You can do something like this :

form.find(':radio').bind("change", {
context : this
}, function(event){
    console.log(event.data.context);
    console.log(event.data.context.note);
});
like image 1
Radoslav Georgiev Avatar answered Oct 16 '22 16:10

Radoslav Georgiev