Editing and deleting games
Now that we can create games it's time to make them editable. Here is what I came up with (not the best UI design I know):
But it's functional. You can update the scores easily, and when the game is finished you just hit the 'Finish' button. Feel free to try and code this yourself and then check with my code after:
client/views/game.html
<template name="game">
<li>
{{#if completed}}
{{teams.[0].name}} ({{teams.[0].score}})
vs
{{teams.[1].name}} ({{teams.[1].score}})
{{else}}
{{teams.[0].name}}
(<a class="one-minus" href="#">-</a>
{{teams.[0].score}}
<a class="one-plus" href="#">+</a>)
vs
{{teams.[1].name}} (
<a class="two-minus" href="#">-</a>
{{teams.[1].score}}
<a class="two-plus" href="#">+</a>)
<a href="#" class="finish-game">Finish</a>
<a href="#" class="delete-game">Delete</a>
{{/if}}
</li>
</template>
client/views/game.js
Template.game.events({
"click a.finish-game": function(e, tpl){
e.preventDefault();
Games.update({_id: this._id}, {$set: {completed: true}});
},
"click a.delete-game": function(e, tpl){
e.preventDefault();
Games.remove(this._id);
},
"click a.one-plus": function(e, tpl){
e.preventDefault();
Games.update({_id: this._id}, {$inc: {"teams.0.score": 1}});
},
"click a.two-plus": function(e, tpl){
e.preventDefault();
Games.update({_id: this._id}, {$inc: {"teams.1.score": 1}});
},
"click a.one-minus": function(e, tpl){
e.preventDefault();
Games.update({_id: this._id}, {$inc: {"teams.0.score": -1}});
},
"click a.two-minus": function(e, tpl){
e.preventDefault();
Games.update({_id: this._id}, {$inc: {"teams.1.score": -1}});
}
});
We have a new operator with $inc
, which stands for 'increment'. But it also acts as a decrement if you provide a negative number. We also use dot notation to reach our 'score' attribute ("teams.0.score"
). So 0
refers to the index of the teams array.
We can simplify this code some more by setting some information on the DOM elements and using this information in the event handler:
client/views/game.js
Template.game.events({
"click a.finish-game": function(e, tpl){
e.preventDefault();
Games.update({_id: this._id}, {$set: {completed: true}});
},
"click a.delete-game": function(e, tpl){
e.preventDefault();
Games.remove(this._id);
},
"click a.score": function(e, tpl){
e.preventDefault();
var data = $(e.currentTarget).data();
var update = {$inc: {}};
var selector = "teams." + data.index + ".score";
update.$inc[selector] = data.inc;
Games.update({_id: this._id}, update);
}
});