Reputation: 866
I am trying to build a simple counter that will count from 0 to 100 on page load.Here is some that i came out with but does not work. I'll appreciate all the help thanks
App.AboutController = Ember.ObjectController.extend({
count: 0,
content: 0,
counterUp: function() {
var count = this.get('count') + 1;
this.set('count', count);
this.set('content', count % 100);
}
});
Upvotes: 2
Views: 492
Reputation: 2661
This seems like a great candidate for a component:
component
App.TimerCounterComponent = Ember.Component.extend({
tick: function() {
this.incrementProperty('count');
if (Ember.isEqual(this.get('count'), 100)) {
this.killCounter();
} else {
this.scheduleTick();
}
},
scheduleTick: function() {
this._counter = Ember.run.later(this, 'tick', 600);
},
setup: function() {
this.set('count', 0);
this.scheduleTick();
}.on('didInsertElement'),
killCounter: function() {
Ember.run.cancel(this._counter);
}.on('willDestroyElement')
});
component template
Count: {{count}}
then in any template you want to use the component:
{{timer-counter}}
EDIT: tidied up the jsbin code a bit
Bonus round: full js-bin example
Upvotes: 3
Reputation: 713
As things are, your counterUp
method has been declared and defined, but is never called. You have to call it in an appropriate hook. In http://emberjs.jsbin.com/wuxesosadi/1/edit?html,css,js,output you find an example that counts whenevere you click on the number.
You want to count "on page load" - a full page loade which restarts the application will always reset the counter. If you mean a transition into the route, http://emberjs.jsbin.com/wuxesosadi/4/edit?html,css,js,output would be a working example.
That said, for real world problems you would probably have a counter service or the data in a model. The controller should only hold presentation logic. And even though the controller is held in memory and re-used (as a singleton), this feels very wrong. Then again, as an example of how things work, this is perfectly valid.
Upvotes: 1
Reputation: 645
You cannot make the counting on controller's property because it would always re-initialize and you would have always zero. You can access the application controller however and this way the property will not reset:
// better use Controller because ObjectController is getting deprecated
App.AboutController = Ember.Controller.extend({
needs: ['application'],
count: Ember.computed.alias('controllers.application.count'),
content: Ember.computed.alias('controllers.application.content'),
counterUp: (function() {
count = this.get('count') + 1 || 1;
this.set('count', count);
this.set('content', count % 100);
}).on('init')
});
If you want, you can initialize count and content properties like this:
App.ApplicationController = Ember.Controller.extend({
count: 0,
content: 0
})
If you have used the proxying behavior of ObjectController use can replace Controller with it.
Upvotes: 1