I'm just in the early stages of learning Ember, and have run into something puzzling. I'm trying to communicate between two controllers and have their corresponding views update as well.
In a simplified version, I'd like to click a button to fire an event on one controller, which starts a timer on another controller. This works, but the view of the timer is not being updated when the value changes.
Here's what I have:
var App = Ember.Application.create();
App.Route = Ember.Route.extend({
events: {
startTimer: function(data) {
this.get('container').lookup('controller:Timer').start();
}
}
});
App.ApplicationController = Ember.Controller.extend({
actionWord: 'Start',
toggleTimer: function() {
var timer = this.get('container').lookup('controller:Timer');
if(timer.get('running')) {
timer.stop();
} else {
timer.start();
this.set('actionWord', 'Stop');
}
}
});
App.TimerController = Ember.Controller.extend({
time: 0,
running: false,
timer: null,
start: function() {
var self = this;
this.set('running', true);
this.timer = window.setInterval(function() {
self.set('time', self.get('time') + 1);
console.log(self.get('time'));
}, 1000);
},
stop: function() {
window.clearInterval(this.timer);
this.set('running', false);
this.set('time', 0);
}
});
and for the templates:
<script type="text/x-handlebars">
{{ render "timer" }}
<button {{action toggleTimer }} >{{ actionWord }} timer</button>
</script>
<script type="text/x-handlebars" data-template-name="timer">
{{ time }}
</script>
UPDATE:
Forgot to mention that if you open the console, you can see the time is being updated inside of the TimeController function, it's just not showing up in the view.
Also, calling the start action on the TimerController directly correctly updates the view.
Thanks!
You were using an out-of-date version of Ember.
I've updated your fiddle to the Ember rc3. Also I've replaced instances of container.lookup
with the correct methods. The container
is pretty much a private object.
http://jsfiddle.net/3bGN4/255/
window.App = Ember.Application.create();
App.Route = Ember.Route.extend({
events: {
startTimer: function(data) {
this.controllerFor('timer').start();
}
}
});
App.ApplicationController = Ember.Controller.extend({
actionWord: 'Start',
needs: ["timer"],
toggleTimer: function() {
var timer = this.get('controllers.timer');
if(timer.get('running')) {
timer.stop();
} else {
timer.start();
this.set('actionWord', 'Stop');
}
}
});
App.TimerController = Ember.Controller.extend({
time: 0,
running: false,
timer: null,
start: function() {
var self = this;
this.set('running', true);
this.timer = window.setInterval(function() {
self.set('time', self.get('time') + 1);
console.log(self.get('time'));
}, 1000);
},
stop: function() {
window.clearInterval(this.timer);
this.set('running', false);
this.set('time', 0);
}
});