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.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With