how to switch views with the backbone.js router?

前端 未结 1 785
执笔经年
执笔经年 2021-01-19 15:07

This is more of a conceptual question, in terms of using the backbone router and rendering views in backbone.

for the sake of an example (what I\'m building to learn

相关标签:
1条回答
  • 2021-01-19 15:48

    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

    0 讨论(0)
提交回复
热议问题