I have an ember application that consume a Django Rest Api. Data on backend changes frequently(new records are created/updated every minute). How can I update my data on ember app? I think this is a common pattern in SPA application but I didn't find nothing in official doc that says what is the best approach to this pattern.
After some searches i found two patterns:
- Websockets: this is the only real-time solution but this is to complex to implement because of using django on backend and lack of knowledge
- Old-style interval polling: this is not real-time but good for my needs.
I tried to implement a long polling object according http://ift.tt/1iXPFjM:
I'm using ember-cli and ember-data.
app/util/pollster.js
import Ember from "ember";
var Pollster = Ember.Object.extend({
interval: function() {
return 5000; // Time between polls (in ms)
}.property().readOnly(),
// Schedules the function `f` to be executed every `interval` time.
schedule: function(f) {
return Ember.run.later(this, function() {
f.apply(this);
this.set('timer', this.schedule(f));
}, this.get('interval'));
},
// Stops the pollster
stop: function() {
Ember.run.cancel(this.get('timer'));
},
// Starts the pollster, i.e. executes the `onPoll` function every interval.
start: function() {
this.set('timer', this.schedule(this.get('onPoll')));
},
onPoll: function(){
// Issue JSON request and add data to the store
}
});
export default Pollster;
app/routes/test.js
setupController: function(controller, model) {
if (Ember.isNone(this.get('pollster'))) {
this.set('pollster', Pollster.create({
controller: controller
onPoll: function() {
this.controller.set('model', this.controller.store.find('mymodel',}));
}
}));
}
this.get('pollster').start();
},
deactivate: function() {
this.get('pollster').stop();
},
.....
Q1: It seems to work but is this the best approach? Q2: Also, when the 'onPoll' function is execute i see a 'flickering' on my template. I think it's due to the fact that records of the model are deleted and recreated but it's very annoying. It's possible to avoid this behavior? Q3: where to store custom objects in emberjs? Like Pollster?
Aucun commentaire:
Enregistrer un commentaire