javascript 如何定期更新 Ember 的模型(例如在 setInterval 中)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21708931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update Ember's model periodically (such as in setInterval)?
提问by Edy Bourne
I have an Ember application whose model comes from an Ajax call. The first call works great, I have the model hook of the Ember.Routereturn a promise to the Ajax call that retrieves the data to be displayed.
我有一个 Ember 应用程序,其模型来自 Ajax 调用。第一次调用效果很好,我有模型钩子Ember.Route返回一个承诺给 Ajax 调用,该调用检索要显示的数据。
But this data changes frequently in the backend, and I want to have the webapp poll the server periodically, say, every 5 seconds, and update or, even better, swap the model data entirely with the newly retrieved one.
但是这个数据在后端经常变化,我想让 webapp 定期轮询服务器,比如每 5 秒,然后更新,或者更好的是,将模型数据完全与新检索到的数据交换。
What is the appropriate way of doing that with Ember.js? I'm new to Ember so I'm a bit lost with this.
使用 Ember.js 执行此操作的合适方法是什么?我是 Ember 的新手,所以我对此有点迷茫。
回答by chopper
I think this is a good use case for Ember.run.later, which limits the frequency of function calls.
我认为这是一个很好的用例Ember.run.later,它限制了函数调用的频率。
You could just add a refresh to your model, similar to this:
您可以为模型添加刷新,类似于:
App.Model = DS.Model.extend({
poll: function() {
var _this = this;
Ember.run.later( function() {
_this.reload();
_this.poll();
}, 500);
}.observes('didLoad'),
});
回答by melc
If you are not using Ember data you can simply add a recursive setTimeoutor setIntervalin you controller and set the modelproperty. Here is a simple example setting the model from a UI event.
如果您不使用 Ember 数据,您可以简单地添加一个递归setTimeout或setInterval在您的控制器中并设置model属性。这是一个从 UI 事件设置模型的简单示例。
If you are using ember-data I think the following threads have more accurate solutions:
如果您使用的是 ember-data,我认为以下线程有更准确的解决方案:

