Take this class:
var MyClass = new Class({
Implements: [Events, Options],
initialize: function() {
this.a = 1;
},
myMethod: function() {
var mc = new differentClass({
events: {
onClick: function() {
console.log(this.a); // undefined (should be 1, 2, 3 etc)
this.a ++;
}
}
});
}
});
How do I keep the value of this.a? I am basically trying to draw a line (using canvas) from the last point to the co-ordinates just clicked.
[EDIT]
I dont want to bind this as it’s bad apparently and it will over-ride the differentClass options.
several patterns are available.
decorator via
.bind()keeping a reference.
pointing to a myClass method that can deal with it:
the 2-nd one – by storing a reference is preferred due to the smaller footprint and universal support whereas
.bindis not available in every browser and needs to be shimmed as well as the extra time to curry the function on execution.selfis what you will find in mootools-core itself when possible.if performance is not at risk, method 3 can probably offer the best readability and code structure. the arguments to the method will remain what the click handler passes, i.e.
eventandevent.targetwill be the handler.in pattern #2 with
self,thiswill point to the click handler within the anonymous function (or to the other class, for example), which may be useful as well – rebinding context can be a pain in the neck