简体   繁体   中英

Backbone js help me get at my JSON array

I'm currently going through a backbone.js tutorial and instead of using the suggested REST service I'm using one from my company as a real-world example. The problem is that the tutorial uses a very simple JSON return from the REST server like this:

{
    "name":"Brian"
    "age":52
},
    "name":"Mary"
    "age":"27"
}
... etc.

My own data contains arrays of this type:

{
    "records":20,
    "customers": [{name:"Simon", age:27},{name:"Mary", age:28}... etc.]
}

I want to get at 'customers' in this case. I believe I can use parse: within a Model for this but this tutorial uses only a Collection and renders that out to the template. Can I do this with just a Collection? Or should I make a Model and use parse:?

You can use a collection -- just override Collection.parse . This is the function that Backbone calls to convert the raw AJAX response into model attributes. In your case, you just need it to return response.customers instead of the raw response:

var MyCollection = Backbone.Collection.extend({
    parse: function(response) {
        return response.customers;
    }
});

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