8

我想我可能会对如何使用Marionette.Layout有个根本的误解。了解Marionette中的布局Backbone.js

我想是这样的:

enter image description here

布局包括两个Marinotette.ItemView S:在 “爆炸” ItemView和 “PopStar” ItemView。这种布局的设计总是包含这些意见,所以我试着这样做:

var TheLayout = Backbone.Marionette.Layout.extend({ 
    template: '#the=layout-template', 
    regions: { 
     explode: '#explode-region', 
     popstar: '#popstar-region' 
    } 
    initialize:function(options){ 
     _.bindAll(this); 

     var explodeView = new ExplodeView(); 
     this.explode.show(explodeView);  // <-- This throws and exception because the regions are not available yet 

    } 
}) 

但它看起来像的区域不可用,直到布局之后被渲染。在添加视图之前,我尝试调用this.render(),但这不起作用。我很确定这里的根本问题是我在错误的情况下应用布局。

在这种情况下我该怎么做?何时正确使用Marionette.Layout

谢谢!

回答

17

在布局的onRender方法中显示区域视图。代码:

var TheLayout = Backbone.Marionette.Layout.extend({ 
    template: '#the=layout-template', 
    regions: { 
     explode: '#explode-region', 
     popstar: '#popstar-region' 
    } 
    onRender: function() { 
     var explodeView = new ExplodeView(); 
     this.explode.show(explodeView); 
    } 
}) 

请注意,在这种情况下_.bindAll(this)是不需要的。

+1

关于'_.bindAll(this)'我仍然在什么情况下使用它以及在什么情况下不知道。 – CodeRain 2012-09-26 13:13:54

+4

对于大多数由Marionette直接调用的方法,例如事件处理程序和onRender,onClose,上下文由Marionette正确设置,并且不需要bindAll。如果有人正在调用你的方法,说一个来自AJAX的jQuery回调或直接使用jquery绑定事件,并且你希望上下文'this'仍然是视图,那么'_.bindAll(this,'myfunc')'是你的朋友。 – 2012-09-26 17:26:04

+0

救了我一天:) – SAR 2013-07-24 11:49:47