views:

81

answers:

2

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.

+3  A: 

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)
nandokakimoto
Yes, this is the normal idiom. The closure variable is often called `that` or `self` (although I don't think the latter's a great idea as `self` has an established — though useless — existing meaning in JavaScript).
bobince
OK that works. Out of interest is there another way other than setting a variable to this. For example using closure?
Jonnio
@bobince: I prefer `self`. `self` is exposed by `window` a reference to itself. I'm quite happy to reuse the identifier in other scopes. It seems to me to carry the right meaning and doesn't clash with that it means when `self` happens to be the window either.
AnthonyWJones
+1  A: 

This is the typical approach to this problem:-

(function(self) {
  self.chart.addEventListener('create', function() {self.fireEvent('created');}, false);
})(this);
AnthonyWJones
I prefer `var self = this;`. Creating a function and then executing it whilst passing `this` as the parameter seems a little overboard - the code is slightly longer too ;-)
Andy E
@Andy: Yes I often do that too when the code exists in a small execution context. However the above is the standard approach which works in a wider variety of scenarios. The scope of the `self` identifier is limited only to the closure, there is no danger that subsequent code might modify the value contained in it before the event fires. This is not true of the `var self = this;` approach.
AnthonyWJones