Backbone.js - 匿名视图实例中的集合在获取时请求多次

时间:2011-09-08 03:50:58

标签: javascript view backbone.js router

我正在使用路由器匿名实例化我的视图,所以我可以在初始化时简单地渲染它们。

window.Router = Backbone.Router.extend({
  routes: {
    '': 'index',
    ...
  },

  index: function() {
    new SchoolsView();
  },

  ...

});
window.SchoolsView = Backbone.View.extend({        
    events: {
        'click .more a': 'loadMore'
    },

    initialize: function() {    
        this.collection = new schoolList();

        this.collection.bind('add', this.add, this);
        this.collection.bind('reset', this.render, this);

        this.collection.fetch();
    },

    render: function() {
      ...
    },

    add: function(school) {
      ...
    },

    loadMore: function() {
      this.collection.loadMore();
      return false;
    }
});

视图的集合在视图的构造函数内部构造,具有计算的url属性,该属性支持每个请求的分页“偏移”参数。在每个“下一页”请求之前,“offset”参数加1,服务器返回结果的下一个偏移量。第一个collection#fetch()使用initialize方法的默认“offset”值,一旦调用方法collection#loadMore(),它就会递增。

window.schoolList = Backbone.Collection.extend({
  initialize: function() {
    this.offset = 1;
  },

  url: function() {
    return this.baseUrl()+'?offset='+this.offset;
  },

  pageInfo: function() {
    var info = {
      total: this.total,
      offset: this.offset,
      pages: Math.ceil(this.total / 9),
      more: false
    };

    if (this.offset < info.pages) info.more = this.offset + 1;

    return info;
  },

  loadMore: function() {
    if (!this.pageInfo().more) return false;
    this.offset += 1;
    return this.fetch({ add: true });
  }
});

直到我注意到从默认路线来回导航几次之后才开始工作,这个路线实现了有问题的视图和收藏,再到另一个;并且单击调用集合的collection#loadMore()方法的元素,fetch()被称为我导航回默认路由器的次数。

我预计只会拨打fetch()一次,但在导航后很容易调用该方法2次或更多次。这是因为在我更改路线并导航后,实例没有被销毁吗?如果是这样,我不再需要它后如何正确清理对象?

1 个答案:

答案 0 :(得分:0)

window.Router = Backbone.Router.extend({
    routes: {
        '': 'index',
        ...
    },

    index: function() {
    var collection = new schoolList(),
        view = new SchoolsView({
            collection: collection
        });

    this
        .trigger('destroy_index')
        .bind('destroy_index', function() {
            collection.reset();
            view.remove();
        });
    },

    ...

});

window.SchoolsView = Backbone.View.extend({ 
    initialize: function() {    
        this.collection.bind('add', this.add, this);
        this.collection.bind('reset', this.render, this);

        this.collection.fetch();
    },
    ...
});