Marionette CompositeView不能递归渲染

时间:2015-11-29 21:58:29

标签: javascript backbone.js marionette

我试图通过不指定childView来使Marionette的CompositeView递归呈现。 jQuery给了我以下错误:

Uncaught HierarchyRequestError: Failed to execute 'appendChild' on 'Node': The new child element contains the parent.

这是我在HTML中使用的模板。我知道它会变得难看。我不在乎。我只是想让CompositeView以递归方式呈现(即使用相同的模板在不使用childView的情况下打印出Collection中的所有内容)。

<script type="text/template" id="table-tpl">
  <table border="1">
    <thead>
      <tr>
        <th>Book Title</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
  <footer><p><%- title %></p></footer>
</script>

这是我的Javascript

// Working with Collections example
var App = new Marionette.Application();

// Create Model
App.Book = Backbone.Model.extend();

// Create ItemView
App.BookView = Marionette.ItemView.extend({
  template: "#row-tpl",
  tagName: "tr"
});

// Create a Collection
App.Library = Backbone.Collection.extend({
  model: App.Book
});

// Create a CompositeView
App.BookShelf = Marionette.CompositeView.extend({
  // childView: App.BookView,
  // childViewContainer: "tbody",
  template: "#table-tpl",
  el: '.target'
});

// What should happen on Start
App.on("start", function(){

  // Instantiate some Models
  App.book1 = new App.Book({title: 'Grapes of Wrath'});
  App.book2 = new App.Book({title: 'Who moved my Cheese'});
  App.book3 = new App.Book({title: 'The Alchemist'});
  App.book4 = new App.Book({title: 'Great Books'});

  // Instatiate and populate the Collection
  App.library = new App.Library([App.book1, App.book2, App.book3]);

  // Instatiate the CompositeView
  App.bookshelf = new App.BookShelf({
    // Model is available in template
    model: App.book4,
    // But the CompositeView will loop through collection
    collection: App.library
  });

  // Render the CollectionView
  App.bookshelf.render();

  alert('When book1 is removed from the library, it will be removed from the DOM');
  App.library.remove(App.book1);
});

App.start();

1 个答案:

答案 0 :(得分:0)

尝试将el移出定义,然后转到

// Instatiate the CompositeView
App.bookshelf = new App.BookShelf({
  // Model is available in template
  model: App.book4,
  // But the CompositeView will loop through collection
  collection: App.library,
  el: '.target'
});

我认为问题在于您以递归方式将el设置为相同的元素,以便它附加并尝试将childViewContainer替换为父节点。