addEventListener and the scope of this

后端 未结 3 646
时光说笑
时光说笑 2021-01-02 04:53

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

3条回答
  •  失恋的感觉
    2021-01-02 05:40

    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

提交回复
热议问题