rails 4无限滚动中断javascript ajax



我在帖子索引页面中有ajax注释。我决定实现无限滚动,它运行得很好,但当我向下滚动并加载更多帖子时(无限滚动触发),我在该页面上的ajax评论就不起作用了。我试着将评论js.coffee添加到posts.js.coffe中,但在触发无限滚动后,评论会加倍显示。我想我需要在infinitescroll之后调用comments函数,但不知道在哪里可以再次实现它。

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)

post.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();

谢谢你的帮助。

我委托了这些事件,它运行得很好。

更新代码:

 # 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')

最新更新