【发布时间】:2012-08-26 23:01:58
【问题描述】:
我正在开发一个相对较大的应用程序,类似于某种应用程序集合。
我所有的应用程序都有一个引导视图,它加载基本布局和嵌套视图。
我现在开始为视图实现单例模式:
var SomeView = Backbone.View.extend({});
if (SomeView._instance) return SomeView._instance;
SomeView._instance = new SomeView();
return SomeView._instance;
现在我提到当我在不同的应用程序(视图)之间切换时,事件系统会损坏。这实际上是非常合乎逻辑的,最后我们将视图从文档中移除。但是,我对总是建立新的观点有某种抵抗力。这是非常无效的:一切都必须重新加载(数据)并重建。
那么有没有办法将事件重新绑定到缓存视图,或者这整个想法很糟糕,我应该接受必须重建视图?
更新:
define(['jquery', 'underscore', 'backbone', 'views/settings/profile'], function($, _, Backbone, ProfileSettingsView) {
var ContentView = Backbone.View.extend({
tagName: "div",
className: "content well",
initialize: function() {
this.on('change:section', this.change, this);
this.views = {};
this.views.profile = new ProfileSettingsView();
},
render: function() {
this.$el.empty();
return this;
},
events: {
"click": "click"
},
// the router triggers this one here
change: function(query) {
console.log(query);
// if I uncomment this then nothing is rendered at all
//this.$el.detach();
var el;
if (query === 'profile') {
el = this.views.profile.render().el;
} else {
this.$el.empty();
}
if (el) {
this.$el.empty().append(el);
}
},
click: function(e) {
console.log('clicked, content should disapear');
}
});
if (ContentView._instance) return ContentView._instance;
ContentView._instance = new ContentView();
return ContentView._instance;
});
我对如何使用 jQuery 的 detach() 有点困惑。
我查看了官方文档中的演示,发现在 jQuery 对象上调用 .detach() 是不够的。 .detach 返回一个看起来像 jQuery 的新对象 并且 包含绑定的事件。困难在于我必须将detach() 的返回保存在某个地方,我现在必须知道它来自谁。现在我没有任何看透。我现在将使用detach() 搜索一些Backbone.View 示例,但我认为这是特定的......
更新2:
是的!我找到了一种解决方法:而不是保存事件然后将其重新插入 DOM。我们可以调用this.delegateEvents() 重新绑定所有事件。这确实只是一种解决方法,如果有人能给我一个例子,我会很高兴:)
【问题讨论】:
标签: javascript caching view backbone.js backbone-events