1
votes

I have a custom ClockService object that i inject into my application controller like so (taken from ember js cookbook):

App.ClockService = Em.Object.extend({
  pulse: Ember.computed.oneWay('_seconds').readOnly(),
  tick: function () {
    var clock = this;
    Ember.run.later(function () {
      var seconds = clock.get('_seconds');
      if (typeof seconds === 'number') {
        clock.set('_seconds', seconds + (1/4));
      }
    }, 250);
  }.observes('_seconds').on('init'),
  _seconds: 0
});

Ember.Application.initializer({
  name: 'clockServiceInitializer',
  initialize: function(container, application) {
    container.register('clock:service', App.ClockService);
    application.inject('controller:application', 'clock', 'clock:service');
  }
});

And i create a computed property in the Application Controller from the pulse property in clock service:

App.ApplicationController = Em.ObjectController.extend({
    currentTime: function(){
        return moment().format('MMMM Do YYYY, h:mm:ss a');
    }.property('clock.pulse')
});

The timestamp (using Momentjs) is viewable in the main application on screen but it does not redraw with the pulse. Am i doing something wrong?

UPDATE:

Applying Kingpins update below, I now have the following working solution:

App.ApplicationController = Em.Controller.extend({
setTime: function() {
    var time = moment().format('MMMM Do YYYY, h:mm:ss a');
    this.set('currentTime', time);
    Em.run.later(this, this.setTime, .9999);
}.on('init'),

currentTime: undefined
});
1

1 Answers

2
votes

You're never fetching pulse so Ember is never computing it, and as such is never seeing it change...

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

You could also use the crazy _seconds item, and since it's being set it will update

http://emberjs.jsbin.com/kajuqeja/2/edit

Either way, this seems like a ton of overhead, firing a property change every 1/4 second etc. If you really want to keep this in the page I'd up that to .99 second, and maybe ditch the whole clock service and set up a simple Ember.run.later for your time update.

http://emberjs.jsbin.com/kajuqeja/3/edit