thread_response_view.coffee 2.16 KB
Newer Older
1 2 3
class @ThreadResponseView extends Backbone.View
  tagName: "li"
  template: _.template($("#thread-response-template").html())
4 5
  events:
      "click .vote-btn": "toggleVote"
Matthew Mongeau committed
6 7
      "submit form": "submitComment"

8 9
  render: ->
    @$el.html(@template(@model.toJSON()))
10 11 12
    if window.user.voted(@model)
      @$(".vote-btn").addClass("is-cast")
    @$(".posted-details").timeago()
Matthew Mongeau committed
13
    @convertMath()
14 15 16
    @renderComments()
    @

Matthew Mongeau committed
17 18 19
  convertMath: ->
    element = @$(".response-body")
    element.html DiscussionUtil.postMathJaxProcessor DiscussionUtil.markdownWithHighlight element.html()
20
    MathJax.Hub.Queue ["Typeset", MathJax.Hub, element[0]]
Matthew Mongeau committed
21

22 23 24 25 26 27
  renderComments: ->
      @model.get("comments").each @renderComment

  renderComment: (comment) =>
    view = new ResponseCommentView(model: comment)
    view.render()
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
    @$(".comments li:last").before(view.el)

  toggleVote: ->
    @$(".vote-btn").toggleClass("is-cast")
    if @$(".vote-btn").hasClass("is-cast")
      @vote()
    else
      @unvote()
    false

  vote: ->
    url = @model.urlFor("upvote")
    @$(".votes-count-number").html(parseInt(@$(".votes-count-number").html()) + 1)
    DiscussionUtil.safeAjax
      $elem: @$(".discussion-vote")
      url: url
      type: "POST"
      success: (response, textStatus) =>
        if textStatus == 'success'
          @model.set(response)

  unvote: ->
    url = @model.urlFor("unvote")
    @$(".votes-count-number").html(parseInt(@$(".votes-count-number").html()) - 1)
    DiscussionUtil.safeAjax
      $elem: @$(".discussion-vote")
      url: url
      type: "POST"
      success: (response, textStatus) =>
        if textStatus == 'success'
          @model.set(response)
Matthew Mongeau committed
59

60
  submitComment: (event) ->
Matthew Mongeau committed
61 62
    url = @model.urlFor('reply')
    body = @$(".comment-form-input").val()
63 64
    if not body.trim().length
      return false
Matthew Mongeau committed
65 66 67
    comment = new Comment(body: body, created_at: (new Date()).toISOString(), username: window.user.get("username"))
    @renderComment(comment)
    @trigger "comment:add"
68
    @$(".comment-form-input").val("")
Matthew Mongeau committed
69 70 71 72 73 74 75 76

    DiscussionUtil.safeAjax
      $elem: $(event.target)
      url: url
      type: "POST"
      dataType: 'json'
      data:
        body: body
77
       
Matthew Mongeau committed
78
    false