A.I on the 1s and 0s

Alnur Ismail is a developer for Microsoft

Maintaining Context in a JavaScript Callback

For reference. To maintain context in a JavaScript callback use a closure and an anonymous function. For example:

var curObj = this; //closure to get context in callback
$('#foobar').animate({ height: 100 }, 1000, "jswing", function() { 
   alert(curObj.someProperty); 
});

To avoid the anonymous function use the Microsoft Ajax helper Function.createDelegate as follows:

this.animate = function() {
   $('#foobar').animate({ height: 100 }, 1000, "jswing", 
      Function.createDelegate(this, this.AnimateCallback)
);};

this.AnimateCallback = function() {
   alert(this.someProperty);
}

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required)