如何获取特定属性并将其放入 backbone.js 中的集合中?
How to fetch a specific attribute and put it in a collection in backbone.js?
我想获取特定属性并将其放入集合中。 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'!");
}
});
我不知道在哪里以及如何为 if(bar.a == i)
传递 i
。
您传递给 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());
});
我想获取特定属性并将其放入集合中。 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'!");
}
});
我不知道在哪里以及如何为 if(bar.a == i)
传递 i
。
您传递给 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());
});