Get parent in jQuery callbacks

It is my problem:

var greatapp = { start : function(){ $.AJAX({ url : 'foo.com', success : function(data){ greatapp.say(data); } }) }, say : function(s){ console.log(s); } } 

What I don't like about this example is that I repeat my self in the success function, defining the name of the object, and not just this , which obviously will not work, because it is in an external function.

Once the name is greatapp once in a JS object?

+7
source share
1 answer

A common JavaScript idiom is to store the value of this in a variable like me or self , and use it in a callback.

This will work, since the callback has access to variables declared in the scope - in other words, the callback forms a closure on self

 var greatapp = { start : function(){ var self = this; $.AJAX({ url : 'foo.com', success : function(data){ self.say(data); } }) }, say : function(s){ console.log(s); } } 
+10
source

All Articles