简体   繁体   中英

backbone complex data modeling how to read

Hello all I am new in backbone and JavaScript. My data.json file looks like this:

{
"locations":
[
  {address:"2222", town:"Dallas"},{address:'3333', town:"Houston"},{}....
],

"items":
[
  {title:"shirt", price:20},{title:"shorts", price:10},{}....
]
}

I am populating two different Listview using jquery mobile.


I have created Backbone models separately for both location and item

Item = Backbone.Model.extend({

     default:
     {
             title:"",
         price:""
     }
});

Address = Backbone.Model.extend({

     default:
     {
         address:"",
         town:""
     }
});

I also have created Address and Item collection as following

Items = Backbone.Collection.extend({
   defaults: {
            model: Item
             }
});

Addresses = Backbone.Collection.extend({
   defaults: {
            model: Address
             }
});

Now How do I create my Store model which will have adress and item collection. I guess something like this:

Store = Backbone.Model.extend({
    addresses:[],
    items:[],
    url:"data.json"
});

Also how do I populate the list view once the data is read? Thanks

You can add a parse method to Store ( http://backbonejs.org/#Model-parse ):

Store = Backbone.Model.extend({
    addresses: [],
    items: [],
    url: 'data.json'
    parse: function(response) {
        this.addresses = new Addresses(response.locations);
        this.items = new Items(response.items);
        return response;
    }
});

Alternatively, you could add a listener for "reset" in an initialize function, but if you're going to fetch the data anyway, I'd just use parse.

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