视图中的视图?如何使用 Backbone.js 生成项目列表?

发布于 2024-10-13 14:42:27 字数 821 浏览 1 评论 0原文

我正在尝试构建一个项目列表(例如书籍),然后我想允许用户过滤该列表(例如按作者)。我希望列表中的每个项目都有自己的视图,并且列表本身也有一个视图。然而,我似乎无法“看到”它们如何在 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}))

我想了解的是如何使用自己的视图+模板创建列表中的每个

  • 元素,以便我可以过滤他们由作者。
  • 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.

    如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

    扫码二维码加入Web技术交流群

    发布评论

    需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

    评论(1

    太阳男子 2024-10-20 14:42:27

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

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

    render: ->
      $(this.el).html this.template()
      bookHTML = for book in Books
        (new BookView model: book).render().el
      this.$('.book_list').append bookHTML
    

    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
    
    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文