简体   繁体   中英

How to fetch a specific attribute and put it in a collection in backbone.js?

I would like to fetch a specific attribute and put it in a collection. The JSON looks like this:

{
   foo: "lorem ipsum",
   bars: [{
       a: "a",
       b: {c: "d", e: "f"}
   }, {
       a: "u",
       b: {w: "x", y: "x"}
   }]
}

I understand how to fetch only bars (and not foo bars ) and get it returned somewhere by using parse , but I would like to fetch bars , identify a certain object using attribute a and then put b inside of a collection.

My idea is to do something like

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 am having trouble knowing where and how to pass the i for the if(bar.a == i) .

The options you pass to fetch are forwarded to Collection.parse and that means you can write something like this:

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

And a demo http://jsfiddle.net/nikoshr/v57rpgu9/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM