簡體   English   中英

使用骨干網更改頁面視圖

[英]Change page view with Backbone

我已經使用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();
        });
    }
});

另一種方法:

創建一個AbstractView

聲明一個AbstractView ,然后從AbstractView擴展您的其他應用程序特定的View's具有許多優點。 您始終擁有一個可以放置所有常用功能的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 App.Views.UsersView代替render因為AbstractView's render將調用renderView 您可以從Router調用render ,方法與App.ActiveView.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();
        });
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM