Ada*_*hts 4 ember.js ember-data
我的产品型号有很多价格.我有一个页面显示产品名称,代码,然后显示它的价格数量,即:
<tbody>
{{#each model as |product id|}}
<tr>
<td>{{#link-to "product" product}}{{product.name}}{{/link-to}}</td>
<td>{{product.code}}</td>
<td>{{product.prices.length}}</td>
</tr>
{{/each}}
</tbody>
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,使用product.price.lengthEmber数据会产生数千个按ID获取价格的请求.我不需要任何有关此页面上实际价格的信息.如果没有Ember数据下载所有价格,我怎么能在这里使用长度属性?
车型/ product.js:
export default DS.Model.extend({
code: DS.attr('string'),
name: DS.attr('string'),
prices: DS.hasMany('price', {async: true})
});
Run Code Online (Sandbox Code Playgroud)
车型/ price.js
export default DS.Model.extend({
product: DS.belongsTo('product', {async: true}),
value: DS.attr('number'),
minUnits: DS.attr('number'),
maxUnits: DS.attr('number')
});
Run Code Online (Sandbox Code Playgroud)
在ember slack room聊天时,我有两个当前的解决方案,一个是后端,一个是前端.
前端
截至Ember数据2.5,有一个新的'ds-references'功能,详见发布文章http://emberjs.com/blog/2016/05/03/ember-data-2-5-released.html.
有了这个,这里的解决方案是添加一个类似的计算:
priceCount: Ember.computed('prices.[]', function() {
if (this.hasMany('prices').value() === null) {
return 0;
}
return this.hasMany('prices').ids().length;
}
Run Code Online (Sandbox Code Playgroud)
评论中已经报道,上述内容可能会触发后端请求.作为替代方案,您可以添加totalHasMany带代码的辅助函数
return param[0].hasMany(param[1]).ids().length
并在模板中使用它(totalHasMany product 'prices'),我已经在一个成功的应用程序中使用它.
后端
查看使用元数据返回总价格.所以在Json Api设置中就像是
"meta": {
"prices-total": 123
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参见http://jsonapi.org/format/#document-meta.
https://guides.emberjs.com/v2.1.0/models/handling-metadata/也可能对标准json上的用户有用.
感谢kitler和锁定以获得上述建议.
| 归档时间: |
|
| 查看次数: |
757 次 |
| 最近记录: |