使用Backbone更改页面视图

时间:2013-11-20 00:00:55

标签: javascript backbone.js marionette

我在Backbone.js的单页应用程序中实现了“更改页面”。但是,我不确定我的路由器是否应包含如此多的业务逻辑。我应该考虑使用Marionette.js来实现这样的功能并使我的路由器变瘦吗?我应该担心在我更改它时(为了避免内存泄漏)破坏附加到“上一个”活动页面/视图的Backbone模型和视图,或者它足以清空附加到这些模型/视图的html。 这是我的路由器:

App.Router = Backbone.Router.extend({
    routes: {
        'users(/:user_id)' : 'users',
        'dashboard' : 'dashboard'
    },
    dashboard: function() {
        App.ActiveView.destroy_view();
        App.ActiveViewModel.destroy();

        App.ActiveViewModel = new App.Models.Dashboard;
        App.ActiveViewModel.fetch().then(function(){
            App.ActiveView = new App.Views.Dash({model: App.ActiveViewModel });
            App.ActiveView.render();
        });
    },

    users: function(user_id) {
        App.ActiveView.destroy_view();
        App.ActiveViewModel.destroy();

        App.ActiveViewModel = new App.Models.User;
        App.ActiveViewModel.fetch().then(function() {
            App.ActiveView =  new App.Views.UsersView({model: App.ActiveViewModel});
            App.ActiveView.render();
        });
    }
});

1 个答案:

答案 0 :(得分:0)

另一种方法:

创建AbstractView

声明AbstractView,然后从View's扩展您的其他特定应用AbstractView有很多优点。您总是有一个View,您可以在其中放置所有常用功能。

App.AbstractView = Backbone.View.extend({
    render : function() {
        App.ActiveView && App.ActiveView.destroy_view();
        // Instead of destroying model this way you can destroy 
        // it in the way mentioned in below destroy_view method.
        // Set current view as ActiveView
        App.ActiveView = this;
        this.renderView && this.renderView.apply(this, arguments);
    },
    // You can declare destroy_view() here
    // so that you don't have to add it in every view.
    destroy_view : function() {
        // do destroying stuff here
         this.model.destroy();
    }
});

App.Views.UsersView AbstractView应该从renderView延伸,并render代替AbstractView's,因为renderView呈现将调用Router。从render开始,您可以App.ActiveView.render();

的方式拨打App.Views.UsersView = AbstractView.extend({ renderView : function() { } // rest of the view stuff }); App.Views.Dash = AbstractView.extend({ renderView : function() { } // rest of the view stuff });
 dashboard: function() {
        App.ActiveViewModel = new App.Models.Dashboard;
        App.ActiveViewModel.fetch().then(function(){
            new App.Views.Dash({model: App.ActiveViewModel }).render();
        });
    }

路由器代码将更改为:

{{1}}