Chris Mendla
Chris Mendla

Reputation: 1017

Javascript / Jquery selector ($) in a rails def

I have the following code in an html.erb file. It works fine for that page. I want to move it into a def in the application controller. When I try to do that, the $ shows as an unexpected bad character.

Is there a way to move this code to a def?

<!-- --------------   Begin Dirty Form Checker   -->

<%= javascript_include_tag "jquery.are-you-sure.js" %>
<%= content_for(:body_attributes) do %> data-no-turbolink <% end %>

<script>
    var do_on_load = function() {
        $('form').areYouSure( {'silent':false} );
        $('form').areYouSure();
    }
    $(document).ready(do_on_load)
    $(window).bind('page:change', do_on_load)
</script>

Upvotes: 1

Views: 253

Answers (1)

max
max

Reputation: 102368

That's just wrong. You don't place javascript in your ApplicationController. Javascript in Rails is a view concern and best practice is to avoid as far as possible ever mixing Ruby (or any other server side language) and Javascript*.

You place your javascript in external files (app/assets/javascripts/*.js). Instead of thinking of your scripts on a per page basis think of javascript as an extendable set of behaviors that you can add to elements in your app.

Use classes or data-* attributes to target elements, and data attributes and JSON to pass data between client side and server side.

// app/assets/javascripts/supa_form.js
$(document).on('page:change', function(){
  $('.supa-form').submit(function(){
    if (!window.confirm('Are you sure?')) {
      return false;
    }
  });
});

Why?

  • Allows javascripts to be compiled and minimized at deploy time.
  • Allows javascripts to be effectively cached.
  • Allows javascripts to be tested independently of the rails application.
  • Newbies who mix javascript and server side rendering get confused about what happens when and where.
  • Avoids mixing data and logic.

Additional reading:

Upvotes: 2

Related Questions