Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 664
kbjerring Avatar asked Oct 15 '22 02:10

kbjerring


1 Answers

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")}')"
like image 81
D.Shawley Avatar answered Oct 18 '22 11:10

D.Shawley