purplelichen
purplelichen

Reputation: 25

How to bind DOM objects to a JS object

I'm working on a simple game and struggling with how to bind my DOM objects to the JS objects that spawn them. This used to be very easy back in the days of Flash - the object and it's visual representation were one and same! What's the best way to do this with JS/HTML? Here's a stripped down example of what I'm trying to do:

<body>

    <div id="pond"></div>

</body>

<script>

    function fish() {
        this.genotype = 'GATTACA';        
        this.phenotype = '<div class="fish" onclick=reveal()></div>';
    }

    shark = new fish();

    $(shark.phenotype).appendTo("#pond");

    function reveal() {
        alert(this.genotype);
    }

</script>

Upvotes: 1

Views: 279

Answers (1)

Barmar
Barmar

Reputation: 780974

Use .data() to associate the object with the DOM element.

function fish() {
  this.genotype = 'GATTACA';
  this.phenotype = '<div class="fish" onclick="reveal(this)">Click to see genotype</div>';
}

shark = new fish();
$(shark.phenotype).data('fish', shark).appendTo("#pond");
function reveal(element) {
  alert($(element).data('fish').genotype);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="pond"></div>

Upvotes: 2

Related Questions