I have a third party flash object which i can manipulate through a javascript API they provided. I am tryind to listen to an event on this object and then fire event inside
This is the typical approach to this problem:-
(function(self) {
self.chart.addEventListener('create', function() {self.fireEvent('created');}, false);
})(this);
What about creating an external variable before referencing to 'this' object. For example:
var _this = this;
this.chart.addEventListener('create', function() { _this.fireEvent('created'); }, false)
While the other answers accomplish what you needed, they don't work in the most efficient (scalable) way, because they don't ultimately decouple the view object (this.chart
) from that view's logic (fireEvent()
). In MVC applications, these view "decisions" reside in a controller. The controller "controls" views and should contain all of the APIs the view may access.
In your example, this
is the controller, and that's fine (it means you're adding your listeners in the right place). All you really need to do is bind the handler to the scope of the thing that should do the "handling" -- in your case: this
:
// `this` is the controller of `chart`
this.chart.addEventListener('create', function() {
this.fireEvent('created');
}.bind(this));
What the other answers on this page have done is made it so your view becomes its own controller, but only while handling 'create' events, by assigning a temporary reference to the "controller" using var self = this
. Again, this works just fine, but it doesn't work nicely at scale in event-driven applications, and it doesn't really make sense if you have a lot of events to handle.
.bind()
is an ECMAScript 5 implementation. If it's needed to work in even older browsers, a good method of doing so is described here (using functions
and .call()
): https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind