2

我有一個工作解決方案,用於在我正在處理的Marionette應用程序的區域中呈現佈局視圖,但有些事情對此感覺不太正確。你是否需要直接向DOM添加任何內容?在Marionette/Backbone.js中呈現佈局和子視圖

這是我在控制器方法:

//Grab the main Layout 
     var layout = new APP.Views.LayoutView(); 

     //Render that layout 
     layout.render(); 

     //Make the model 
     var simpleModel = new APP.Models.simpleModel({ 
      "field1" : "foo", 
      "field2" : "bar" 
     }); 


     layout.header.show(new APP.Views.subView({model: simpleModel})); 

     $('body').html(layout.el); 

就這麼不自然的感覺給我的最後一部分。這主要是因爲如果我將'layout.header.show'移動到.html()之後,那麼它不能正確呈現。如果它們在推送到DOM後不能動態變化,那麼區域的重點是什麼?

這裏是我的佈局:

APP.Views.LayoutView = Backbone.Marionette.Layout.extend({ 

    template: "#layoutTemplate", 

    className : 'wrapper', 

    regions: { 
    header: "#header", 
    footer: "#footer" 
    } 


}); 

,這裏是副視點:

APP.Views.subView = Backbone.Marionette.ItemView.extend({ 

    template : '#headerTemplate', 

    className: 'container' 


}); 

正如我所說的,這個作品,但它就像我沒有使用正確的區域感覺。有沒有更好,更簡潔的方法來實現這一點,讓您在將佈局切換到DOM後訪問區域?

Marionette documentation似乎沒有提到使用.html()獲取頁面上的東西 - 我想知道是否因爲它不需要或假定它被遺漏了。

任何人都可以幫忙嗎?

回答

4

好吧,看起來這可以通過在應用程序中創建一個'區域'來避開,然後使用.show()來顯示其內部的佈局。

這裏是一個小提琴我對SO發現幫助的鏈接:http://jsfiddle.net/TDqkj/6/

以及另一個問題:Understanding layouts in Marionette for Backbone.js

尤其是小提琴有這樣的代碼:

App = new Backbone.Marionette.Application(); 
App.addRegions({ 
    'nav': '#nav', 
    'content': '#content' 
}); 

程序員可以使用它將佈局添加到這些區域 - 這意味着您永遠不需要追加到DOM。

如果其他人有更優雅的解決方案,請發佈!