Dynamically created Javascript inside HAML

Why is this not working?

:javascript -[1,2,3].each do |number| $("#form_#{number}").my_method(); 

Rails gives me an error saying that the variable number not defined.

+4
source share
2 answers

The contents of the filter are not interpreted as Haml. You can use #{...} for interpolation, though, and that’s why you see an error - the filter sees #{number} in "#form_#{number}" , but the line above where number defined is simply passed as is, rather than being treated as Ruby, since Ruby is concerned about number still undefined.

In this case, you can do something like:

 :javascript #{[1,2,3].map do |number| "$(\"#form_#{number}\").my_method();" end.join("\n")} 

although it's a little cumbersome.

A clearer solution could be to create a helper method for creating javascript, which you could call from a filter:

 def create_js(arr) arr.map do |number| "$(\"#form_#{number}\").my_method();" end.join("\n") end 

and Haml will be

 :javascript #{create_js([1,2,3])} 
+4
source

You have ruby ​​syntax in your javascript and this obviously won't work. You can use a library like underscore.js and iterate over the array as follows:

 _.each([1, 2, 3], function(number){ $("#form_" + number).my_method(); }); 

Try it.

Or you can use jQuery each:

 $.each([1, 2, 3], function(i, number){ $("#form_" + number).my_method(); }); 
0
source

All Articles