"1) What strategies exist for binding objects to html elements ..."
Since you use .addEventListener() , I would suggest using a feature that few people know about ... your Dog object implements the EventListener interface.
This establishes a very clean relationship between your Dog data and its associated item.
Only minor changes are required. First code ... 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+"\nmyDog.name: "+myDog.name); } }; var myDog = new Dog("tye","dog1");
So, all I did was pass this in the constructor to addEventListener() instead of passing the function, and then I added the handleEvent() method to Dog.prototype .
Now, when the "click" event occurs, it calls the handleEvent() method. The value of this in this method will be your instance of Dog . Therefore, from there you can call any method (s) that you need.
Since you made the element the this property, you can access the element through this.el But this is technically not even necessary, since the element is also accessible through the event object as event.currentTarget .
"2) Are global variables in this case a necessary evil ..."
Fortunately not!
This behavior should be part of your padding for .addEventListener() .
user1106925
source share