I'm not sure that I understand how to keep my web application reactive with Meteor.
I have this very simple template
<body>
{{> simple}}
</body>
<template name="simple">
Counter: {{counter}} <br/>
<button>Increase</button>
</template>
And client side script
var counter = 0;
Template.simple.counter = function () {
return counter;
}
Template.simple.events({
'click button': function () {
counter++;
console.log("counter is ", counter);
Meteor.flush();
}
});
When clicking on button I can see in console that counter
variable is increasing properly but nothing happens on UI. Why? I thought it's exactly what Meteor.flush()
is intended to do.
I'm not sure that I understand how to keep my web application reactive with Meteor.
I have this very simple template
<body>
{{> simple}}
</body>
<template name="simple">
Counter: {{counter}} <br/>
<button>Increase</button>
</template>
And client side script
var counter = 0;
Template.simple.counter = function () {
return counter;
}
Template.simple.events({
'click button': function () {
counter++;
console.log("counter is ", counter);
Meteor.flush();
}
});
When clicking on button I can see in console that counter
variable is increasing properly but nothing happens on UI. Why? I thought it's exactly what Meteor.flush()
is intended to do.
3 Answers
Reset to default 4The UI isn't reactive all by itself, you need to use one of Meteor's reactive items. In this case, you probably want to use Session
. Try the following, instead of the second script you pasted:
Session.set('counter', 0); // Initialize a *reactive* variable
Template.simple.counter = function () {
return Session.get('counter'); // This will automatically update, because Session is reactive
}
Template.simple.events({
'click button': function () {
Session.set('counter', Session.get('counter') + 1);
}
});
You could also build your own reactive data source:
if (Meteor.isClient) {
Sort = {
sort: 1,
dep: new Deps.Dependency,
get: function () {
this.dep.depend();
return this.sort;
},
toggle: function () {
this.sort *= -1;
this.dep.changed();
}
};
Template.leaderboard.players = function () {
return Players.find({}, {sort: {score: Sort.get(), name: 1}});
};
Template.leaderboard.events({
'click input.sort': function () {
Sort.toggle();
}
});
}
Recent versions of Meteor provides the reactive-var
package, see here : http://docs.meteor./#/full/reactivevar_pkg
To use ReactiveVar, add the reactive-var package to your project by running in your terminal:
meteor add reactive-var