根据单击的元素构造和渲染骨干视图

时间:2012-04-07 23:44:46

标签: backbone.js coffeescript

嗨,我遇到了主干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

评论框视图

 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>

当点击评论链接时,我在commentMainBox中构造html和dump。 但问题是点击的元素始终是我页面上带有类注释的第一个元素。如何获取当前单击的元素,以便在正确的div中呈现内容。

CommentBoxView的元素也应该是el: $('.commentBoxMain')但是如果我分配了这个,那么我在视图中没有得到任何渲染,但是当我初始化为el: $('.comment')时,我看到了注释框但是它总是在无论点击哪一条,第一条评论。

我哪里错了?

1 个答案:

答案 0 :(得分:1)

您不应该将@elCommentView传递到它实例化的CommentBoxView;也没有在el: $('.commentBoxMain')课程中宣布CommentBoxView开始工作。正如Backbone.js文档所说:

  

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

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

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

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

相关问题