最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ember computed property that observes current time - Stack Overflow

programmeradmin3浏览0评论

Is there a way to have a puted 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?"),

Is there a way to have a puted 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?"),
Share Improve this question edited Dec 21, 2013 at 8:10 JJJ 33.2k20 gold badges94 silver badges103 bronze badges asked Dec 21, 2013 at 8:07 BenBen 16.5k24 gold badges82 silver badges122 bronze badges 2
  • What are you trying to achieve? You don't want to be observing time, as it is continually changing. If it were possible to do this, your javascript would be stuck in a continuous loop of just updating that property, and never have enough time (no pun intended) to do anything else. I think if you explain what the desired oute is, there will be a better way. – Scott Commented Dec 21, 2013 at 11:53
  • Yeah just looking for my las updated timestamp which is relative(using moment.js) to stay current. I'll try kingpins answer – Ben Commented Dec 21, 2013 at 19:13
Add a ment  | 

2 Answers 2

Reset to default 8

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...

Agree with Scott pletely. 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./Elibefem/1/edit

发布评论

评论列表(0)

  1. 暂无评论