【发布时间】:2012-02-15 17:44:50
【问题描述】:
我有一个显示用户所有工作的工作表视图。 Jobs 集合 fetch() 可能返回包含数千条记录。我运行了一个测试并在数据库中插入了 1000 个作业记录,并对集合执行了 fetch()。然而,1000 条记录对于浏览器来说似乎太多了,因为插入 1000 条 DOM 表行似乎会导致浏览器冻结。
有没有更好的方法来优化行的呈现以使其执行得更快?我知道您总是可以进行部分提取(最初获取 100 条记录,并在每次用户滚动到屏幕底部时额外获取 100 条记录),但我通常反对这个想法,因为向下滚动 100 条记录并且必须等待 3 -4 秒再渲染另外 100 条记录似乎会导致糟糕的用户体验。
这是我的代码:
FM.Views.JobTable = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'render', 'refresh', 'appendItem');
this.collection.bind('add', this.appendItem, this);
this.collection.bind('reset', this.refresh, this);
},
render: function(){
this.el = ich.JobTable({});
$(this.el).addClass('loading');
return this;
},
refresh: function(){
$('tbody tr', this.el).remove();
$(this.el).removeClass('loading');
_(this.collection.models).each(function(item){ // in case collection is not empty
this.appendItem(item);
}, this);
return this;
},
appendItem: function(item){
var jobRow = new FM.Views.JobTableRow({
model: item
});
$('tbody', this.el).prepend(jobRow.render().el);
$(jobRow).bind('FM_JobSelected', this.triggerSelected);
}
});
FM.Views.JobTableRow = Backbone.View.extend({
tagName: 'tr',
initialize: function(){
_.bindAll(this, 'render', 'remove', 'triggerSelected');
this.model.bind('remove', this.remove);
},
render: function(){
var j = this.model.toJSON();
j.quantity = j.quantity ? number_format(j.quantity, 0) : '';
j.date_start = date('M j Y', j.date_start);
j.date_due = j.date_due ? date('M j Y', strtotime(j.date_due)) : '';
j.paid_class = j.paid;
j.status_class = j.status;
j.paid = slug2words(j.paid);
j.status = slug2words(j.status);
this.el = ich.JobTableRow(j);
$(this.el).bind('click', this.triggerSelected);
return this;
}
});
【问题讨论】:
标签: javascript collections backbone.js render fetch