Rails 3:将字符串从 Ruby 传递到 Javascript?
Jist:
在 中,我想访问从 Ruby 到 Javascript 的静态(Rails 将页面传递到客户端后不会更改)字符串。
更多细节(又名:为什么我想这样做。)
我使用名为 Juggernaut 的推送服务器,它必须连接到适当的“通道”,由控制器中的变量确定。 “监听”Juggernaut 服务器的 Juggernaut 语法是:
j.subscribe("channel", function(data) { })
我希望它是:
j.subscribe(<%= @myChannel %>, function(data) { })
The Jist:
In a <script type="text/javascript">
I want to access a static (won't ever change after Rails delivers page to client) string from Ruby to Javascript.
More Detail (AKA: Why I want to do it.)
I use a push server called Juggernaut and it has to connect to the appropriate "channel", determined by a variable in the controller. The Juggernaut syntax for "listening" to the Juggernaut server is:
j.subscribe("channel", function(data) { })
I want it to be:
j.subscribe(<%= @myChannel %>, function(data) { })
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
@myChannel
很可能不包含 "。您应该使用:
Most likely your
@myChannel
doesn't contain ".You should use:
一个不同的想法是不将 ruby 代码嵌入到 .js 文件中,而是嵌入到视图本身中。
因此,在您看来,要么设置一个 javascript 变量
channel
,要么添加“channel”作为某些 html 元素的属性,以适合您的情况为准。然后,一旦文档准备好,您就可以在应用程序 JavaScript 中访问该变量。这样做的好处是,如果/当频道更改时,客户端不需要重新下载 JavaScript,而是可以继续从缓存中使用它,并且 Rails 不需要每次都渲染 .js。
A different idea is to not embed your ruby code in your .js files but rather in the view itself.
So in your view, either set a javascript variable
channel
or add "channel" as an attribute of some html element, whichever is more natural for your case. Then in your application javascript you can access that variable once the document is ready.This has the side benefit that if / when channel changes the client doesn't need to re-download your javascript but can instead keep using it from cache, and that rails doesn't need to render the .js every time.