PromiseProxyMixin
Ember 附帶了一個內建的幫助程式,它將為非同步任務的狀態提供計算屬性。
優點
- 內建 - 無需外掛。
- 可以在元件的生命週期中進行管理。
- 提供可以驅動模板邏輯的方便的狀態屬性。
缺點
- 必須用
Ember.Object
包裹,不能直接應用於Ember.Component
。 - 在原始承諾鏈和
content
值的破壞之間建立斷開連線。 - 不是非常直觀,可能很難推理。
- 無法取消。
JavaScript
import Ember from 'ember';
const {
Component, PromiseProxyMixin, get, set, computed,
isPresent, run, RSVP: { Promise }
} = Ember;
const MyPromiseProxy = Ember.Object.extend(PromiseProxyMixin);
export default Component({
myProxy: computed('promise', {
get() {
const promise = get(this, 'promise');
return isPresent(promise) ? MyPromiseProxy.create({promise}) : null;
}
}),
actions: {
performTask() {
const fakeTask = new Promise((resolve) => {
run.later(resolve, 'Foobar', 2000);
});
set(this, 'promise', fakeTask);
}
}
});
模板
{{#if myProxy.isPending}}
Loading…
{{else}}
<button onclick={{action "performTask"}}>
Start Task
</button>
{{/if}}
{{#if myProxy.isFulfilled}}
Done. {{myProxy.content}}
{{/if}}
{{#if myProxy.isRejected}}
Something went wrong. {{myProxy.reason}}
{{/if}}