Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Views within Views? How to generate lists of items with Backbone.js?

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.

like image 776
Phillip B Oldham Avatar asked Jan 23 '11 20:01

Phillip B Oldham


1 Answers

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
like image 144
jashkenas Avatar answered Oct 09 '22 17:10

jashkenas