0

这是使用 Marionette 时仍然让我感到困惑的一件事。

想象一个用于查看评论列表和发表新评论的简单界面。我目前构建它的方式与CommentApp我在下面包含的类似。

我想我的问题有两个部分:

这是我应该如何构建这种类型的应用程序吗?我尝试尽可能遵循BBCloneMail 示例应用程序,但这似乎没有提供将新项目创建到集合中的示例。

为什么layout.listRegion下面会返回undefined我尝试调用.show()它的地方?更一般地说,是否有一种确定的方法来处理触发和绑定到'layout:rendered'具有嵌套布局的事件。它似乎变得相当混乱。

App.module "CommentApp", (CommentApp, App, B, M, $, _) ->
  class Layout extends M.Layout
    template: 'comment_layout'

    regions:
      listRegion: '#comment_list_region'
      newRegion: '#new_comment_region'

  class CommentView extends M.ItemView
    # this is as you would expect

  class NewCommentView extends M.ItemView
    # this is as you would expect
    # This view triggers a 'new:comment' on the CommentApp.vent
    # event aggregator when the user submits a new comment.

  class CommentsListView extends M.CollectionView
    # this is as you would expect
    # This view listens to the 'new:comment' event on the
    # CommentApp.vent event aggregator.

  # Public API
  # ----------

  CommentApp.showComments = (comments) ->
    # In here I need to render a layout
    layout = new Layout()

    # I also need to render a comments list an the
    # view for writing a new comment.
    commentsListView = new CommentsList(collection: comments)
    newCommentView = new NewCommentView()

    # THen I need to place these views into the layout when ready.
    layout.on "show", ->
      # This part fails because it seems that the layout.listRegion
      # is not yet defined for some reason. Don't understand why?
      layout.listRegion.show(commentsListView)
      layout.newRegion.show(newCommentView)

    # Now I need to stick the commenting layout into it's
    # place in the main app layout.
    App.layout.mainRegion.show(layout)


  App.addInitializer (options) ->
    @vent.bind "layout:rendered", -> CommentApp.showComments(comments)

'comment_layout'模板只是一个基本的容器模板:

<h2>Comments</h2>
<section id="comment_list_region"></section>
<section id="new_comment_region"></section>

我正在使用JST它来渲染它。我已经用这段代码覆盖了渲染函数:

# Override the marionette renderer to make it use JST.
Backbone.Marionette.Renderer.render = (template, data) ->
  # Check if a template is specified first.
  if template
    throw "Template '" + template + "' not found!" unless JST[template]
    JST[template](data)
4

1 回答 1

2

结构

您的应用程序通常按照我的方式构建。不过,有几点我会改变。

例如,您不需要使用初始化程序来为“layout:rendered”设置事件绑定。你可以这样做:

App.vent.bind "layout:rendered", -> CommentApp.showComments(comments)

在这种情况下,在初始化程序内部设置事件绑定没有任何实际价值。

布局

为什么下面的 layout.listRegion 在我尝试调用 .show() 的地方返回未定义?

......我不确定......虽然这段代码看起来有点奇怪:App.layout.mainRegion.show(layout)

这是故意的App.mainRegion.show(layout)吗?

当布局的render方法被调用时,布局的区域将被实例化。在区域中显示布局将调用布局的render方法,并监听show布局事件以在布局区域中显示内容应该可以正常工作。事实上,我经常这样做。

不过,我最近看到了一些类似问题的报告,我认为这里有一个我无法隔离的错误。

模板comment_template指的是什么?这是某个地方的预编译模板吗?您是否覆盖了模板的呈现?如果是这样,您可以发布处理此问题的代码吗?

如果您console.dir(layout)在布局的“显示”事件处理程序内部进行操作,它会返回什么?你看到区域对象了吗?你在那个物体上还能看到什么?

于 2012-05-24T04:27:40.530 回答