Last active
July 20, 2018 23:26
-
-
Save ankushdharkar/9fb2effa66c92bfcd8d14379f03ab43e to your computer and use it in GitHub Desktop.
Using tasks that perform on property update
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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