Michael Moulsdale
Michael Moulsdale

Reputation: 1488

Rails CoffeeScript carry out a command on load

I have a CoffeeScript file as part of a Rails application that looks like the following

    jQuery ->
      $ ->
        $('#secondthing').hide()

      $('#trips').change ->
        trips = $('#trip_quantity :selected').text()
        if trips == '1'
          $('#secondthing').hide()
        else
          $('#secondthing').show()

Now the part of the code that executes when trips changes works fine. However, the first bit of code that is menat to execute once the page has loaded does not change. I'm not sure where to go from here

Upvotes: 1

Views: 162

Answers (2)

Raffaele
Raffaele

Reputation: 20885

There's no problem with your code, so if it doesn't work the reason must be in the part you didn't show. However I'm pointing out a couple of things that apparently confuse people here.

First, there's no need to use both jQuery and $ in the same scope. $ is just an alias for jQuery, and the only scenario where both names make sense is when for compatibility reasons (with other versions of jQuery or maybe other libraries which also use $ as a shortcut) you encapsulate your code in a module like this:

(function($) {
  // Now $ is bound to whatever object you pass in
})(jQuery);

Given that we can freely substitute $ for jQuery in your code, the next piece of misunderstanding is (compacted on a single line):

$ -> $ -> $("#foo").hide()

This snippet schedules a callback to be executed once the DOM is loaded. This callback in turn schedules another callback to hide #foo once the DOM is loaded. Since the second schedule is run when the DOM is already loaded, in practice it's executed immediately. That's why, even if you should really use

$ -> $("#foo").hide()

any extra "level" in the original code is no harmful, and in fact everything works as expected. BTW, this is the most compact version of your code:

$ ->
  el = $("#secondthing")

  el.hide()

  $("#trips").change ->
    el[if $('#trip_quantity :selected').text() == '1' then "hide" else "show"]();

Upvotes: 1

Benjamin Bouchet
Benjamin Bouchet

Reputation: 13181

Try removing the $ -> on your second line.

jQuery ->
  // $ ->
  $('#secondthing').hide()

  $('#trips').change ->
    trips = $('#trip_quantity :selected').text()
    if trips == '1'
      $('#secondthing').hide()
    else
      $('#secondthing').show()

Upvotes: 1

Related Questions