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

查看:99
本文介绍了用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 。我的常识说我应该确保 删除 每个视图,然后再启动另一个视图,以防止绑定,DOM和whatnot中的冲突。

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.

是否足够将$ code> $(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:

编辑: strong>这是整个文件的外观。 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天全站免登陆