Why doesn't this work?
:javascript
-[1,2,3].each do |number|
$("#form_#{number}").my_method();
Rails gives me an error, saying that the variable number isn't defined.
The content of a filter isn’t interpreted as Haml. You can use #{...} for interpolation though, and that’s why you’re seeing the error – the filter sees the #{number} in "#form_#{number}", but the line above where number is defined is simply passed through as it is, not treated as Ruby, so as far as Ruby is concerned number is still undefined.
In this case you could do something like:
:javascript
#{[1,2,3].map do |number|
"$(\"#form_#{number}\").my_method();"
end.join("\n")}
although that’s a bit unwieldy.
A clearer solution might be to create a helper method to create the javascript, which you could call from the filter:
def create_js(arr)
arr.map do |number|
"$(\"#form_#{number}\").my_method();"
end.join("\n")
end
and the Haml would be
:javascript
#{create_js([1,2,3])}
.join("\n") trick to work on ruby 1.9.3 (the function above just returns the contents of arr)each to map as well as add the join; did you change that too? Otherwise, what do you see? (I’m using 1.9.3 and it works for me).each to map, thanks for pointing that out.You have ruby syntax within your javascript and that obviously will not work. You can use a library like underscore.js and iterate over your array like this:
_.each([1, 2, 3], function(number){
$("#form_" + number).my_method();
});
Try that.
Or you can use jQuery's each:
$.each([1, 2, 3], function(i, number){
$("#form_" + number).my_method();
});
$() indicates jQuery, $.each([1,2,3],function(i, number) {...