A
A
A_Modestov2016-05-24 12:02:14
JavaScript
A_Modestov, 2016-05-24 12:02:14

How to make ajax execute once?

Good afternoon, ladies and gentlemen. The following incident has overtaken:
The controller method works through ajax:

def create
    @comment = @commentable.comments.new(comment_params)
    @comment.user = current_user

    respond_to do |format|
      if @comment.save
        format.js do
          PrivatePub.publish_to "/comments", comment: @comment.to_json,
                                             comment_author: @comment.user.email.to_json
          render nothing: true
        end
      else
        format.json { render json: { errors: @comment.errors.full_messages } }
      end
    end
  end


Response handling js file:

ready = ->
  PrivatePub.subscribe '/comments', (data, channel) ->
    comment_author = $.parseJSON(data['comment_author'])
    comment_body = $.parseJSON(data['comment']).body
    commentable_id = $.parseJSON(data['comment']).commentable_id
    commentable_type = $.parseJSON(data['comment']).commentable_type

    $( '.' + commentable_type + '-comments#' + commentable_id).append(JST["templates/comment"]({comment_author: comment_author, comment: comment_body}))
    $('textarea#comment_body').val('')

$(document).ready(ready)
$(document).on('page:load', ready)
$(document).on('page:update', ready)


When you first go to the desired page and call the method, js is executed several times, that is, several comments are added (one is added to the database, as expected). If you reload the page and execute the method, everything works as intended. What could be the problem and how to win? Thanks in advance for your attention)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
A_Modestov, 2016-05-24
@A_Modestov

The problem was turbolinks, be it wrong. Deleted - everything worked as expected. Maybe someone knows how to make friends with turbolinks scripts?

V
vsuhachev, 2016-05-25
@vsuhachev

Names of events changed in turbolinks after some version

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question