简体   繁体   中英

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.

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:

I have my controller specific .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

@addFoo <%= raw @foo_id %>

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

but the reverse doesn't work in 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

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.

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?

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. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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