I'm trying to build a simple game using Meteor. I have a collection of 'games', where each game has a state which is a 7x7 array of data used for a grid.
I have 3 templates, the game table, a row of that table and a cell of that table:
<template name="game">
{{#with gameObject}}
{{name}}
<table id="gameGrid">
{{#each state}}
{{> gameRow}}
{{/each}}
</table>
{{/with}}
</template>
<template name="gameRow">
<tr>
{{#each this}}
{{> gameSpace}}
{{/each}}
</tr>
</template>
<template name="gameSpace">
<td class="game-grid-space colour-{{this}}" ></td>
</template>
The GameObject context in that first one is a single game from my collection - it has a name and a state which is the 7x7 array.
To deal with click events on each of the elements, I'm assigning them a data attribute as they render, like so:
currentSpaceId = 0;
Template.gameSpace.rendered = function(){
if(!this.rendered){
this.$("td").data("spaceId", currentSpaceId);
currentSpaceId++;
this.rendered = true;
}
};
I'm not using a session here because it doesn't seem necessary but I've tried with it and have the same issue.
This is basically labelling the 49 squares from 0-48 as they render, ie in order. Then I can very easily translate that into their grid position and identify the clicked square.
The problem is that on any state change Meteor seems to re-render the whole DOM and re-call that rendered method for every square. That of course means their data attribute gets way out of whack, since it just keeps iterating. As far as I can tell the solution would seem to be if I could somehow pin those data attributes so the newly rendered dom just keeps them instead of rewriting them.
All I really want to do is change a class on each grid space based on its value in the state array (values being r=red, b=blue etc, but just being used as CSS classes) - so if what I'm doing is completely insane that would also be really helpful feedback! I'm really having trouble figuring out how I should be identifying which is clicked though if not like this.
Thanks in advance for any help, and if I can provide any clarification I'd be happy to.