سؤال

I'm trying to build a list of items (eg. books) and I would like to then allow the user to filter this list (eg. by author). I would expect that each item in the list would have it's own view, and that the list itself would also have a view. I can't seem to "see" how these fit together in Backbone, however.

Currently, my code is as follows (coffee-script):

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

What I'd like to understand is how to create each <li> element in the list with it's own view+template so I can filter them by author.

هل كانت مفيدة؟

المحلول

While it's certainly possible to write it that way, things can get convoluted if you have templates nesting views nesting templates, ad infinitum...

Instead, why not insert your Book views into the list:

render: ->
  $(this.el).html this.template()
  bookHTML = for book in Books
    (new BookView model: book).render().el
  this.$('.book_list').append bookHTML
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top