问题描述:

After days of searching on google, I finally pushed myself to ask the question over here.

I have few json files.

localhost/feed01.json

localhost/feed02.json

localhost/feed03.json

all the json file structures similar to this one. but random data including random, id, date type etc...

[

{

"id":1,

"date": "12/12/2011",

"type": "Run",

"distance": "3 miles",

"comments": "This was really hard",

"minutes": 36

},

{

"id":2,

"date": "12/11/2011",

"type": "Bike",

"distance": "6 miles",

"comments": "All down hill...felt like nothing",

"minutes": 30

},

{

"id":3,

"date": "12/10/2011",

"type": "Walk",

"distance": "2.5 miles",

"comments": "Shouldn't have taken the dog",

"minutes": 45

}

]

Now I want to merge all this json files to a one and sort by date by default (on initialization). What is the best way to merge and sort using backbone.js using collections?

网友答案:

To merge data just create a collection and all the arrays with json objects/model representations to this collection. To achieve the ability you can override the fetch method and make it do 3 ajax calls and using jquery deferreds wait until all three of them are resolved and added returned data to collection before you resolve the fetch request.

To alter the sorting logics you need to overwrite the collections comparator method to sort based on your data.

you could specify it as for example as this

comparator: function(model) {
    return +new Date(model.get('date'));
}

and it would sort it by date.

If you would for whatever reason specify the comparator after adding the models to the collection you'd need to call the sort method so that the models get sorted according to the rule specified by comparator

网友答案:

Backbone lets you override some of backbone.sync through options

  • you can pass a target url as an option to collection.fetch to override the default url
  • and passing add: true appends the models to the collection instead of resetting it

which means you can build a collection with

var c = new Backbone.Collection();
c.fetch({
    url: ('localhost/feed01.json'),
    add: true
});
c.fetch({
    url: ('localhost/feed02.json'),
    add: true
});
...

To invoke a callback when all fetches have completed, you can build a jQuery deferred object

var files = ['localhost/feed01.json', 'localhost/feed02.json', 'localhost/feed03.json'];
var c=new Backbone.Collection();
var dfds = [], dfd, i, l;
for (i=0, l=files.length; i<l;i++) {
    dfd = c.fetch({
        url: (files[i]),
        add: true
    });
    dfds.push(dfd);
}

$.when.apply(null, dfds).done(function() {
    console.log(c.pluck('id'));
});
相关阅读:
Top