Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update Ember's model periodically (such as in setInterval)?

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.Route return a promise to the Ajax call that retrieves the data to be displayed.

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.

What is the appropriate way of doing that with Ember.js? I’m new to Ember so I’m a bit lost with this.

like image 297
Edy Bourne Avatar asked Feb 11 '14 17:02

Edy Bourne


2 Answers

I think this is a good use case for Ember.run.later, which limits the frequency of function calls.

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'),
});
like image 138
chopper Avatar answered Nov 20 '22 08:11

chopper


If you are not using Ember data you can simply add a recursive setTimeout or setInterval in you controller and set the model property. Here is a simple example setting the model from a UI event.

If you are using ember-data I think the following threads have more accurate solutions:

  • Ember model reloading in interval
  • How to reload an ember data record?
like image 44
melc Avatar answered Nov 20 '22 07:11

melc