视图中的视图?如何使用 Backbone.js 生成项目列表?
我正在尝试构建一个项目列表(例如书籍),然后我想允许用户过滤该列表(例如按作者)。我希望列表中的每个项目都有自己的视图,并且列表本身也有一个视图。然而,我似乎无法“看到”它们如何在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虽然当然可以这样写,但如果您有模板嵌套视图嵌套模板,那么事情可能会变得复杂……
相反,为什么不将 Book 视图插入列表中:
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: