views:

67

answers:

3

Hi guys,

I've got a problem with linking unobtrusive js file with view.

I've got view named index.html.erb

...
<div id="fooBar">say bye!</div>
...

Also I've got js file index.js.erb

$("#fooBar").html("say hello!")

Currently I get say bye message, because javascript file are not executed.

What I'm doing wrong?

It seems to me that js.erb is not used for that purpose. And i just need to add script reference on normal .js file where view specific client logic is held

Thanks, Alexey

A: 

Are you doing it after the element or the document loads?

Try

$(function() {
    $("#fooBar").html("say hello!")
});

assuming you are using jQuery which appears to be the case.

Anurag
I assume that Rails will auto link index.js.erb file to index.html.erb view. But it doesn't do it. Or may be I should manually add script reference to my view. According to samples that I have seen, it is not necessary to manually to add javascript reference in view.
Alexey Zakharov
A: 

Do you have

<%= javascript_include_tag :defaults %>
<%= csrf_meta_tag %>

in your views/layouts/application.html? I had JS problems because I forgot the latter one (Rails 3 only).

amay82
Yes I have included them.
Alexey Zakharov
+2  A: 

Did you specify a render_with :js in your controller?

Unfortunately, the way you have it scripted there won't really work. You can only render one thing html or js. With Rails UJS when you click show (for example) it decides based on if you have JS to render dynamically or to render it with HTML. You can't render two things at once.

Try this: http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/

Maletor
Also take a look inside of rails.js. It's not that big and it will give you a good understanding of what's really going on.
Maletor