javascript – 如何避免Backbone Marionette Region或LayoutView中的额外div
作者:互联网
我们使用Backbone,Marionette和车把作为我的应用程序.当我尝试在Marionette.Region中渲染我的视图时,一个额外的div包裹在模板周围.我怎么能避免这种情况.
HTML代码:
<div id="mainDiv"></div>
<script type="text/x-handlebars-template" id="basic">
<div id="first"></div>
<div id="second"></div>
</script>
js代码:
//function
var templateCompilation=function(templateId,data){
var alertCompilation=Handlebars.compile(document.getElementById(templateId).innerHTML);
return alertCompilation(data);
};
//Application
myApp = new Backbone.Marionette.Application();
myApp.addRegions({
mainContainer:"#mainDiv"
});
myApp.start();
//first view
var basicView=Marionette.ItemView.extend({
template:function(){
return templateCompilation("basic",{});
}
});
//reding view
var basicViewObj=new basicView();
myApp.mainContainer.show(basicViewObj);
为了避免额外的div,我尝试以下陈述我的运气不好无效.
var basicViewObj=new basicView({el:$("#mainDiv")});
var basicViewObj=new basicView({tagName:""});
谁能帮我.
解决方法:
重要更新:
该行下面的代码不起作用.我没有测试就写了它(在我的手机上).以下更新已经过测试,并纳入了@vzwick建议的重要评论.
如下所述,覆盖Region中的attachHtml.我们将在下面的评论中对attachHtml进行三个重要更改
myApp.mainContainer.attachHtml = function (view) {
// empty the node and append new view
this.el.innerHTML="";
// All view elements are attached to that view's el, which acts as a
// container for that view. The OP wants to get rid of that container
// and use the region's el instead. So first get the children of the
// view that we want to show in the Region
var children = view.el.childNodes;
// Now pop each child element into the el of the Region
// Note that Node.appendChild(Node) removes the first element from the
// Node array on each iteration so children[0] will be the next
// child for each iteration
while (children.length > 0) {
this.el.appendChild(children[0]);
}
// Finally, assign a new el to the view:
// view.setElement(element, delegate) is a Backbone method
// that reassigns the el of the *view* to the parameter *element*
// and if delegate = true, re attaches the events to the new el
view.setElement(this.el, true)
}
需要注意的重要一点是,OP的basicView现在与myApp.mainContainer共享其el.由于myApp.mainContainer是一个Region,并且它不接受事件参数,因此如果重新委派事件,则不存在冲突的可能性.如果它与LayoutView一起使用也是如此,因为事件的重新委派将发生在LayoutView Region el而不是LayoutView el上,那么应该没有冲突.
旧帖子的开头
我之前没有尝试过,但我从功能和结构层面对你的问题很敏感.我建议你做的是覆盖Region的attachHtml函数.
默认情况下,Backbone.Marionette的attachHtml正在这样做
attachHtml: function(view) {
// empty the node and append new view
this.el.innerHTML="";
this.el.appendChild(view.el);
}
要更改此功能,您可以在您的Region中定义一个新的attachHtml,如下所示:
attachHtml: function(view) {
// empty the node and append new view
this.el.innerHTML="";
this.el.appendChild(view.el.childNodes);
}
现在,Region el将直接附加您在该区域中显示的视图的内部节点.
要覆盖mainContainer区域的原始attachHtml,您将使用Application变量,即
myApp.mainContainer.attachHtml = function (view) { ... }
使用上面编写的代码示例.
标签:javascript,backbone-js,marionette 来源: https://codeday.me/bug/20191008/1874489.html