willcodejavaforfood
willcodejavaforfood

Reputation: 44063

In a Rails application, where should my Javascript be and how do I call it?

Just another Rails newbie with a problem. I have some Javascript (dynamic) in a partial .html.erb, but I have been informed in another post that this is really not where the Javascript should go. It's dynamic so I can find the correct ID of an element and only apply the javascript on that particular element. I assume it is possible to parameterise the javascript and put it in an external file and somehow call it from my partial. Would that be the correct way to do it? If so how would I do that? If not what should I do?

I have a nested resource. On the parent resource's show I am using AJAX to add children without leaving this page. I have quite a lot of Javascript magic that needs to be executed for each added child.

Partial _care_point.html.erb

<script>
  $(function() {
    $("#<%="node_#{care_point.id}" %>").live('dblclick', function(){
      console.log('moo');
      jQuery(this).hide();
      jQuery('.close', jQuery(this).parent()).show();
      jQuery('.node_input', jQuery(this).parent()).show();
    });
  });
</script>
<div id=<%="care_point.#{care_point.id}" %> class='draggable node_chin'>
  <div id=<%="node_#{care_point.id}" %> class='node'><%= care_point.body %>
  </div>
  <textarea class='node_input'><%= care_point.body %></textarea>
  <a class='close' href='#'>Close</a>
</div>

Thanks,

Erik

Upvotes: 2

Views: 128

Answers (2)

Evgeny Shadchnev
Evgeny Shadchnev

Reputation: 7388

In your partial:

<div id=<%="care_point.#{care_point.id}" %> class='draggable node_chin care_point'>
  <div id=<%="node_#{care_point.id}" %> class='node'><%= care_point.body %>
  </div>
  <textarea class='node_input'><%= care_point.body %></textarea>
  <a class='close' href='#'>Close</a>
</div>

In public/javascripts/application.js (where your js should be)

$(function() {
  $(".care_point").live('dblclick', function(){
    console.log('moo');
    jQuery(this).hide();
    jQuery('.close, .node_input', jQuery(this).parent()).show();
  });
});

Having used rails for a few years, I have never had to generate JS dynamically in the view. I can't think of a good use case that would require this (if you can think of one, leave a comment please).

Upvotes: 1

Vince
Vince

Reputation: 929

I've had similar cases where I need to reference the DOM element by ID (for example, a custom library that expects an ID as a parameter). What I normally do in these cases is generate inline javascript as Erik points out, or a more hybrid solution is adding a class, then cycle through all elements of that class, get their IDs, and bind them to the respective event (or do whatever you need with the ID).

I'd also like to see a best practice for this…

Upvotes: 0

Related Questions