Skip to content

Instantly share code, notes, and snippets.

@jordpo
Last active August 29, 2015 14:26
Show Gist options
  • Save jordpo/6d01902ca0bda63b942f to your computer and use it in GitHub Desktop.
Save jordpo/6d01902ca0bda63b942f to your computer and use it in GitHub Desktop.
Ember Polling Mixin for Routes
// an alternative approach to my gist below
import Ember from 'ember';
const get = Ember.get;
const set = Ember.set;
const later = Ember.run.later;
const cancel = Ember.run.cancel;
export default Ember.Mixin.create({
pollInterval: 5000, // default value in ms
poll(...items) {
return items.map((item) => {
const timer = later(this, function() {
get(this, `controller.model.${item[0]}`).reload().then(() => {
if (!get(this, `controller.model.${item[0]}.${item[1]}`)) {
this.poll(item);
}
});
}, get(this, 'pollInterval'));
set(this, `timer-${item[0]}`, timer);
return timer;
});
},
stopPoll(...models) {
return models.map((model) => {
return cancel(get(this, `timer-${model}`));
});
}
});
// use case
activate() {
// provide the model name and the property where when true we stop polling
// if no property provided, it will continuously poll
// must always be list of arrays: this.poll([model1], [model2, property], etc)
this.poll(['productBankAccount', 'hasBeenProvided']);
},
deactivate() {
this.stopPoll('productBankAccount');
},
import Ember from 'ember';
const get = Ember.get;
const set = Ember.set;
const later = Ember.run.later;
const cancel = Ember.run.cancel;
export default Ember.Mixin.create({
pollingTime: 5000, // default value in ms
continuePoll: false, // reset this in the callback of the poll method
timer: null,
poll(cb) {
const continuePoll = get(this, continuePoll);
const timer = later(this, function() {
if (continuePoll) {
cb();
this.poll(cb);
}
}, get(this, pollingTime));
set(this, 'timer', timer);
},
stopPoll() {
return cancel(get(this, timer));
}
});
// use case
activate() {
this.poll(() => {
get(this, 'controller.model.productBankAccount').reload().then(continuePollIf);
});
},
deactivate() {
this.stopPoll();
},
continuePollIf() {
const continuePoll = !get(this, 'controller.model.productBankAccount.hasBeenProvided');
set(this, 'continuePoll', continuePoll);
}
@jordpo
Copy link
Author

jordpo commented Aug 1, 2015

I think we should rely on Ember.run as much as possible rather than window.setInterval or window.setTimeout to ensure computed properties are updated properly with each execution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment