How to avoid an extra div in a Backbone Marionette Region or LayoutView

≡放荡痞女 提交于 2019-12-01 11:15:47

Important Update:

The code below the line will not work. I wrote it without testing it (was on my mobile). The following update has been tested and incorporated the important comment suggested by @vzwick.

As explained below, override attachHtml in the Region. We are going to three important changes to attachHtml as annotated in the comments below

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)
}

The important thing to note is that the OP's basicView now shares its el with myApp.mainContainer. Since myApp.mainContainer is a Region and it does not take an event parameter there isn't a chance of there being conflicts if events are re-delegated. The same is true if this is used with a LayoutView since the re-delegation of events would happen to the LayoutView Region el, and not the LayoutView el, then there should be no conflicts.


Beginning of old post

I haven't tried this before, but I'm sensitive to your problem from a functional and structural level. What I suggest you do is override the Region's attachHtml function.

By default Backbone.Marionette's attachHtml is doing this

attachHtml: function(view) {
    // empty the node and append new view
    this.el.innerHTML="";
    this.el.appendChild(view.el);
}

To change this functionality you could define a new attachHtml in your Region like the following:

attachHtml: function(view) {
    // empty the node and append new view
    this.el.innerHTML="";
    this.el.appendChild(view.el.childNodes);
}

Now the Region el will directly append the inner nodes of the view that you're showing in that region.

To override the original attachHtml of the mainContainer region you would use your Application variable, i.e.

myApp.mainContainer.attachHtml = function (view) { ... }

with the code example written above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!