在Ember应用程序中SetTimeout与Ember.run.later?

Bla*_*son 26 handlebars.js ember.js momentjs

在我的车把模板内:

Today's date: {{currentDate}}
Current Time: {{currentTime}}
Run Code Online (Sandbox Code Playgroud)

在我的助手里面:

Ember.Handlebars.registerBoundHelper 'currentDate', (option) ->
  moment().format('LL');

Ember.Handlebars.registerBoundHelper 'currentTime', (option) ->
  moment().format('h:mm:ss a');
Run Code Online (Sandbox Code Playgroud)

我如何每1秒更新一次currentTime到视图?

我已经阅读了Ember的建议Ember.run.later但是我无法弄清楚它的位置以及如何使用这个帮助器来调用它.

Tor*_*ups 53

您可以像使用setTimeout一样使用Ember.run.later

Ember.run.later((function() {
  //do something in here that will run in 2 seconds
}), 2000);
Run Code Online (Sandbox Code Playgroud)

我不确定内部是什么,但我知道集成测试Ember要求你使用run.later(如果你不测试代码不会等待超时完成).


Kin*_*n2k 12

您不希望将超时添加到帮助程序中,您需要将其添加到全局变量中,然后从中进行差异处理.你想要使用Em.run.later它的原因是它会将它注入到运行循环中(Toran所获得的部分).这对测试非常重要.

将时间添加到全局变量

App.ApplicationRoute = Em.Route.extend({
  setupController: function(controller, model){
    this._super(controller, model);
    this.startWatchingTime(controller);
  },
  startWatchingTime: function(controller){
    var self = this;
    controller.set('currentTime', moment());
    Em.run.later(function(){
      self.startWatchingTime(controller);
    }, 1000);
  }
});
Run Code Online (Sandbox Code Playgroud)

将其添加到帮助程序

Ember.Handlebars.helper('time-diff', function(date1, date2, format, options) {
  return date1.diff(date2, format);
});
Run Code Online (Sandbox Code Playgroud)

将它发送给帮助者

{{time-diff  controllers.application.currentTime anotherTime 'seconds'}}
Run Code Online (Sandbox Code Playgroud)

http://emberjs.jsbin.com/UcUrIQa/1/edit


mih*_*hai 6

你想使用Embers.run循环,而不是使用setTimer.

当前(今天)版本的ember需要这种格式context this(更新Toran Billups答案)

this._debouncedItem = Ember.run.later(this, () => {
   debugger;
}, 5000);
Run Code Online (Sandbox Code Playgroud)

我强烈建议保留对later()的响应的引用并在destroy钩子中取消它

destroy() {
   this._super(...arguments);
   Ember.run.cancel(this._debouncedItem);
},
Run Code Online (Sandbox Code Playgroud)