backbone.js - 渲染视图
我的 ListClass 如下所示:
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;
}
});
由于某种原因,当我第一次访问加载此视图的页面时,会显示 5 个项目(这是应该发生的)。但是,当我通过单击 10
触发“setperpage”事件时,即使网址已更新,然后调用 fetch()
,该列表永远不会更新。 (我已经看过带 firebug 的请求,所以我知道我正在以 json 形式返回 10 个项目)。他们为什么不重新渲染?我仍然只看到 5 项。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
this.collection.fetch();
是异步的,因此对 render 的调用仍将使用旧数据。在调用渲染函数之前,您需要等待 fetch() 完成。
在初始化函数中,将渲染函数绑定到“重置”事件。
当您需要新数据时,请致电
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.
When you need new data, call