标签: 无限滚动应用

  • Backbone.Collection.fetch小优化一则

    使用Backbone开发无限滚动应用的时候,必然会用到Collection.fetch()加载后面的内容。在Backbone的设计中,fetch之后,Collection会把取回来的内容“智能合并”到当前结果集中,该添加的添加、该修改的修改、该删除的删除,并且触发不同的事件。

    这样就会带来一个问题,因为我们知道,向DOM树当中添加元素的次数越少越好,因为每次添加都会导致重新计算布局和重绘;但是Backbone又是依次触发add事件的,怎么办呢?

    其实也容易,因为set完成后,Collection还会广播sync事件,所以我们可以在响应add事件时拼装jquery对象,响应sync事件时再把它们添加到DOM树中。代码如下:

    var InfinityScroll = Backbone.View.extend({
      initialize: function () {
        this.collection.on('add', this.collection_addHandler, this);
        this.collection.on('sync', this.collection_syncHandler, this);
      },
      collection_addHandler: function (model) {
        var html = this.template(model.toJSON());
        this.fragment = this.fragment ? this.fragment.add(html) : $(html);
      },
      collection_syncHandler: function () {
        if (this.fragment) {
          this.$el.append(this.fragment);
          this.fragment = null;
        }
      }
    });