Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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).

Solution 2:

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:

varself = this;
var innerFunction = function() {
    self.x = 1;
};

Solution 3:

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);
});

Solution 4:

You can bind the context of the parent object like so.

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

Post a Comment for "Jquery: How To Access Parent Function "this" From Inside Anonymous Function?"