Skip to content

Instantly share code, notes, and snippets.

@alexander-alvarez
Created April 26, 2017 21:10
Show Gist options
  • Save alexander-alvarez/3d4130fea587ebb38dccc6bc15460ff8 to your computer and use it in GitHub Desktop.
Save alexander-alvarez/3d4130fea587ebb38dccc6bc15460ff8 to your computer and use it in GitHub Desktop.
Derived state
import Ember from 'ember';
import {task, timeout} from 'ember-concurrency';
const { computed } = Ember;
export default Ember.Component.extend({
requiredInputA: null,
requiredInputB: null,
hasRequiredInputA: computed.bool('requiredInputA'),
hasRequiredInputB: computed.bool('requiredInputB.length'),
hasValidInputs: computed.and('hasRequiredInputA', 'hasRequiredInputB'),
taskInstance: computed('requiredInputB.[]', 'requiredInputA', function(){
return this.get('task').perform();
}),
task: task(function * () {
this.incrementProperty('counter');
yield timeout(1000);
return [this.get('requiredInputA'), ...this.get('requiredInputB')];
}).keepLatest(),
// for demo purposes
counter: 0
});
import Ember from 'ember';
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
foo: null,
bar: null,
actions : {
addInputs(){
this.set('foo', 'abc');
this.set('bar', [1, 2]);
},
addAnother() {
this.get('bar').pushObject('z');
}
}
});
<h1>Welcome to {{appName}}</h1>
<br>
<br>
{{my-component requiredInputA=foo requiredInputB=bar}}
<br>
<button {{action 'addInputs'}}>
Add valid inputs
</button>
<button {{action 'addAnother'}}>
click me next
</button>
{{#if (not hasValidInputs)}}
User feedback, no valid inputs
{{else if taskInstance.isRunning}}
Show loading {{counter}}
{{else if taskInstance.isError}}
Shoot an error.
{{else if taskInstance.value}}
{{#each taskInstance.value as |v|}}
{{v}}
{{/each}}
{{/if}}
{{!--
You could also make a higher order query/data component to be used in block mode
that give you derived state for your other components.
// .hbs
{{yield (hash
loading=taskInstance.isRunning
error=task.last.isError
value=taskInstance.value
hasValidInputs=hasValidInputs
)
}}
// usage
{{#my-query-component as |q|}}
{{#if q.loading}}
{{else if q.error}}
{{else if q.value}}
{{/if}}
{{/my-query-component}}
--}}
{
"version": "0.12.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.12.0",
"ember-template-compiler": "2.12.0",
"ember-testing": "2.12.0"
},
"addons": {
"ember-data": "2.12.1",
"ember-truth-helpers": "*",
"ember-concurrency": "*"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment