3

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

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

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

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(). 我查看了官方文档中的演示,发现仅调用.detach()jQuery 对象是不够的。.detach返回一个看起来像 jQuery 的新对象包含绑定的事件。困难在于我必须保存这个从detach()某个地方返回的东西,我现在必须知道它来自谁。现在我没有任何看透。我现在将搜索一些Backbone.View使用示例,detach()但我认为它是特定的....

更新2:

是的!我找到了一种解决方法:而不是保存事件然后将其重新插入 DOM。我们可以调用this.delegateEvents()来重新绑定所有事件。这确实只是一种解决方法,如果有人能给我一个例子,我会很高兴:)

4

1 回答 1

2

就个人而言,我更喜欢重建我的观点。

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

于 2012-09-01T12:29:30.683 回答