kbjerring
kbjerring

Reputation: 623

Calling javascript functions from view in Rails 3

I am new to Rails and I have a pretty simple problem with calling javascript functions from within a view. In Rails 2 I would do...

= javascript_tag "name(arguments)"

where the javascript function "name" was located in my application.js file. However, this does not appear to work in Rails 3? Or am I missing something? I have been searching Google for some time without finding an answer.

UPDATE:

OK, so I looked at the source of the two different ways (using the javascript_tag and the haml javascript filter) as suggested. And this is very strange because the html source appears to be identical? Apart from a difference in double and single quotes in declaring the script type.

FIRST: using the javascript_tag which does not work

= javascript_tag "number_interval(#{fact.current_value}, #{fact.growth_per_second}, #{fact.decimal_number}, '#{dom_id(fact, "number")}'"

Source...

<div id='number_number_interval_727'>loading</div>
<script type="text/javascript">
//<![CDATA[
number_interval(6952596670.36814, 2.33002440293917, 0, 'number_number_interval_727'
//]]>
</script>

SECOND: using the haml javascript filter and it works

:javascript
  number_interval(#{fact.current_value}, #{fact.growth_per_second}, #{fact.decimal_number}, '#{dom_id(fact, "number")}')

Source...

<div id='number_number_interval_727'>loading</div>
<script type='text/javascript'>
//<![CDATA[
number_interval(6952596917.02179, 2.33002440293917, 0, 'number_number_interval_727')
//]]>
</script>

Well, I guess I'll just stick with the haml filter!

Upvotes: 5

Views: 10393

Answers (4)

D.Shawley
D.Shawley

Reputation: 59633

You have a syntax error:

= javascript_tag "number_interval(#{fact.current_value}, #{fact.growth_per_second}, #{fact.decimal_number}, '#{dom_id(fact, "number")}'"

is missing the closing parenthesis for the number_interval function. I think that it should be:

= javascript_tag "number_interval(#{fact.current_value}, #{fact.growth_per_second}, #{fact.decimal_number}, '#{dom_id(fact, "number")}')"

Upvotes: 2

Taryn East
Taryn East

Reputation: 27757

Silly question but... is application.js included in your layout?

One option to try is to hand-code the js function-call into your view in "real" javascript - just to see if it works. eg

<script type="text/javascript">
  name(arguments)
</script>

Then you can be sure it's not the js itself (or lack thereof) at fault.

Upvotes: 0

kbjerring
kbjerring

Reputation: 623

A friend of mine pointed me to the fact that there is a javascript helper in haml. Apparently, I can call javascript functions by using...

:javascript
  name_of_function(arguments)

This works, but of course only with haml.

Upvotes: 2

Hitesh Manchanda
Hitesh Manchanda

Reputation: 490

Check out the right syntax on link text

and Check if you have included the javascript defaults in your file.As this working for me in RAILS 3 also

Upvotes: 0

Related Questions