【发布时间】:2015-01-29 15:54:57
【问题描述】:
到目前为止,我的 groupedItems 已在模板中正确呈现。但是当我点击add to cart 链接时,它会触发addToCart 操作。模板不呈现新项目...我必须手动刷新页面才能看到它。
我检查了 Ember Inspector,数据选项卡。新添加的项目已附加到列表中。那么,如果反映在数据存储中,它不应该在模板中也反映/呈现吗?
新添加的项目也被持久化在数据库中。
如果我将路由中的模型挂钩更改为items: this.store.find('item'),而不是items: this.store.find('item', { status: 'queued' })。一切正常...
我怀疑这是我的计算属性groupedItems 的管理方式。有什么指点吗?
// Routes
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return Ember.RSVP.hash({
// items: this.store.find('item'),
// items: this.store.find('item').filterBy('status', 'queued'),
items: this.store.find('item', { status: 'queued' }),
// products: this.store.find('product', { status: 'available' })
});
},
// You can use model.items to get items, etc
// Since the model is a plain object you can just use setProperties
// http://stackoverflow.com/questions/16463958/how-to-use-multiple-models-with-a-single-route-in-emberjs-ember-data
setupController: function(controller, model) {
// model.reload;
controller.setProperties(model);
},
actions: {
addToCart: function(product) {
var _this = this;
var item = _this.store.createRecord('item');
item.set('product', product);
item.save().then(function() {
// _this.transitionTo(fromRoute);
});
}
}
});
// Controller
import Ember from 'ember';
export default Ember.Controller.extend({
groupedItems: function () {
var result = [];
this.get('items').forEach(function(item) {
// this.get('items').filterBy('status', 'queued').forEach(function(item) {
var hasProductId = result.findBy('productId', item.get('product.id'));
if(!hasProductId) {
result.pushObject(Ember.Object.create({
productId: item.get('product.id'),
product: item.get('product'),
item: item,
numberOfProducts: 0,
subtotalInCents: 0
}));
}
var productFromResult = result.findBy('productId', item.get('product.id'));
productFromResult.set('numberOfProducts', productFromResult.get('numberOfProducts') + 1);
item.get('product').then(function(product){
productFromResult.set('subtotalInCents', productFromResult.get('subtotalInCents') + product.get('amountInCents'));
});
});
return result;
}.property('items.@each')
});
// Template / hbs
<ul>
{{#each groupedItems}}
<li>
<a href="#" {{action "addToCart" product}}>Add</a>
/ <a href="#" {{action "removeFromCart" item 'index'}}>Remove</a>
{{numberOfProducts}} {{product.name}} P{{cents-to-pesos product.amountInCents}} / each
</li>
{{/each}}
</ul>
【问题讨论】:
标签: ember.js ember-data ember-cli