azz*_*z0r 3 javascript setinterval backbone.js
我需要视图来重新收集集合并每30秒重新渲染一次.问题是,一旦我更改页面(没有完整页面刷新),setInterval将保留在内存中并在后台保持重新获取.然而,这种观点早已被摧毁.
码:
define(
[
"underscore",
"collection/system/feed",
"view/list",
"text!template/index/system-feed.html"
],
function (_, Collection, ListView, Template) {
return ListView.extend({
el: '<div id="main-inner">',
collection: new Collection(),
loading: true,
client: false,
initialize: function (options) {
this.collection.fetch();
this.collection.on('reset', this.onFetchCollection, this);
var self = this;
setInterval(function() {
self.collection.fetch();
}, 30000);
},
/*collection is returned, so reset the loading symbol and set the posts to the render*/
onFetchCollection: function () {
this.list = this.collection.toJSON();
this.loading = false;
this.render();
},
render: function () {
var html = _.template(Template, {loading: this.loading, client: this.client, list: this.list});
this.$el.html(html);
return this;
}
});
}
);
Run Code Online (Sandbox Code Playgroud)
将timer变量分配给setInterval并在关闭视图时将其清除.
initialize: function() {
this.timer = setInterval(function() {
self.collection.fetch();
}, 30000);
},
close: function() {
clearInterval(this.timer);
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您有一个在关闭视图时调用的自定义原型方法,那么只需包含它并且应该清除计时器.
但请确保在移动到下一页之前清理视图,如果不处理,将导致内存泄漏,从而大大降低应用程序的速度.
并且最好将事件直接附加到视图中,而不是使用model或collection使用listenTo
更换
this.collection.on('reset', this.onFetchCollection, this);
Run Code Online (Sandbox Code Playgroud)
同
this.listenTo(this.collection, 'reset', this.onFetchCollection);
Run Code Online (Sandbox Code Playgroud)
这样,如果删除视图,即使是事件绑定也会被处理掉.否则,您需要显式取消绑定集合上的事件.
只需调用this.stopListening()就可以解除视图中所有事件的绑定.
| 归档时间: |
|
| 查看次数: |
5141 次 |
| 最近记录: |