Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js - rendering view

My ListClass looks like this:

var ListView = Backbone.View.extend({

    initialize: function() {
        this.render();
    },  

    events: {
        'click ul#perpage span': 'setperpage'
    },

    setperpage: function(event) {
        this.collection.perpageurl = '/perpage/' + $(event.target).text();
        this.collection.fetch();
        this.render();
    },

    render: function() {

    template = _.template('\
    <table>\
    <% _(collection).each(function(model){%>\
    <tr><td><%=model.id%></td><td><%=model.name%></td><td><%=model.email%></td></tr>\
    <%}); %>\
    </table>\
    <ul id="perpage">\
    <li><span>5</span></li>\
    <li><span>10</span></li>\
    </ul>\
    ');

        var context = {collection: this.collection.toJSON()};
        $(this.el).html(template(context));
        $('#app').html(this.el);
        return this;
    }
});

For some reason, when I first visit the page that loads this view, 5 items show up (which is supposed to happen). But when I hit the "setperpage" event by clicking the <span>10</span>, even though the url is updated and then fetch() is called, the list never updates. (I've watched the requests w/ firebug, so I know I'm getting back 10 items in json). Why don't they re render? I still only see 5 items.

like image 390
Matthew Avatar asked Apr 15 '11 19:04

Matthew


1 Answers

The this.collection.fetch(); is asynchronous so the call to render will still be using the old data.

You need to wait for the fetch() to complete before calling the render function.

In your initialize function, bind to the render function to the "reset" event.

this.collection.on("reset", function() { this.render(); }, this);

When you need new data, call

this.collection.fetch({reset: true});
like image 51
Paul Perigny Avatar answered Oct 25 '22 18:10

Paul Perigny