Turning off div wrap for Backbone.Marionette.ItemView

前端 未结 5 1804
闹比i
闹比i 2020-12-07 15:03

I\'m looking at the Angry Cats Backbone/Marionette tutorial posts here

http://davidsulc.com/blog/2012/04/15/a-simple-backbone-marionette-tutorial/

http://dav

5条回答
  •  醉酒成梦
    2020-12-07 15:25

    For IE9+ you could just use firstElementChild and childElementCount:

    var Layout = Backbone.Marionette.LayoutView.extend({
    
      ...
    
      onRender: function () {
          if (this.el.childElementCount == 1) {
              this.setElement(this.el.firstElementChild);
          }
      }
    
      ...
    
    });
    

    There is a good reason why Marionette automatically inserts the wrapper DIV. It's only when your template consists of just one element when you can drop it. Hence the test for number of child elements.

    Another option is to use the attachElContent method present in every Marionette view. Its default implementation means re-renders of the view will overwrite the root element's inner HTML. This ultimately gives rise to the infinite nesting mentioned in bejonbee's answer.

    If you would rather not overwrite onRender and/or require a pure-JS solution, the following code might be just what you want:

    var Layout = Backbone.Marionette.LayoutView.extend({
    
      ...
    
      attachElContent: function (html) {
          var parentEl = this.el.parentElement;
          var oldEl;
    
          //View already attached to the DOM => re-render case => prevents
          //recursive nesting by considering template's top element as the
          //view's when re-rendering
          if (parentEl) {
              oldEl = this.el;
              this.setElement(html);                   //gets new element from parsed html
              parentEl.replaceChild(this.el, oldEl);   //updates the dom with the new element 
              return this;
    
          //View hasn't been attached to the DOM yet => first render 
          // => gets rid of wrapper DIV if only one child
          } else {
              Marionette.ItemView.prototype.attachElContent.call(this, html);
              if (this.el.childElementCount == 1) {
                  this.setElement(this.el.firstElementChild);
              }
              return this;
          }
      }
    
      ...
    
    });
    

    Note that for re-rendering to work, the code assumes a template with a single child that contains all markup.

提交回复
热议问题