2014-11-04 67 views
1

我无法渲染Marionette LayoutView并在该布局中显示区域。Backbone Marionette LayoutView无法找到DOM元素

我的布局文件:

template: '#fooTemplate', 
    regions: { 
     barRegion: '.bar' 
    } 

我的HTML:

<script id="fooTemplate" type="text/template"> 
    <div id="fooDiv"> 
     <div class="bar"> 
     </div> 
    </div>   
</script> 

呈现的布局和显示区域代码:

var FooLayout = require('./browserify/path'); 
var fooLayout = new FooLayout({el:"#fooDiv"}) 

collectionView = new CollectionView({ 
    collection: collection 
}); 
fooLayout.render(); 
fooLayout.barRegion.show(collectionView); 

我得到一个错误未被捕获的错误: DOM中的“el”#foo .bar必须存在

我在LayoutView的功能中缺少什么?我有一个类似的例子工作得很好,但由于某种原因,我无法复制它。

回答

4

发生这种情况是因为视图与DOM分离。如果指定{el:"#fooDiv"},则#fooDiv元素必须位于DOM中。我想应该是这样的:

<script id="fooTemplate" type="text/template"> 
    <div class="bar"></div>  
</script> 

添加#fooDiv HTML标记

<body> 
    ... 
    <div id="fooDiv"></div> 
    ... 
</body> 

,然后你可以做

// "wrap" new Layout around existing div 
new FooLayout({ el: '#fooDiv' }); 
// etc. 

// create a new DOM element with the id 'fooDiv': 
var fooLayout = new FooLayout({ id: 'fooDiv' }); 
fooLayout.render(); 
document.body.appendChild(fooLayout.el); // or $('body').append(fooLayout.el);