2013-05-10 153 views
0

我只是在学习Ember的早期阶段,并遇到了令人费解的事情。 我正试图在两个控制器之间进行通信,并更新其相应的视图。Ember.js - 控制器和他们的意见之间的沟通

在一个简化版本中,我想点击一个按钮来触发一个控制器上的事件,该控制器在另一个控制器上启动一个定时器。这有效,但计时器的视图在值更改时未更新。

这是我有:

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); 
    } 

}); 

和模板:

<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> 

http://jsfiddle.net/mAqYR/1/

UPDATE:

忘了提,如果你打开控制台,可以看到TimeController函数内部正在更新的时间,它只是没有显示在视图中。

另外,直接在TimerController上调用start操作可以正确更新视图。

谢谢!

回答

3

您使用的是Ember的过期版本。 我已将您的小提琴更新为Ember rc3。我还用正确的方法替换了container.lookup的实例。 container几乎是一个私人对象。

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); 
    } 
}); 
+0

那伟大工程,谢谢! 现在如果我想访问另一条路线,该怎么办?有没有像'this.routeFor('timer');'或'this.get('route.timer');'? 这是全部记录在某处? – rainbowFish 2013-05-10 16:34:21

+0

从另一条路线访问路线在概念上并没有多大意义,您想实现什么目标? – 2013-05-10 19:36:23