是否有可能通过ember.js定期通知观察者计算的属性? [英] Is it possible to periodically notify observers of a computed property with ember.js?

查看:94
本文介绍了是否有可能通过ember.js定期通知观察者计算的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现以下简单的用例:有一个ember模板定期显示当前时间。我找到了一种办法,但我怀疑有更好/更简单的方法。这是我做的:

I am trying to implement the following simple use case: have an ember template periodically display the current time. I have found a way to do it, but I suspect that there is a better/simpler way. Here is what I do:


  1. 在我的控制器中,我有一个dirtyFlag属性。我使用这个方法来触发观察者的通知(因此我的模板)。

  1. In my controller, I have a dirtyFlag property. I use this as a trick to trigger the notification of observers (hence of my template).

当应用程序准备就绪时,我会定时启动一个定时器更改 dirtyFlag属性的值。

When the application is ready, I start a timer to periodically change the value of the dirtyFlag property.

我想避免使用dirtyFlag属性,基本上我想知道是否有一种方式来表达类似于的所有观察者在currentTime计算属性应更新并获取此属性的新值

I would like to avoid using the dirtyFlag property, and essentially I am wondering if there is a way to express something like all observers on the currentTime computed property should update and get the new value for this property.

var App = Ember.Application.create({
    ready: function() {
        setInterval(function() {
            console.info("Updating clock (" + new Date() + ")");
            App.theClockController.set('dirtyFlag', new Date());    
        }, 1000)
    }
});

App.ClockController = Ember.ObjectController.extend({
    dirtyFlag: null,
    currentTime: function() {
        return new Date();
    }.property('dirtyFlag')
});


推荐答案

我建议使用标准属性来存储缓存时间值,然后根据需要绑定到它。例如:

I would recommend using a standard property to store the cached time value and then binding to it as needed. For example:

App = Ember.Application.create({
  ready: function() {
      setInterval( function() {
            console.info("Updating clock (" + new Date() + ")");
            App.set('currentTime', new Date());
      }, 1000)
  }
});

App.ClockController = Ember.Controller.extend({
  currentTimeBinding: Ember.Binding.oneWay('App.currentTime')
});

请看这个jsfiddle一个工作示例: http://jsfiddle.net/nzLyh/1/

See this jsfiddle for a working example: http://jsfiddle.net/nzLyh/1/

这篇关于是否有可能通过ember.js定期通知观察者计算的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆