使用backbone.js 清理视图? [英] Cleaning views with backbone.js?

查看:21
本文介绍了使用backbone.js 清理视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个backbone.js 应用程序并且已经达到了我有许多路由器和视图代表我的应用程序的每个部分的地步.在下面的简化路由器示例中,我有两个位置;账户 &用户.

I am working on a backbone.js-application and have reached the point where I have a number of routers and views representing each part of my application. In the simplified router example below, I have two locations; account & users.

每个位置的两个视图都将它们的内容渲染到一个名为 #appcontainer 的相互元素中.我的常识是,我应该确保remove每个视图在启动另一个视图之前,以防止绑定、DOM 和诸如此类的冲突.

Both view in each location render their content to a mutual element, named #appcontainer. My common sense says that I should make sure to remove each view before launching another to prevent collisions in bindings, DOM and whatnot.

但由于我无法确定是否已创建视图,因此我无法从路由器内部或视图中显式调用 previousView.remove().

But as I cannot know for sure whether a view already has been created, I cannot explicitly call previousView.remove() either from inside my router or views.

$(this.el).empty() 添加到每个视图的构造函数中是否足以清除 DOM 中任何最终的先前绑定和元素?

Would it be sufficient to add $(this.el).empty() to the constructor of each view to clean out any eventual previous bindings and elements from the DOM?

这是路由器示例?

var myRouter = Backbone.Router.extend({

    routes: {
        "account": "account",
        "users": "users"
    },

    account: function() {
        view = new AccountView({});
        view.render();
    },

    users: function() {
        view = new UserView({});
        view.render();
    }

});

推荐答案

我有一个非常简单的实现,我现在才开始我的应用程序,不知道从长远来看这会如何,但是它看起来像这样:

I have a really simple implementation, I'm just starting my application now and don't know how this is going to hold up in the long run, but it looks something like this:

这是整个文件的样子.this.render 将是 myRouter 的另一个功能.

Here's what the entire file would look like. this.render will be another function of myRouter.

var myRouter = Backbone.Router.extend({
    routes: {
        'path/to/account' : 'account',
        'path/to/users': 'users'
    }

    account: function() {
        view = new AccountView({});
        this.render(view);
    },

    users: function() {
        view = new UserView({});
        this.render(view);
    },

    render: function (view) {
        //Close the current view
        if (this.currentView) {
            this.currentView.remove();
        }

        //render the new view
        view.render();

        //Set the current view
        this.currentView = view;

        return this;
    }
});

这篇关于使用backbone.js 清理视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆