Skip to content

Instantly share code, notes, and snippets.

@camskene
Forked from vitch/controllers.application.js
Created October 3, 2018 14:13
Show Gist options
  • Save camskene/18cebd25e1026977052c16d8385fae2e to your computer and use it in GitHub Desktop.
Save camskene/18cebd25e1026977052c16d8385fae2e to your computer and use it in GitHub Desktop.
Ember - Return Promise from Computed Property
import Ember from 'ember';
export default Ember.Controller.extend({
shouldRenderComponent: false,
actions: {
renderComponent() {
this.toggleProperty('shouldRenderComponent');
},
},
});
import Ember from 'ember';
import { task } from 'ember-concurrency';
let Api = Ember.Object.extend({
getItems() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(['John', 'Paul', 'George', 'Ringo']);
}, 1000);
});
},
});
let api = Api.create();
export default Ember.Component.extend({
api,
isLoading: true,
init() {
this._super(...arguments);
this.get('fetchItems');
this.get('eccItemsFetch').perform();
},
items: undefined,
fetchItems: Ember.computed(function() {
this.get('api').getItems().then((items) => {
this.setProperties({
items,
isLoading: false,
});
});
}),
otherItems: Ember.computed(function() {
let data = Ember.Object.create({
isLoading: true,
});
this.get('api').getItems().then((items) => {
data.setProperties({
items,
isLoading: false,
});
});
return data;
}),
eccItemsFetch: task(function* () {
let items = yield this.get('api').getItems();
this.set('eccItems', items);
}),
eccItems: undefined,
});
{{#if isLoading}}
<p>Loading 'Beatles...</p>
{{else}}
<ul>
{{#each items as |item|}}
<li>{{item}}</li>
{{/each}}
</ul>
{{/if}}
{{#if otherItems.isLoading}}
<p>Loading 'Beatles...</p>
{{else}}
<ul>
{{#each otherItems.items as |item|}}
<li>{{item}}</li>
{{/each}}
</ul>
{{/if}}
{{#if eccItemsFetch.isRunning}}
<p>Loading 'Beatles...</p>
{{else}}
<ul>
{{#each eccItems as |item|}}
<li>{{item}}</li>
{{/each}}
</ul>
{{/if}}
<p>Clicking the button will render a component. This component will fetch data.</p>
<button onclick={{action 'renderComponent'}}>
{{if shouldRenderComponent 'Destroy' 'Render'}} component
</button>
{{#if shouldRenderComponent}}
{{my-component}}
{{/if}}
{
"version": "0.15.0",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": true,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js",
"ember": "3.2.2",
"ember-template-compiler": "3.2.2",
"ember-testing": "3.2.2"
},
"addons": {
"ember-concurrency": "0.8.21"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment