Olivier Liechti
Olivier Liechti

Reputation: 3188

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

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

Upvotes: 0

Views: 844

Answers (2)

Mike Grassotti
Mike Grassotti

Reputation: 19050

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/

Upvotes: 2

Olivier Liechti
Olivier Liechti

Reputation: 3188

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

Upvotes: 0

Related Questions