Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a master object in my 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 I loop over my cars and put them in a table. In the table I also have a button that lets me toggle the car as "in use" and "not in use".

How can I associate the DOM Element of every row with its corresponding car, so that if I toggle the "inuse" flag, I can update the master object?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
212 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can actually attach an object directly to a node:

var n = document.getElementById('green-ford-escape');
n.carObject = myGarage.cars[0];
n.onclick = function() {
  doSomethingWith(this.carObject);
}

For the same of removing ambiguity, in some cases, it's more clear write the above event handler to refer to n instead of this:

n.onclick = function() {
  doSomethingWith(n.carObject);
}

You can also refer directly to the object from the attached event:

var n = document.getElementById('green-ford-escape');
n.onclick = function() {
    doSomethingWith(myGarage.cars[0]);
}

In the latter case, myGarage does not have to be global. You can do this and expect it to work correctly:

(function(){

    var myGarage = { /* ... etc ... */ };

    var n = document.getElementById('green-ford-escape');
    n.onclick = function() {
        doSomethingWith(myGarage.cars[0]);
    }

})();

The node's event function will "hold onto" the local variable correctly, effectively creating a private variable.

You can test this in your Chrome/FF/IE console:

var o = {a: 1};
var n = document.createElement('div');
n.innerHTML = "click me";
n.data = o;
n.onclick = function() { n.data.a++; console.log(n.data, o); }
document.body.appendChild(n);

You should see the console log two identical objects with each click, each with incrementing a values.

Beware that setting n.data to a primitive will not create a reference. It'll copy the value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...