大佬教程收集整理的这篇文章主要介绍了javascript – Rails 3.1 – JS – * .js.erb中的Socket.io-emit未执行并阻止执行jQuery-Function,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我的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中正确加载:
<%= javascript_include_tag "application","http://localhost:8080/socket.io/socket.io.js" %>
现在我想使用套接字在create.js.erb中发送@L_944_3@发送给所有侦听客户端的事件:
$(function() { window.socket.emit('message',<%= @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
我通过这种方式在另@L_944_3@名为index.js.erb的视图中监听此事件:
$(function() { window.socket.on('message',function (msg) { $("#articles").prepend(<%= escape_javascript render(Article.new.from_json(msg.data)) %>); }); });
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做了@L_944_3@解决方法:
$.getScript('http://localhost:8080/socket.io/socket.io.js',function(){ window.socket = io.connect('http://localhost:8080/'); });
现在的问题是:为什么我必须以这种方式获取脚本,尽管它在application.html.erb中是loadet?但是尽管有这种解决方法,create.js.erb仍然无法正常工作.我会尝试解决一下睡眠后的问题.
以上是大佬教程为你收集整理的javascript – Rails 3.1 – JS – * .js.erb中的Socket.io-emit未执行并阻止执行jQuery-Function全部内容,希望文章能够帮你解决javascript – Rails 3.1 – JS – * .js.erb中的Socket.io-emit未执行并阻止执行jQuery-Function所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。