Skip to content

Instantly share code, notes, and snippets.

@ankushdharkar
Last active July 20, 2018 23:26
Show Gist options
  • Save ankushdharkar/9fb2effa66c92bfcd8d14379f03ab43e to your computer and use it in GitHub Desktop.
Save ankushdharkar/9fb2effa66c92bfcd8d14379f03ab43e to your computer and use it in GitHub Desktop.
Using tasks that perform on property update
// Mixin
import { task } from 'ember-concurrency';
import Mixin from '@ember/object/mixin';
export default Mixin.create({
computedTask(keyToWatch, genFunc) {
// Maybe check if this wasn't previously set up
// Ready the task
Ember.defineProperty(this, 'taskToRun', task(genFunc).restartable());
// Add the observer that performs the task on value update
this.addObserver(keyToWatch, () => {
this.taskToRun.perform();
});
// Run the first time
this.taskToRun.perform();
}
});
import ComputedTask from 'computed-tasks/mixins/my-comp-task';
import { timeout } from 'ember-concurrency';
import { later } from '@ember/runloop';
import Component from '@ember/component';
export default Component.extend(ComputedTask, {
mSetupComputedTaskExample() {
this.computedTask('foo', function * () {
yield timeout(1000);
let randomVal = Math.random();
let fooVal = this.get('foo');
this.set('newFoo', `fooVal = ${fooVal}, randomVal = ${randomVal}`);
});
},
didInsertElement() {
// Initial value
this.set('foo', 'Physics');
this.mSetupComputedTaskExample();
// To see it in action
later(this, function(){
this.set('foo', 'Biology');
}, 2000);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment