Is it possible to periodically notify observers of a computed property with ember.js?

天涯浪子 提交于 2019-12-25 07:37:16

问题


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. In my controller, I have a dirtyFlag property. I use this as a trick to trigger the notification of observers (hence of my template).

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

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

回答1:


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

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




回答2:


I have found one other way to do it (not sure that it is the best however). I call the propertyWillChange and propertyDidChange methods:

var App = Ember.Application.create({
    ready: function() {
        console.info("Preparing the timer...");
        setInterval(function() {
            console.info("Updating clock (" + new Date() + ")");
            App.theClockController.propertyWillChange('currentTime');
            App.theClockController.propertyDidChange('currentTime');
        }, 1000)
    }
});


来源:https://stackoverflow.com/questions/14232665/is-it-possible-to-periodically-notify-observers-of-a-computed-property-with-embe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!