javascript - How to Associate an Object with a DOM Element -
i have master object in js setup, i.e.:
var mygarage = { cars: [ { make: "ford", model: "escape", color: "green", inuse: false }, { make: "dodge", model: "viper" color: "red", inuse: true }, { make: "toyota", model: "camry" color: "blue", inuse: false } ] }
now loop on cars , put them in table. in table have button lets me toggle car "in use" , "not in use".
how can associate dom element of every row corresponding car, if toggle "inuse" flag, can update master object?
i'd suggest considering addeventlistener
, , constructor conforms objects eventlistener
interface.
that way can have nice association between object, element, , handlers.
to this, make constructor that's specific data.
function car(props) { this.make = props.make; this.model = props.model; // , on... this.element = document.createelement("div"); // or whatever document.body.appendchild(this.element); // or whatever this.element.addeventlistener("click", this, false); }
then implement interface:
car.prototype.handleevent = function(e) { switch (e.type) { case "click": this.click(e); // add other event types if needed } }
then implement .click()
handler on prototype.
car.prototype.click = function(e) { // this.element... this.element.style.color = "#f00"; // ...and other properties this.inuse = !this.inuse }
so can loop on array, , make new car
object each item, , it'll create new element , add listener(s).
mygarage.cars.foreach(function(obj) { new car(obj) })
Comments
Post a Comment