gpt4 book ai didi

javascript - Backbone & Require - 离开时破坏 View

转载 作者:行者123 更新时间:2023-11-28 01:14:14 25 4
gpt4 key购买 nike

我已阅读 Derick Bailey's article on Zombies但似乎无法弄清楚。我有一个使用 require.js 的主干应用程序,并且当我离开它时需要能够关闭/销毁 View 。

启动主干应用程序的方法有很多,但是使用 require 进行清理时,正确的方法是什么?在离开之前,如何在 View 上调用 close() 函数?

Main.js

require([ "app", "backbone", "router", "facebook"], function(App, Backbone, Router, FB) {

//theres a lot of facebook integration
FB.init({
appId : '********',
version : 'v2.0'
});

//force the page to go to index when first arriving
window.location.hash = "";

new App;

Backbone.history.start();
});

App.js

define([ "backbone", "router" ], function(Backbone, Router){

var App = function () {
Router;
}

return App;
})

Router.js

define([ "backbone", "models/user" ], function(Backbone, User){

var AppRouter = Backbone.Router.extend({
routes: {
//All my routes
},
index: function () {
require([ "views/index", "models/user" ], function (IndexView, UserModel) {
var indexView = new IndexView({ model: UserModel });
})
},

// Remaining route functions

return new AppRouter;
})

最佳答案

那篇文章解决了您的代码没有的问题。

只有当您的 View 将事件处理程序附加到模型实例时,才会出现问题(僵尸 View )。

var View = Backbone.View.extend({
setup: {
// model instance will now be storing a callback which is bound
// to *this* instance of a view
this.model.on('change', this.render, this);
},
render: function () {
// whatever code that uses the context, `this`
this.$el.innerHTML(this.model.get('title'));
}
});

然后在您的应用程序生命周期中,上面的 View 被渲染,然后页面发生更改,或者发生任何情况,并且不再需要该 View 。但是可能还有其他东西正在使用此 View 所使用的模型 - 并且该模型可能会不断更改,然后它将触发 change 事件(即 render 方法)的回调这将指向看似不存在的观点。

但是由于该 View 可能不再在 DOM 中包含其元素,因此您将收到 DOM 错误(例如,如果您的渲染方法引用了 this.$el.parent())和 View 将在您不知情的情况下保留在内存中,最终导致您的页面变慢甚至无响应。

自从那篇文章撰写以来,现在有一种附加事件处理程序的新方法,称为 listenTo ,这使得 stopListening 变得更容易.

现在还有View.prototype.remove方法将从 DOM 中删除 View 元素,并调用 stopListening ,这将有助于您使用 listenTo 为模型附加事件处理程序。

关于javascript - Backbone & Require - 离开时破坏 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24036628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com