Ben
Ben

Reputation: 16534

Ember computed property that observes current time

Is there a way to have a computed property observe the current time (for use in a timestamp)?

For example in my controller I might have a method that looked something like this:

formatLastUpdated:function() {
    return moment(this.get("model.update_ts")).fromNow();
}.property("model.update_ts", "date.now?"),

Upvotes: 6

Views: 2330

Answers (2)

vitch
vitch

Reputation: 3214

The ember-time repository includes a good example of what you are trying to do.

They use a custom view via a handlebars helper. The view sets up a tick function which is called every second via Ember.run.later:

didInsertElement: function() {
  this.tick();
},
tick: function() {
  var nextTick = Ember.run.later(this, function() {
    this.notifyPropertyChange('value');
    this.tick();
  }, 1000);
  this.set('nextTick', nextTick);
},
willDestroyElement: function() {
  var nextTick = this.get('nextTick');
  Ember.run.cancel(nextTick);
}

The notifyPropertyChange call tells the view that the property has changed and so triggers the re-render...

Upvotes: 8

Kingpin2k
Kingpin2k

Reputation: 47367

Agree with Scott completely. That being said, you could create a global property that you update once a minute or so with the latest time so you are working with a subset of time.

I would store it on the application controller, then use a needs from other controllers. Here's an example.

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

Upvotes: 1

Related Questions