I have the following code:
Template.leaderboard.players = function() {
return Players.find({}, {sort: {score: -1, name: 1}});
};
Template.leaderboard.selected_name = function() {
var player = Players.findOne(Session.get("selected_player"));
return player && player.name;
};
And I would like to organize it more clearly like that:
Template.leaderboard = {
players: function() {
return Players.find({}, {sort: {score: -1, name: 1}});
},
selected_name: function() {
var player = Players.findOne(Session.get("selected_player"));
return player && player.name;
}
};
The problem is (I believe from the errors in the console) that this overwrites all the existing methods of the Template.leaderboard object and replaces it.
Is there a possibility to add those methods to the object while keeping existing methods using the kind of notation shown above?
You can either add them one at a time as you've done in your first example, or you can use a method that merges an object with another, such as jQuery's .extend:
$.extend(Template.leaderboard, {
newMethod1: function() {
...
},
newMethod2: function() {
...
}
});
Using the latter method, you also need to be sure that Template.leaderboard actually exists, first!
var Template = Template || {};
Template.leaderboard = Template.leaderboard || {};
Code like the above would be typical if Template is actually defined across multiple JS files, and allows you to keep adding methods without regard to which order the files are actually loaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With