我有一个带有相关标签
的产品列表。我想过滤列表以仅显示具有指定标签的产品:
App.Product = DS.Model.extend({
tags: DS.hasMany('Tag', { async: true }),
name: DS.attr( 'string' )
});
App.Tag = DS.Model.extend({
name: DS.attr('string')
});
App.ProductsTaggedRoute = Ember.Route.extend({
model: function(params) {
var store = this.store;
return store.find('product').then(function() {
store.filter('product', function(product, index, enumerable) {
var match = false;
product.get('tags').then(function(tags) {
tags.forEach(function(tag) {
if(tag.get('name') === 'Tag 1') {
console.log(product.get('name') + ' true');
match = true;
} else {
console.log(product.get('name') + ' false', tag.get('name'));
}
});
});
return match;
});
});
}
});
App.Product.FIXTURES = [
{ id: 1, tags: [1,2,3], name: "test 1" },
{ id: 2, tags: [3], name: "test 2" },
{ id: 3, tags: [2,1], name: "test 3" },
{ id: 4, tags: [], name: "test 4" }
];
App.Tag.FIXTURES = [
{ id: 1, name: "Tag 1" },
{ id: 2, name: "Tag 2" },
{ id: 3, name: "Tag 3" },
{ id: 4, name: "Tag 4" }
];
输出为:
test 2 false undefined
test 3 false undefined
test 3 false undefined
test 1 true
test 1 false Tag 2
test 1 false Tag 3
我不明白为什么前三个是未定义的?另外,我在模板中没有得到任何输出,因此过滤器功能似乎不正确:
{{#each controller}}
{{ name }}
{{/each}}
最佳答案
您需要确保在使用过滤器之前解析记录。这是 Promise 的完美用例。您返回一个 promise ,并控制解决的内容和时间。
http://emberjs.jsbin.com/OxIDiVU/84/edit
model: function(params) {
var store = this.store;
return new Em.RSVP.Promise(function(resolve){
//find products
store.find('product').then(function(products) {
// get all the tag promises
var promiseArr = products.getEach('tags');
//wait on them
Em.RSVP.all(promiseArr).then(function() {
var filter = store.filter('product', function(product, index, enumerable) {
var match = false;
product.get('tags').forEach(function(tag) {
if(tag.get('name') === 'Tag 1') {
console.log(product.get('name') + ' true');
match = true;
} else {
console.log(product.get('name') + ' false', tag.get('name'));
}
});
return match;
}); //filter
resolve(filter);
}); // RSVP All
}); //find
}); // promise
}
关于ember.js - 按相关模型过滤模型 (hasMany),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20760146/