$(函数)在Rails 3.2.1 App中被调用两次

时间:2012-02-23 00:15:00

标签: jquery ruby-on-rails

我有一个Rails 3.2.1应用程序,我试图包含一些jquery。

以下是文件:

states.js:

var grid;

var columns = [
 {id: "firstName", name: "FirstName", field: "FirstName"},
 {id: "lastName", name: "LastName", field: "LastName"}
]



var options = {
 enableCellNavigation: true,
 enableColumnReorder: false
};

$(function () {
 alert("hi");
 var state = $("#myGrid").data("state");
 $.getJSON(state, function(data){
    grid = new Slick.Grid("#myGrid", data, columns, options);
});
})

states_controller.rb:

class StatesController < ApplicationController
def index
  @states = SiteIndexPlayer.select("DISTINCT HometownState")
end

def name
  logger.debug(":name #{params[:name]}")
  @athletes = SiteIndexPlayer.select('FirstName, LastName').find_all_by_HometownState(params[:name])
  @state=params[:name]
  respond_to do |format|
    format.html
    format.json { render json: @athletes }
  end
end
end

我在每次加载页面时都会收到两次“hi”弹出窗口。

出于某种原因是否有2个请求出现?

由于

问题

结果是states.js被加载到DOM两次。我不是在预编译资产。还有其他任何想法为什么文件被加载两次?

解决方案

ls app/assets/javascripts
application.js  lib     slick.core.js   slick.grid.js states.js.coffee  states.js 

我猜测states.js.coffee正在加载文件以及application.js。我一删除states.js.coffee,它就运行良好。

知道我可以在*.coffee上阅读的内容吗?

修改

的application.js:

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require_tree .

application.html.erb

<!DOCTYPE html>
<html>
<head>
  <title>CapApp</title>
  <%= stylesheet_link_tag    "application", :media => "all" %>
  <%= javascript_include_tag "application" %>
  <%= csrf_meta_tags %>
</head>
<body>

<%= yield %>

</body>
</html>

3 个答案:

答案 0 :(得分:2)

我猜是states.js.coffee正在加载文件以及application.js。一旦我删除了states.js.coffee,它就运行良好。

答案 1 :(得分:1)

我在我的environments/staging.rb文件中找到了与Rails 3.2.x相同的症状我做了设置

# Expands the lines which load the assets
config.assets.debug = true

但是Capistrano被配置为预编译资产,因此我在application.js中有一个副本,在控制器特定的.coffee文件中有另一个副本。将值设置为false可以解决我的问题。

答案 2 :(得分:0)

您是否“耙资产:procompile”?如果是y,请尝试“assets:clean”并运行服务器