the following JS code is being produced from CoffeeScript equivalent.
I want to add objects to a slider widget, properties of these objects come from a Django REST view, nothing fancy, just a list of dictionaries.
I am very new to both CoffeeScript and Django and I don’t understand the visibility of this.
of the two versions here, one works, the other doesn’t.
Slider.prototype.manageObject = function(itemId, colorSequence) {
var obj;
obj = this;
return $.getJSON("http://localhost:8000/api/?item=" + itemId, function(data) {
return obj.managed.push([itemId, data]);
});
};
Slider.prototype.manageObject = function(itemId, colorSequence) {
return $.getJSON("http://localhost:8000/api/?item=" + itemId, function(data) {
return this.managed.push([itemId, data]);
});
};
why?
The problem is that value of
thisdepends on the context. It usually refers to the current object, which in the second case is the callback function. By assigningobj = thisyou keep the original reference toSliderin the variableobj, therefore callingmanaged.pushworks, in the second case you are trying to callmanaged.pushfunction on the callback function which doesn’t exist.A really great explanation of
this: http://www.quirksmode.org/js/this.html and http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/