Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 240
Jonnio Avatar asked Nov 26 '09 11:11

Jonnio


People also ask

What is the purpose of addEventListener?

The addEventListener() method makes it easier to control how the event reacts to bubbling. When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.

Is addEventListener an event handler?

This way, you can set up code to react to events as they happen on the fly. JavaScript provides an event handler in the form of the addEventListener() method. This handler can be attached to a specific HTML element you wish to monitor events for, and the element can have more than one handler attached.

What is event in addEventListener?

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. Common targets are Element , or its children, Document , and Window , but the target may be any object that supports events (such as XMLHttpRequest ).


2 Answers

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)
like image 195
nandokakimoto Avatar answered Oct 05 '22 22:10

nandokakimoto


This is the typical approach to this problem:-

(function(self) {
  self.chart.addEventListener('create', function() {self.fireEvent('created');}, false);
})(this);
like image 32
AnthonyWJones Avatar answered Oct 05 '22 23:10

AnthonyWJones