As a web developer I can't avoid using Javascript. Not that I would want to or anything. I love Javascript. I'm happy enough with my JS coding skills but there was one thing that always found a way to leave me scratching my head. Callbacks!
I had no problem with the concept of callbacks, but something was missing. I always had trouble maintaining scope in callback methods. I haven't had to pay too much attention to the problem until today as jQuery has met the majority of my Javascript needs to date. Anyway after a quick search I found the solution, which is so easy I deserve a kick in the ass.
The Wrong Way
This is how I was registering callbacks to an object method in a jQuery.get():
-
$.get('http://test.domain.com', data, this.callback_method)
The problem with that is, the actual method is passed, but no reference to the object 'this'. When the callback method is executed is is executed within the scope of the method that is calling it, which could be anywhere, in which case 'this' does not refer to the object you intended.
The Right Way
-
var thisObject = this
-
$.get('http://test.domain.com', data, function(){thisObject.callback_method})
Note that the variable 'thisObject' becomes a reference to the object that this call originates from and can be called from anywhere.
It's well worth reading the full article 'Registering JavaScript object methods as callbacks' over at Bitstructures.com.