2016-11-12 53 views
0

通常,用戶通過主頁進入網站,然後在那裏呈現側欄視圖。接下來,用戶單擊鏈接,路由器呈現另一個視圖並替換原始內容視圖。側欄視圖不會被重新渲染。如何檢查側欄視圖是否已在主幹中呈現?

當用戶在子頁面上單擊刷新時,側欄不會呈現。

如何檢查視圖是否存在並已呈現?

回答

2

拆分責任並堅持下去。不要將側邊欄渲染放在主頁視圖的手中。

你可以有一個佈局視圖負責處理渲染內容頁腳側邊欄。然後,當用戶導航到另一個頁面時,路由器會在佈局視圖上調用諸如setContent(view)之類的東西,從而確保在渲染內容之前渲染邊欄(以及其他所有內容)。

假設這個模板:

<body> 
    <div class="header"></div> 
    <div class="content"></div> 
    <div class="sidebar"></div> 
</body> 

佈局視圖可能是簡單的:

var Layout = Backbone.View.extend({ 
    el: 'body' // just for the simple example, let's put this as the body. 

    // This avoids repeating selector strings everywhere in the view code. 
    // If you change a class name in the template, change it only once here. 
    regions: { 
     header: '.header', 
     content: '.content', 
     sidebar: '.sidebar' 
    }, 
    initialize: function(options) { 
     var regions = this.regions; 

     // I like to "namespace" my sub-views into an object. 
     // That way, you still can access them by name, but you can also 
     // loop on the sub-views. 
     this.views = { 
      sidebar: new SideBar({ el: regions.sidebar }), 
      header: new Header({ el: regions.header }), 
     }; 

     this.$content = this.$(regions.content); 
    }, 

    render: function() { 
     _.invoke(this.views, 'render'); 
     return this; 
    }, 

    /** 
    * Set the content to a view. 
    * @param {Backbone.View} view to replace the content with. 
    */ 
    setContent: function(view) { 
     var views = this.views, 
      content = views.content; 
     if (content !== view) { 
      if (content) content.remove(); 
      views.content = content = view; 
      this.$content.html(content.render().el); 
     } 
    }, 
}); 

和路由器可以懶洋洋地創建視圖:

var AppRouter = Backbone.Router.extend({ 
    routes: { 
     '*otherwise': 'homepage', 
     'specific/:id': 'specificPage' 
    }, 
    initialize: function() { 
     this.layout = new Layout(); 
     this.layout.render(); 
     this.views = {}; 
    }, 
    homepage: function() { 
     // These local variables improve minification and readability. 
     var views = this.views, 
      homepage = views.homepage; 
     if (!homepage) { 
      views.homepage = homepage = new HomePage(); 
     } 
     this.layout.setContent(homepage); 
    }, 
    specificPage: function(id){ 
     var views = this.views, 
      specific = views.specific; 
     if (!specific){ 
      views.specific = specific = new HomePage(); 
     } 
     specific.setId(id); // hypothetical logic 
     this.layout.setContent(specific); 
    } 
}); 
相關問題