Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js fetch problem (can't refresh data immediately)

I have such code:

var MyModel = Backbone.Model.extend();

var MyCollection = Backbone.Collection.extend({
    url: '/url/',
    model: MyModel
});
var coll = new MyCollection();

The url is correct and returns correct json. But if I try to use the next code:

$('#fetch').click(function(){
    coll.fetch();
    console.log(coll.toJSON());
});
  • it shows me data only after the second click (http-response in firebug i see after the first one). It seems that data isn't refreshed in time.

If I put each statement in different event it works correct. But I need to know the length of collection immediately. How to do this?

like image 252
Andrew Avatar asked May 18 '11 17:05

Andrew


2 Answers

Keep in mind that fetch is an asynchronous call to the server. To make your code work as you expected, create a success function that Backbone.Collection can call once it refreshes its contents from the server:

$('#fetch').click(function(){
    coll.fetch({
        succcess: function() {
            console.log(coll.toJSON());
        }
    });    
});

Obviously you app doesn't need to really call console.log so a more real world example would use backbone's event binding like this:

coll.bind('refresh', someFunction);
coll.fetch();

With this approach, backbone will call someFunction when the collection refreshes. This is really useful especially when someFunction is the render function of a view to which you want to bind your collection.

coll.bind('refresh', yourView.render);
coll.fetch();
like image 62
Andrew Hare Avatar answered Oct 23 '22 19:10

Andrew Hare


From version 0.5.0 Collection.refresh was renamed to Collection.reset.

So in Andrew's answer (that I found very useful):

coll.bind('refresh', someFunction);

becomes

coll.bind('reset', someFunction);
like image 24
Pietro Avatar answered Oct 23 '22 20:10

Pietro