how to switch views with the backbone.js router?

房东的猫 提交于 2019-12-01 22:49:46

You can use an utility object like this :

var ViewManager = {
    currentView : null,
    showView : function(view) {
        if (this.currentView !== null && this.currentView.cid != view.cid) {
            this.currentView.remove();
        }
        this.currentView = view;
        return view.render();
    }
}

and whenever you want to show a view use ViewManager.showView(yourView)

App.Router = Backbone.Router.extend({
    routes: {
        '' : 'index',
        'addnew' : 'addNew',
        'contacts/:id' : 'singleContact',
        'contacts/:id/edit' : 'editContact'
    },

    index: function(){
        var indexView ...
        ViewManager.showView(indexView);
    },

    addNew: function() {
        var addNewView ...
        ViewManager.showView(addNewView);
    },

    singleContact: function(id) {
        var singleContactView ...
        ViewManager.showView(singleContactView);
    },

    editContact: function(id) {
        var editContactView ...
        ViewManager.showView(editContactView);
    },

});

So it's the ViewManager that's responsible of rendering your views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!