我的网站是在 Backbone 上构建的。它具有基于提要的 UI,这意味着提要中通常会显示大量内容。大约每个项目绑定(bind)了大约 30 个事件。
向下滚动几页后,它变得缓慢。
解除已滚出的项目的绑定(bind),并在滚入时再次绑定(bind)是否有意义?
什么可能导致缓慢?
最佳答案
很难说缓慢是因为事件处理程序,还是仅仅因为浏览器无法处理页面上大量的 DOM 节点,或者任何其他原因。
这里有一个快速解决方案,用于取消不在当前视口(viewport)中的 View 的委派事件。它并不完全适合生产,但应该可以帮助您测试事件处理程序是否是性能问题的原因。
( Working JSFiddle here ,另请检查浏览器控制台)
var View = Backbone.View.extend({
onScroll: function() {
var wasInView = this.isInView;
var isInView = this.checkIsInView();
if(wasInView === true) {
if(!isInView) {
this.undelegateEvents();
}
}
else if(wasInView === false) {
if(isInView) {
this.delegateEvents();
}
}
else {
//first pass
if(!isInView) {
this.undelegateEvents();
}
}
this.isInView = isInView;
},
checkIsInView: function() {
var $el = this.$el,
top = $el.offset().top,
bottom = top + $el.height(),
windowTop = $(window).scrollTop(),
windowBottom = windowTop + $(window).height();
return ((bottom <= windowBottom) && (top >= windowTop));
},
render: function () {
//rendering code here...
if(!this.lazyScroll) {
//wait for scroll events to stop before triggering scroll handler
this.lazyScroll = _.debounce(_.bind(this.onScroll, this), 50);
$(window).bind('scroll', this.lazyScroll)
.bind('resize', this.lazyScroll);
}
return this;
},
remove: function() {
if(this.lazyScroll) {
$(window).unbind('scroll', this.lazyScroll)
.unbind('resize', this.lazyScroll);
delete this.lazyScroll;
}
Backbone.View.prototype.remove.apply(this, arguments);
}
});
关于jquery - 取消绑定(bind)滚动事件 - 推荐吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14195621/