我想获取一个特定属性并将其放入一个集合中。 JSON看起来像这样:
{
foo: "lorem ipsum",
bars: [{
a: "a",
b: {c: "d", e: "f"}
}, {
a: "u",
b: {w: "x", y: "x"}
}]
}
我了解如何仅使用bars
(而不是foo bars
)获取并使用parse将其返回到某处,但我想获取bars
,某个对象使用属性a
,然后将b
放在集合中。
我的想法是做一些像
这样的事情MyCollection = Backbone.Collection.extend({
model: MyModel,
url: "someUrl",
parse: function(data) {
data.bars.each(function(bar) {
if (bar.a == i) {
return bar.b;
}
}
}
};
var myCollection = new MyCollection();
myCollection.fetch({
success: function() {
console.log("Proper collection of the correct 'b'!");
}
});
我无法知道在i
传递if(bar.a == i)
的位置和方式。
答案 0 :(得分:1)
您传递给fetch
的选项会转发到Collection.parse
,这意味着您可以写下这样的内容:
MyCollection = Backbone.Collection.extend({
model: MyModel,
url: "someUrl",
parse: function(data, opts) {
console.log(opts);
// I took the liberty of replacing your filter
var matches = _.where(data.bars, {a: opts.i});
return _.map(matches, "b");
}
});
var myCollection = new MyCollection();
// pass your filter as an option when you fetch you collection
myCollection.fetch({
i: "u",
success: function() {
console.log("Proper collection of the correct 'b'!");
}
}).then(function() {
console.log(myCollection.toJSON());
});