gpt4 book ai didi

ember.js - 按相关模型过滤模型(已有很多)

转载 作者:行者123 更新时间:2023-12-02 06:10:52 25 4
gpt4 key购买 nike

我有一个与tags相关的产品列表。我想过滤列表以仅显示具有指定标签的产品:

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

我不明白为什么前三个 undefined ?另外,我在模板中没有得到任何输出,因此似乎过滤器功能不正确:
{{#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 - 按相关模型过滤模型(已有很多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20760146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com