Okay, consider the following:
A app/views/pages/index.html.erb
, consisting of:
<div id='content'>
<%= link_to 'Test', get_page_path('test'), :remote => true %>
</div>
A definition in app/controllers/pages_controller.rb
like this:
def get
@page = Page.new(:title => '404', :content => '<strong>Page not found</strong>') unless @page = Page.find_by_title(params[:title])
respond_to do |format|
format.html
format.js
end
end
A javascript asset in app/assets/javascripts/pages.js.coffee
like this:
bork = (swedish) -> alert swedish
$ ->
bork 'bork bork'
And finally a app/views/pages/get.js.coffee
like this:
bork 'Smoerrebroed'
$('#content').html '<%= escape_javascript(@page.content).html_safe %>'
So, here's the fun part - I do see the 'bork bork' alert once as expected. However, after clicking on the link, only the content gets replaced (as indicated by the second line), I don't see a 'Smoerrebroed' alert.
The pages.js.coffee
stuff is obviously included - but seems to be inaccessible outside the page itself. As such, the compartmentalization Rails is doing is not very useful - why exactly should I put my 'pages controller' specific stuff into pages.js.coffee
when it is only accessible inside that specific script? Is there any way to work around that?
It seems to based on the fact that coffee script wraps everything inside a
(function() {
//specific stuff here
}).call(this);
which supposedly is there to prevent the script from executing before the page has loaded. Is there some way of telling coffeescript to stop doing that because I'm using the $ ->
(shorthand) or $(document).ready()
function anyway...