Ruby on rails 我的两个咖啡文件在Rails中相互干扰

Ruby on rails 我的两个咖啡文件在Rails中相互干扰,ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,ruby-on-rails-3.2,Ruby On Rails,Ruby On Rails 3,Ruby On Rails 4,Ruby On Rails 3.2,这里的问题是,在我的rails应用程序中,我编写了两个咖啡脚本文件,它们都需要window.onscroll fn 当我一次一个地实现它们时,两者都可以很好地工作,但是当我同时包含两者时, 脚本停止工作 这是第一个脚本 rightBarControl = -> windowHeight = $(window).height() scrollHeight = $(window).scrollTop() rightBarWidth = $('#index_top_confessio

这里的问题是,在我的rails应用程序中,我编写了两个咖啡脚本文件,它们都需要window.onscroll fn

当我一次一个地实现它们时,两者都可以很好地工作,但是当我同时包含两者时, 脚本停止工作

这是第一个脚本

rightBarControl = ->
  windowHeight = $(window).height()
  scrollHeight = $(window).scrollTop()
  rightBarWidth = $('#index_top_confession_div').width()
  #20% of .main width
  rightBarHeight = $('#index_top_confession_div').outerHeight()
  rightBarOffset = $('#index_confessions').offset().left + $('#index_confessions').outerWidth()
  rightBarTop = 75
  #30 because .head is 30px high
  if windowHeight - 75 < rightBarHeight
    #Again including 30 because of .head
    rightBarTop = windowHeight - rightBarHeight
  if windowHeight + scrollHeight - 75 >= rightBarHeight
    $('#index_top_confession_div').css
      position: 'fixed'
      left: rightBarOffset
      top: rightBarTop
  else
    $('#index_top_confession_div').css
      position: 'static'
      left: rightBarOffset
      top: rightBarTop
  return

$('#search').addClass 'form-control'
$(window).scroll rightBarControl
#Run control on window scroll
$(window).resize rightBarControl
rightBarControl=->
windowHeight=$(window).height()
scrollHeight=$(窗口).scrollTop()
rightBarWidth=$('#index_top_div')。宽度()
#主宽度的20%
rightBarHeight=$('#index_top_div')。outerHeight()
rightBarOffset=$(“#索引#告白”).offset().left+$(“#索引#告白”).outerWidth()
rightBarTop=75
#因为,头是30px高
如果windowHeight-75=rightBarHeight
$('#index_top_div').css
位置:'固定'
左:右偏移
上图:右上角
其他的
$('#index_top_div').css
位置:“静态”
左:右偏移
上图:右上角
返回
$(“#搜索”).addClass“表单控件”
$(窗口)。向右滚动条控件
#在窗口滚动上运行控件
$(窗口)。调整rightBarControl的大小
第二个脚本文件

 $(document).ready ->
  if $('.pagination').length
    $(window).scroll ->
      console.log('hey');
      url = undefined
      url = $('.pagination .next_page').attr('href')
      if url and $(window).scrollTop() > $(document).height() - $(window).height() - 200
        $('.pagination').html '<img src = \'/uploads/loader/loader.gif\' alt=\'loading...\'/>'
        return $.getScript(url)
      return
    return $(window).scroll()
  return
$(文档).ready->
如果$('.pagination').length
$(窗口)。滚动->
console.log('hey');
url=未定义
url=$('.pagination.next_page').attr('href'))
如果url和$(窗口).scrollTop()>$(文档).height()-$(窗口).height()-200
$('.pagination').html“”
返回$.getScript(url)
返回
return$(window.scroll())
返回

资产管道将所有CSS和Javascript文件合并到一个大文件中

当两个coffeescript文件中都有
$(window).scroll()
时,两个函数都将运行

解决这个问题的方法很少。一种是编辑
layout.html.erb
以将控制器名称作为主体
class
id
。然后您可以在您的coffeescript中检查它,以便在正确的页面上运行正确的js


另一种方法是确保始终以
id
为目标元素,而不是避免使用网站范围内的目标,如
body
window

嗯。。这两个点都在同一页上运行。。一个控制右栏,一个控制无限滚动