"1) What are some strategies for attaching objects to html elements..."
Since you're using .addEventListener()
, I'd suggest taking advantage of a feature of it that few people seem to know about... making your Dog
object implement the EventListener
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/
function Dog(name,id) {
this.name = name ? name : "spot";
this.id = id ? id : "dog";
this.el = document.getElementById(this.id);
// ---------------------------------v----no function!
this.el.addEventListener("click", this);
}
Dog.prototype = {
// Implement the `EventListener` interface
handleEvent: function(event) {
switch (event.type) {
case "click": return this.speak();
}
},
speak: function() {
console.log("this.name: "+this.name+"
myDog.name: "+myDog.name);
}
};
var myDog = new Dog("tye","dog1");
So all I did was pass this
in the constructor to addEventListener()
instead of passing a function, and then I added a handleEvent()
method to Dog.prototype
.
Now when a "click"
event occurs, it will invoke the handleEvent()
method. The value of this
in that method will be your Dog
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 via this.el
. But that's technically not even necessary, since the element is also available via the event
object as event.currentTarget
.
"2) Are global variables in this case a necessary evil..."
Thankfully no!
This behavior should be part of your shim for .addEventListener()
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…