缓存主干视图及其事件

Cache backbone views with its events

本文关键字:事件 视图 缓存      更新时间:2023-09-26

我正在开发一个相对较大的应用程序,它就像某种应用程序集合。

我所有的应用程序都有一个引导视图,它加载基本布局和嵌套视图。

我现在开始实现视图的单例模式:

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()来重新绑定所有事件。这确实只是一个变通方法,如果有人能给我一个例子,我会很高兴:)

就我个人而言,我更喜欢重建我的视图。

然而,我知道很多人更喜欢重复使用它们。在这种情况下,请按照Tim Branyen的博客文章中的说明进行操作:http://tbranyen.com/post/missing-jquery-events-while-rendering