Rails 3.1 – JS – * .js.erb中的Socket.io-emit未执行并阻止执行jQuery-Function

我想在我的Rails-Project中使用node.js来提供异步io。 我不想使用juggernaut,faye或类似的东西,因为我需要与web-socket,服务器发送的事件和spdy的干净连接而没有其他选择。 我第一次尝试使用node.js现在使用Socket.io,只是为了使用JavaScript将数据提供给node.js-module。 但它根本不起作用。

我的application.js看起来像这样:

// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require_tree . window.socket = io.connect('http://localhost:8080/'); 

io的要求在我的application.html.erb中正确加载:

   

现在我想使用套接字在create.js.erb中发出一个发送给所有侦听客户端的事件:

 $(function() { window.socket.emit('message', ); }; $("#new_article")[0].reset(); 

消息以这种方式在ArticlesCrontroller中创建:

 def create @article = current_user.articles.build(params[:article]) if @article.save msg = {:data => @article.to_json} @message = msg.to_json end end 

我通过这种方式在另一个名为index.js.erb的视图中监听此事件:

 $(function() { window.socket.on('message', function (msg) { $("#articles").prepend(); }); }); 

Socket.io看起来像这样:

 var io = require('socket.io').listen(8080); io.sockets.on('connection', function (socket) { socket.on('message', function () { }); socket.on('disconnect', function () { }); }); 

并且似乎工作正常,因为它告诉我它如何服务于请求的js-File:

 info - socket.io started debug - served static /socket.io.js 

但它根本不起作用,尽管create.js.erb在没有错误的情况下呈现:

 Rendered articles/create.js.erb (0.5ms) Completed 200 OK in 268ms (Views: 70.0ms | ActiveRecord: 14.6ms) 

甚至用于重置表单的jQuery-Function也没有被执行,没有尝试发出socket事件的情况下也能正常工作。 文章正确保存到数据库,所以这不是问题。 有人能告诉我问题可能在哪里吗?

更新:通过使用chrome的JavaScript调试器,我发现问题始于application.js中window.socket的定义。 错误代码是:

 Uncaught ReferenceError: io is not defined (anonymous function) 

io是在我的application.html.erb中加载的socket.io.js文件中定义的。 我用这种方式为application.js做了一个解决方法:

 $.getScript('http://localhost:8080/socket.io/socket.io.js', function(){ window.socket = io.connect('http://localhost:8080/'); }); 

现在的问题是:为什么我必须以这种方式获取脚本,尽管它在application.html.erb中是loadet? 但是尽管有这种解决方法,create.js.erb仍然无法正常工作。 我会尝试解决一下睡眠后的问题。

我通常在相关清单中包含依赖项(在本例中为application.js )。

Rails可以识别许多不同的资产路径,所有资源路径都在编译之前进行检查。 我倾向于将(例如socket.io.js )放在vendor/assets/javascripts并在清单中添加一行,如下所示:

 //= require jquery //= require jquery_ujs //= require socket.io //= require_tree .