如何获取特定属性并将其放在backbone.js的集合中?

时间:2015-06-04 13:46:11

标签: javascript json 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'!");
     }
});

我无法知道在i传递if(bar.a == i)的位置和方式。

1 个答案:

答案 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());        
});

演示http://jsfiddle.net/nikoshr/v57rpgu9/