Ember 2.17
我正在从我的模板中调用一个助手:
{{#each invoice.invoiceLines as |line| }}
{{pricings/full-pricing line.pricing}}
{{/each}}
invoice
、invoiceLine
和pricing
是成员模型。
以下是如何在模型((中创建发票:
model(params) {
let invoice= this.store.findRecord('invoice',params.invoice_id)
return Ember.RSVP.hash({
invoice: invoice,
allShares: invoice.then((i)=>{return i.allShares()}),
detailShares: invoice.then((i)=>{return i.detailShares()})
});
}
助手的目标是获取定价,提取数字(所有内容都在模型中,不再有关系(,并返回一个格式化初始价格和订阅价格的字符串。助手如下:
import { helper } from '@ember/component/helper';
export function pricingsFullPricing([pricing]) {
return pricing.then(
p=>{
debugger
},p=>{
}
)
}
export default helper(pricingsFullPricing);
当我运行页面时,调试器被调用两次(模板循环运行一次(。
第一次p为null,第二次是定价。
then
不应该阻止这种情况吗?为什么它会那样?
您的路由是错误的,路由是承诺感知的(这就是hash
的作用(,它应该是:
model(params) {
return Ember.RSVP.hash({
invoice: this.store.findRecord('invoice',params.invoice_id)
//allShares: invoice.then((i)=>{return i.allShares()}),
//detailShares: invoice.then((i)=>{return i.detailShares()})
});
}
那么你的车把就是:
{{#each model.invoice.invoiceLines as |line| }}
{{line}}
{{/each}}
您也不应该像在模型上那样调用方法。目前还不清楚allShares()
等的作用,但它们(可能(应该是控制器中的computed
。大致如下:
import { computed } from '@ember/object';
export default Controller.extend({
allShares:computed('model.invoice', function(){
return this.get('model.invoice').allShares();
});
});
尽管这看起来并不理想。就像我说的,很难明确,因为不清楚你想在这里做什么。如果将这些方法提取到服务中,可能会更有意义。
这样你就根本不需要帮助者了这似乎只是为了兑现承诺。
如果您尝试在加载前将所有服务器端数据加载到route
中,这将使生活变得更加轻松。
助手的第一条规则
每次助手的输入发生更改时,都会再次调用计算函数。
其次,由于您返回的是promise,所以没有任何关于助手的信息会使此块后续调用。
export function pricingsFullPricing([pricing]) {
return pricing.then(
p=>{
debugger
},p=>{
}
)
}
您在这里创建了一个简单的助手,它将使用promise本身作为值。查看ember-promise helpers/await,了解如何使用基于类的帮助器手动设置模板中显示的值。
现在,如果你想知道为什么会进行重新计算,我将不得不根据我作为Ember社区的一员对Ember数据的了解进行推测(我从未真正使用过Ember数据(。你知道line.pricing
是承诺吗?然后,我可以假设您使用某种关系,这种关系很可能必须通过ajax调用加载(因此承诺(。但是Ember数据iirc中的这些关系使用了这个PromiseProxy Mixin,它允许它们同时表现得像promise或对象(取决于数据是否已经在存储中(。这允许您在没有then
的情况下引用模板中的承诺
请参阅本文以更好地理解的含义