12

我正在尝试建立一个项目列表(例如书籍),然后我想允许用户过滤这个列表(例如按作者)。我希望列表中的每个项目都有自己的视图,并且列表本身也将有一个视图。但是,我似乎无法“看到”它们如何在 Backbone 中组合在一起。

目前,我的代码如下(咖啡脚本):

class Book extends Backbone.Model

class BookList extends Backbone.Collection
  model: Book
  url: "/library/books.json"

books = new BookList

class BookListView extends Backbone.View
  initialize: ->
    @template = _.template('''
      <ul>
        <% books.each(function(book){ %>
          <li><%= book.get('title') %>, <%= book.get('author') %></li>
        <% }); %>
      </ul>
    ''')
    @render

  render: ->
    template = @template
    books.fetch success: -> jQuery("#books").html(template({'books': books}))

我想了解的是如何<li>使用自己的视图+模板创建列表中的每个元素,以便我可以按作者过滤它们。

4

1 回答 1

11

虽然当然可以这样写,但如果你有模板嵌套视图嵌套模板,那么事情可能会变得复杂......

相反,为什么不将您的 Book 视图插入到列表中:

render: ->
  $(this.el).html this.template()
  bookHTML = for book in Books
    (new BookView model: book).render().el
  this.$('.book_list').append bookHTML
于 2011-01-25T14:42:23.910 回答