【问题标题】:Construct and render backbone view with respect to elements clicked针对单击的元素构建和渲染主干视图
【发布时间】:2012-04-07 23:44:46
【问题描述】:

您好,我遇到了骨干 js 的问题

我有一个评论视图

class window.CommentView extends Backbone.View
  el: $('.comment')
  initialize: ->
    @$el.show()
  events:
    "click": "renderCommentBoxView"

  renderCommentBoxView: ->
    @commentBoxView = new CommentBoxView
      id: this.$('.comment')['context']['activeElement']['id']
      model: new Item
      el: @el

还有一个 cmets 框视图

 class window.CommentBoxView extends Backbone.View
   el: $('.commentBoxMain')

   events:
     "click.comment": "showCommentBox"
     "click document": "stopEvent"
     "click .login_button": "submitComment"
   initialize: ->
     @showCommentBox()

   stopEvent: (event) ->
     event.stopPropagation()

  showCommentBox: ->
     $(@el).append('<textarea class=\'commentBox\'></textarea><br/><input type=\'button\' class=\'login_button\' name=\'Add a comment\' value=\'Add a comment\'><span class=\'loading\' style=\'display: none;\'>Loading...</span>')

现在,用户可以评论多个项目。因此,每当单击评论按钮时,我都会呈现一个名为 CommentBoxView 的新视图,用于定义元素和模型

问题是我无法获取视图应该绑定到的当前单击元素。

我的 HTML 示例如下所示:

   <div id="item_1">
     <a class="comment" href='javascript:void(0)'>Comment</a>
     <div class="commentMainBox"></div>
   </div>
  <div id="item_2">
    <a class="comment" href='javascript:void(0)'>Comment</a>
    <div class="commentMainBox"></div>
  </div>

每当点击评论链接时,我都会构建 html 并将其转储到 commentMainBox 中。 但问题是单击的元素始终是我页面上带有类注释的第一个元素。如何获取当前点击的元素,以便在正确的 div 中呈现内容。

CommentBoxView 的元素也应该是el: $('.commentBoxMain'),但是如果我分配它,那么我在视图中什么都没有呈现,但是当我初始化为el: $('.comment') 时,我看到了评论框,但它总是在第一个评论下呈现无论点击的是哪一个。

我哪里错了?

【问题讨论】:

    标签: backbone.js coffeescript


    【解决方案1】:

    您不应该将@elCommentView 传递给它实例化的CommentBoxView;在CommentBoxView 类中声明el: $('.commentBoxMain') 也不起作用。正如 Backbone.js 文档所说:

    如果您想创建一个引用 DOM 中已有元素的视图,请将元素作为选项传入:new View({el: existingElement})

    否则,View 会尝试创建一个新元素。所以你要做的是:

    @commentBoxView = new CommentBoxView
      model: new Item
      el: @$('.commentMainBox')
    

    这将在 Comment 视图中找到 commentMainBox 元素(因为 @$ 的范围在其元素内)并将其作为 CommentBoxView 的元素提供。

    【讨论】:

    • 感谢您的解决方案,但它不起作用。此外,commentMainBox 也不在 commentView 中。我首先想到在单击链接的评论时动态创建 commentMainBox 视图,但后来我想如果我在评论链接下方定义 commentBox 视图会很好。我在项目的其他部分做过类似的事情,它们确实有效,但这里的情况有点不同。这里我需要在多个地方多次渲染同一个视图。我在这里面临的最大问题是我没有得到当前点击的元素。
    • 另外,至少当我点击评论链接时,它应该给我当前元素,而不是给我第一个元素 class= 'comment'。任何帮助将不胜感激:)
    • 定义 el: $('.commentBoxMain') 来引用 DOM 中的现有元素对我来说很好。虽然在那种情况下我会使用 ID 而不是类,因为您的元素是(并且应该是)唯一的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多