开发者

addEventListener and the scope of this

I have a third party flash object which i can manipulate through a javascript API they provided. I am tryind to listen to开发者_JS百科 an event on this object and then fire event inside my object to further bubble up the event. I happen to being using EXT Js but i dont think its important here.

Sample code

this.chart.addEventListener('create', function() {
    this.fireEvent('created');
}, false)

My problem is that 'this' inside the anonymous function refers to the object that fired the event rather than my object that I want to fire an event on.

Its yet another scope issue. Thanks in advance for any help.


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


This is the typical approach to this problem:-

(function(self) {
  self.chart.addEventListener('create', function() {self.fireEvent('created');}, false);
})(this);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜