So, im really new to both JavaScript and Meteor, so I only know a handful of things.
Learning both, JavaScript and Meteor I set myself the challenge to make a 3 by 3 field of with individual counters in them, that count, if you click the cell.
I reached my first goal: http://9fields.meteor.com/
The second goal I set for myself was to try to make it easily expandable. Say, i want to make the same field but 7x7.
Every cell has its own template.
<template name="zelle1">
<td class="box">
<p class="textinbox">{{counter}}</p>
</td>
</template>
Every cell has its own counter and every cell has one event handler and one helper to register a click
Template.zelle1.helpers({
counter: function () {
return Session.get("counter1");
}
});
Template.zelle1.events({
"click td": function() {
return Session.set("counter1", Session.get("counter1")+1);
}
});
I then pasted the code 8 more times and replaced the numbers.
The only thing that i feel reaches my criteria for the second goal is the way i create the table.
<table>
{{#each zellen}}
{{#if this.newrow}}
<tr></tr>
{{> UI.dynamic template=this.name}}
{{else}}
{{> UI.dynamic template=this.name}}
{{/if}}
{{/each}}
</table>
in combination with this Array (array is the right word?)
Template.body.zellen = [
{name: "zelle1", newrow: false},
{name: "zelle2", newrow: false},
{name: "zelle3", newrow: false},
{name: "zelle4", newrow: true},
{name: "zelle5", newrow: false},
{name: "zelle6", newrow: false},
{name: "zelle7", newrow: true},
{name: "zelle8", newrow: false},
{name: "zelle9", newrow: false},
];
My question: Do i have to make 9 Templates and 9 helpers and 9 events for those 9 fields? Meaning that if i want to make a 7x7 field i need to paste the code 49 times? Or is there a more efficient way to do this?
Already Thank you for reading through this!
Let's propose a third way to approach the problem :) You can always use something like the following to get multiple Session variables filled:
Or perhaps use an array inside the
Session
. It can even be an array of objects:This is basically the same approach as using
ReactiveVar
, only that you are using a global variable (Session
) instead of a scoped one. You entire application will be able to access the things you store withinSession
.Also, you should perhaps not use a template bound to each field, but iterate using
{{#each}}
The trouble here is that you have no control over which cell you are rendering currently, so you need to add an index to each of the
{{#each}}
runs. This is why I suggest a new global helperwithIndex
:You can use the new
index
just like any other field from the array. You will need it to determine which number was clicked and where to increase the counter. I've used thetd
'sid
value to store the index of which cell was clicked.