简体   繁体   English

Rails 4从.js.coffee视图调用CoffeeScript函数

[英]Rails 4 calling a CoffeeScript function from a .js.coffee view

I have a bit of a problem, I'm a real noob with JS and CS but seem to be slowly getting there. 我有一个问题,我是使用JS和CS的真正菜鸟,但似乎正在慢慢到达那里。

I have an app that has to maintain some pretty complex JS objects and I do this by using CS classes etc. The thing that has me scratching my head is the following: 我有一个必须维护一些非常复杂的JS对象的应用程序,并且通过使用CS类等来做到这一点。

I have my controller specific .js.coffee 我有控制器专用的.js.coffee

foos.js.coffee foos.js.coffee

@addFoo(foo_id) ->
    #logic to instantiate foos
    #and add maintain data structures

@removeFoo(foo_id) ->
    #logic to remove foos
    #and maintain datastructures

this works in my create view 这在我的创建视图中有效

foos/create.js.coffee FOOS / create.js.coffee

@addFoo <%= raw @foo_id %>

$("#sidebar").html ""
$("<%= escape_javascript(render 'shared/sidebar') %>").appendTo "#sidebar"

but the reverse doesn't work in destroy.js.coffee 但是相反的情况在destroy.js.coffee中不起作用

foos/destroy.js.coffee FOOS / destroy.js.coffee

@removeFoo <%= raw @foo_id %>

$("#sidebar").html ""
$("<%= escape_javascript(render 'shared/sidebar') %>").appendTo "#sidebar"

Could somebody please explain why this is? 有人可以解释为什么吗?

Edit 1 编辑1

Strangely, this suddenly began to work. 奇怪的是,这突然开始起作用。 I tried restarting my server, clearing my cache multiple times and even tried a complete system shutdown. 我尝试重新启动服务器,多次清除缓存,甚至尝试完全关闭系统。 Then, miraculously, after around 4 or 5 more failed attempts it began to work. 然后,奇迹般地,经过大约4或5次失败的尝试,它开始起作用。

Has anybody had a similar issue with rails/CoffeeScript and is there any measures I can take to avoid this sort of thing happening in the future? 是否有人在rails / CoffeeScript中遇到过类似的问题,并且我有什么措施可以避免将来发生这种情况?

This is just a shot in the dark.. but is something you can consider for the future 这只是黑暗中的一枪..但这是您可以考虑的未来

Your situation reminded me of something that threw me off so good, I thought it would be well worth mentioning. 您的情况使我想起了让我失望的事情,我认为这很值得一提。 I switched to Sublime Text and if you (accidentally) hit cmd+B, your CoffeeScript will compile to a Javascript file and both files will exist in your rails directory. 我切换到Sublime Text,如果您(不小心)按了cmd + B,则CoffeeScript将编译为Javascript文件,并且这两个文件都将存在于rails目录中。 Then proceeding on, code you thought you removed is invoked, or handlers are called more than once. 然后继续进行操作,以为您认为已删除的代码被调用,或者多次调用处理程序。 All types of strange behavior. 所有类型的奇怪行为。

I hope it saves you some frustration! 我希望它可以使您免于沮丧!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM