1
votes

I have ajax comments in posts index page. I decided to implement infinitescroll and it is working fine, but when I scroll down and more posts load(infinite scroll triggered) my ajax comments on that page don't work. I tried adding the comments js.coffee to posts.js.coffee but after infinite scroll is triggered, comments show up double. I guess I need to call my comments function back after infinitescroll but don't know where I'd implement it again.

comments.js.coffee

# comments.js.coffee
 jQuery ->
  # Create a comment
  $(".commentform")
    .on "ajax:beforeSend", (evt, xhr, settings) ->
      $(this).find('textarea')
        .addClass('uneditable-input')
        .attr('disabled', 'disabled');
    .on "ajax:success", (evt, data, status, xhr) ->
      $(this).find('textarea')
        .removeClass('uneditable-input')
        .removeAttr('disabled', 'disabled')
        .val('');
        $(xhr.responseText).hide().insertAfter($(this)).show('slow')




      $(document)
    .on "ajax:beforeSend", ".comment", ->
      $(this).fadeTo('fast', 0.5)
    .on "ajax:success", ".comment", ->
      $(this).hide('fast')
    .on "ajax:error", ".comment", ->
      $(this).fadeTo('fast', 1)

posts.js.coffee

  $(document).on 'ready, page:change', ->
  loading_posts = false
  $('a.load-more-posts').on 'inview', (e, visible) ->
    return if loading_posts or not visible
    loading_posts = true

    $.getScript $(this).attr('href'), ->
      loading_posts = false

      $("abbr.timeago").timeago();

index.js.haml

    $('#indexstream').append('#{escape_javascript(render partial: 'post', :locals => { :post => @posts }, :collection => @posts)}');
$('a.load-more-posts').attr('href', '#{posts_path page: @posts.next_page}');
- unless @posts.next_page
  $('a.load-more-posts').remove();

thanks for the help.

1

1 Answers

0
votes

I delegated the events and it worked perfectly.

updated code:

 # comments.js.coffee
jQuery ->
  # Create a comment
  $("body")
    .on "ajax:beforeSend", ".commentform", (evt, xhr, settings) ->
      $(this).find('textarea')
        .addClass('uneditable-input')
        .attr('disabled', 'disabled');
    .on "ajax:success", ".commentform", (evt, data, status, xhr) ->
      $(this).find('textarea')
        .removeClass('uneditable-input')
        .removeAttr('disabled', 'disabled')
        .val('');
      $(xhr.responseText).hide().insertAfter($(this)).show('slow')