我正在使用路由器匿名实例化我的 View ,这样我就可以在初始化时简单地渲染它们。
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;
}
});
View 的集合在 View 的构造函数内部构造,具有计算的 url
属性,该属性支持每个请求的分页“偏移”参数。在每次“下一页”请求之前,“offset”参数都会加一,以便服务器返回结果的下一个偏移量。第一个 collection#fetch()
使用初始化方法中的默认“偏移”值,一旦调用 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 });
}
});
它工作得很好,直到我从实现相关 View 和集合的默认路由来回导航几次后注意到另一条路由;然后单击调用集合的 collection#loadMore()
方法的元素,调用 fetch()
的次数是我导航回默认路由器的次数。
我预计它只会调用 fetch()
一次,但它在导航后很容易调用该方法 2 次或更多次。这是因为在我更改路线并导航回来后实例没有被销毁吗?如果是这样,我不再需要该对象后如何正确清理它?
最佳答案
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();
},
...
});
关于javascript - Backbone.js — 匿名 View 实例中的集合在获取时多次请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7342924/