2013-08-26 46 views
3

我当前的代码看起来是这样的:如何正确使用Marionette布局?

define([ 
    'jquery', 
    'underscore', 
    'backbone', 
    'marionette', 
    'templates', 
    'gridView', 
    'detailView', 
    'detailModel' 
], function ($, _, Backbone, Marionette, JST, GridView, DetailView, DetailModel) { 

    'use strict'; 

    return Marionette.Layout.extend({ 

     el: '#main', 

     template: JST['app/scripts/templates/main.ejs'], 

     initialize: function() { 
      this.render(); 
     }, 

     onRender: function() { 
      var Layout = Marionette.Layout.extend({ 
       el: 'div', 

       template: _.template(""), 

       regions: { 
        grid: '#grid', 
        detail: '#detail' 
       } 
      }); 
      this.layout = new Layout(); 
      this.layout.render(); 
     }, 

     showGrid: function() { 
      var detailModel = new DetailModel(); 

      var g = new GridView(detailModel); 
      var d = new DetailView(detailModel); 

      this.layout.grid.show(g); 
      this.layout.detail.show(d); 
     } 

    }); 

}); 

我不明白的是为什么我需要一个额外的布局我的OnRender方法来完成这项工作。该“#grid”和“#detail”的div是main.ejs模板的一部分,但下面不工作:

return Marionette.Layout.extend({ 

    el: '#main', 

    template: JST['app/scripts/templates/main.ejs'], 

    regions: { 
     grid: '#grid', 
     detail: '#detail' 
    }, 

    initialize: function() { 
     this.render(); 
    }, 

    onRender: function() { 
     var detailModel = new DetailModel(); 

     var g = new GridView(detailModel); 
     var d = new DetailView(detailModel); 

     this.grid.show(g); 
     this.detail.show(d); 
    } 

}); 

看来,如果在区域对象指定的元素已经布局只能在布局创建时存在。但是文件表明情况并非如此。

我可能做错了什么。但是什么?

问候 罗杰

回答

2

作为一个额外的警告,在onRender调用.show()方法可以负面影响嵌套在该布局下的任何东西,特别是如果您试图在后面使用onShow以确保视图的DOM子树是jQuery可访问的。

.show()触发一个“秀”事件跨布局中的任意子视图,并可能意味着onShow()就是所谓的那些子视图(其监听“秀”事件)的子视图已呈现,并插入其内容之前。

+2

作为附录,如果您使用Marionette 1.8,您现在可以利用[onDomRefresh](https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.view.md#view- domrefresh - ondomrefresh-event),这将确保最初呈现的内容和新呈现的内容完全存在于DOM中。 –