Ember计算属性,观察当前时间

时间:2021-08-06 21:28:15

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?"),

2 个解决方案

#1


8  

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

ember-time存储库包含了您尝试执行的操作的一个很好的示例。

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:

他们通过车把助手使用自定义视图。该视图设置了一个tick函数,该函数每秒通过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...

notifyPropertyChange调用告诉视图属性已更改,因此触发重新呈现...

#2


1  

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

#1


8  

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

ember-time存储库包含了您尝试执行的操作的一个很好的示例。

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:

他们通过车把助手使用自定义视图。该视图设置了一个tick函数,该函数每秒通过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...

notifyPropertyChange调用告诉视图属性已更改,因此触发重新呈现...

#2


1  

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