【发布时间】:2013-10-14 19:32:26
【问题描述】:
我将从一个明确的问题开始,然后解释:
如何正确地将包含在 CompositeView 中的模型封装到 ItemView 中
我的问题很简单,但我无法设法让一些好的工作。
我有一棵笔记树。
每个笔记都是一个 Backbone.model 并且有一个 @descendants 集合,
然后我有一个 Backbone.Collection 来代表那棵树(其中@descendants 是一个实例)
我设置了一个基本的CollectionView,作为itemView,CompositeView。一切都完美呈现,我对此感到非常高兴。此工作解决方案显示在代码的第一个 sn-p 中!
问题来了。在此基础上,我遇到了这个问题:Events fired for whole hierarchy 这对于我的事件如何绑定是有意义的。起初,我只是简单地添加了独特的选择器(将 data-guid 添加到我的 html 元素中,以便我可以通过它获取它们)并且它工作正常,尽管它已经变得“hacky”。但是其他类似的问题已经出现,所以我决定我需要一个解决方案。 所以,我告诉 myslef,让我们将每个模型封装在一个 ItemView 中,并使用 Composite 视图递归地渲染它们。 但是……这并不是世界上最好的……
这是我一开始的:
class Note.ModelView extends Marionette.CompositeView
template: "note/noteModel"
id: "note-item"
itemViewContainer: ".note-descendants"
ui:
noteContent: ".noteContent"
events:
"keypress .noteContent": "createNote"
"click .destroy": "deleteNote"
# ...
initialize: ->
@collection = @model.descendants
# ...
class Note.CollectionView extends Marionette.CollectionView
id: "note-list"
itemView: Note.ModelView
initialize: ->
@listenTo @collection, "sort", @render
现在我将所有属于渲染模型的东西都转移到了一个新的 ItemView 中
class Note.ModelView extends Marionette.ItemView
template: "note/noteModel"
ui:
noteContent: ".noteContent"
events: ->
guid = @model.get 'guid'
events = {}
events["keypress #noteContent#{guid}"] = "createNote"
events["blur #noteContent#{guid}"] = "updateNote"
events["click #destroy#{guid}"] = @triggerEvent 'deleteNote'
initialize: ->
@bindKeyboardShortcuts()
@listenTo @model, "change:created_at", @setCursor
class Note.TreeView extends Marionette.CompositeView
template: "note/parentNote"
itemView: Note.ModelView
initialize: ->
@collection = @model.descendants
@listenTo @collection, "sort", @render
_.bindAll @, "renderItem"
renderItem: (model) ->
if model.get('parent_id') is 'root'
itemView = new Note.ModelView model: model
itemView.render()
@$el.append itemView.el
onRender: ->
@collection.each this.renderItem
@renderItem @model
appendHtml: (collectionView, itemView) ->
@model.descendants.each (note) =>
iv = new Note.ModelView model: note
iv.render()
@.$('.note-descendants').append iv.el
class Note.CollectionView extends Marionette.CollectionView
id: "note-list"
itemView: Note.TreeView
initialize: ->
@listenTo @collection, "sort", @render
还有noteMode模板(parentNote现在只是一个空模板)
<button class="btn btn-danger btn-xs untab">UN</button>
<button class="btn btn-success btn-xs tab">TAB</button>
<div class="noteContent">{{{indent}}}{{{title}}}</div>
<button class="destroy"></button>
<div class="note-descendants"></div> # That is where I'm putting the children notes
所以这几乎可以工作了。但它很老套,而且......好吧,它仍然不能正常工作。我一直在阅读所有文档,并且我已经阅读了这两个链接Derick Bailey on nested structure and CompositeView 和 David Sulc on Nested Views,但我仍然觉得我遗漏了一些重要的细节。
作为答案,我正在寻找的是使用 Marionette 管理此问题的任何提示或任何常用方法。我真的在寻找干净的东西,因为这将是构建应用程序的角度之一。
也许我也在错误的地方搜索?任何事情都会受到欢迎!!非常感谢
祝大家有个愉快的夜晚。 感谢您的宝贵时间。
【问题讨论】:
-
感谢您链接问题中已经存在的链接!..
标签: javascript backbone.js recursion marionette