Consider this straightforward code example (it's in AngularJS for simplicity, but the scenario is common in JavaScript):
angular.module('app',[]).
directive('myDir', function(){
this.state = {a:1, b:2};
return {
link: function(scope, elem, attrs){
elem.on('click', function(){
// "this" refers to the element, not the directive
this.state.a++;
this.state.b++;
console.log(this.state);
});
}
}
});
When the onclick callback is triggered, "this" points to the element rather than the directive function.
To remedy this, we often create a closure and use var self = this
.
angular.module('app',[]).
directive('myDir', function(){
// creating a closure for assistance
var self = this;
this.state = {a:1, b:2};
return {
link: function(scope, elem, attrs){
elem.on('click', function(){
self.state.a++;
self.state.b++;
console.log(self.state);
});
}
}
});
Although this method works and is commonly used, it may seem like a workaround in design. Is there a more optimal way to synchronize between a class and user events?