I've generalized my lack of understanding of the situation to this small problem. Here's what I think I know so far:
I have an object myDog
(a global variable). Dog
has a member variable el
that is an html element; because it's an element, I can add event listeners to it. So, when you click on myDog.el
, it logs to the console the values of this.name
and myDog.name
. As expected because of scope, this.name
is undefined and myDog.name
is 'tye'. this
inside of Dog.speak
when invoked by the click event listener refers to the element that was clicked, the member variable el
, not the object Dog
. Since myDog
is a global variable, it's able to pick back up regardless of the function's scope and get to myDog.name
just fine.
See code below:
function Dog(name,id) {
this.name = name ? name : "spot";
this.id = id ? id : "dog";
this.el = document.getElementById(this.id); // given there is a div with a matching
this.el.addEventListener("click",this.speak); // ignore IE for simplicity (attachEvent has its own 'this' scope issues)
}
Dog.prototype = {
speak: function() {
console.log("this.name: "+this.name+"\nmyDog.name: "+myDog.name);
}
};
var myDog = new Dog("tye","dog1");
So... my questions are
1) What are some strategies for attaching objects to html elements, so that I can go from this.el
back to myDog
(this.el
's owner) without myDog
being a global variable?
2) Are global variables in this case a necessary evil? And if so, what are so good strategies in this case to gracefully use them? For example, what if I wanted 100 dogs instantiated? How would I handle all those global variables in Dog.speak
?
Here's a jsfiddle version if you want to play with it: http://jsfiddle.net/chadhutchins/Ewgw5/
You can try something like this:
Through the magic of closures the anonymous function I've added within
addEventListener()
has access to the scope of the containing function even after the containing function returns, so it is able to useself
which holds a reference to the original object saved fromthis
whenDog()
was called as a constructor.EDIT: Sorry, I didn't directly address the questions you numbered (1) and (2), but as you can see you don't need global variables to fix this this issue. With the technique I described you could instantiate 100 dogs and they'd all work. (Well, they'd all speak anyway: they'd all work if you added
Dog.prototype.work = function() { }
.)Since you're using
.addEventListener()
, I'd suggest taking advantage of a feature of it that few people seem to know about... making yourDog
object implement theEventListener
interface.This establishes a very clean relationship between your
Dog
data and its associated element.Only minor changes are required. Code first... explanation below.
DEMO: http://jsfiddle.net/Ewgw5/1/
So all I did was pass
this
in the constructor toaddEventListener()
instead of passing a function, and then I added ahandleEvent()
method toDog.prototype
.Now when a
"click"
event occurs, it will invoke thehandleEvent()
method. The value ofthis
in that method will be yourDog
instance. So from there you can call whatever method(s) you need.Because you made the element a property of
this
, you can access the element viathis.el
. But that's technically not even necessary, since the element is also available via theevent
object asevent.currentTarget
.Thankfully no!
This behavior should be part of your shim for
.addEventListener()
.https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
This way is preferable because it doesn't require allocating a scope in order to pass the binding. Scope allocation is one of the more costly things in JS.