0

I have the following piece of code:

    $(document).ready(function() {
    // Cycles the carousel to a particular frame
      <%  (0..6).each_with_index do |i, index| %>
        $(".slide<%= i%>").click(function(){
          $("#myCarousel").carousel(<%= i%>);
        });
      <% end %>
    });

I need to convert it to coffee script and move it out the external file.

1) Is it possible to call pass the variables from here to the external file? 2) How to go about it?


Updated Code to show why I need to pass variables.

$(document).ready(function() {
  // Cycles the carousel to a particular frame
  <%  @images.each_with_index do |i, index| %>
    $(".slide<%= index%>").click(function(){
      $("#myCarousel").carousel(<%= index%>);
    });
  <% end %>
});
2
  • Why do you want to pass any variables? You don't need any of the Ruby/ERB here at all. Sep 27, 2014 at 17:16
  • have updated the code. Sep 28, 2014 at 9:47

2 Answers 2

0

As mentioned by mu is too short you do not actually need to pass any variables you can directly convert that into Coffeescript like so:

$(document).ready ->
    for i in [0..6]
        $(".slide#{i}").click ->
            $("#myCarousel").carousel i
1
  • 1
    You probably want to use a do loop to make sure that i is what you expect it to be inside the click handlers. Sep 28, 2014 at 2:34
0

It seems to me that Kyle Needham's answer is (mostly) correct. You could just do this in an external file:

root = exports ? this

root.foo = {} #namespace

root.foo.createNCarousels = (n) ->
  for i in [0..(n - 1)]
    do (i) -> #If this is confusing, see http://rzrsharp.net/2011/06/27/what-does-coffeescripts-do-do.html
      $(".slide#{i}").click ->
        $("#myCarousel").carousel i

Now in your original file include the external script tag and you should be able to call it like this:

$(document).ready(function() {
  // Cycles the carousel to a particular frame
  document.foo.createNCarousels(<%=  @images.length %>);
});

Keep in mind I don't know Ruby so the Ruby syntax may be wrong, but I hope my intent is clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.