Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3: How do I call a javascript function from a js.erb file
    text
    copied!<p>Now that I've upgraded to Rails 3, I'm trying to figure out the proper way to separate and reuse pieces of javascript. Here's the scenario I'm dealing with:</p> <hr> <p>I have a page with two areas: one with elements that should be draggable, the other with droppables.</p> <p>When the page loads I use jQuery to setup the draggables and droppables. Currently I have the script in the head portion of application.html.erb, which I'm sure is not the right solution but at least works.</p> <p>When I press a button on the page, an ajax call is made to my controller that replaces the draggables with a new set of elements that should also be draggable. I have a js.erb file that renders a partial in the correct location. After rendering I need to make the new elements draggable, so I'd like to reuse the code that currently lives in application.html.erb, but I haven't found the right way to do it. I can only make the new elements draggable by pasting the code directly into my js.erb file (yuck).</p> <p>What I'd like to have: - a javascript file that contains the functions prepdraggables() and prepdroppables() - a way to call either function from application.html.erb or from a js.erb file</p> <p>I've tried using :content_for to store and reuse the code, but can't seem to get it working correctly.</p> <hr> <p>What I currently have in the head section of application.html.erb </p> <pre><code>&lt;% content_for :drag_drop_prep do %&gt; &lt;script type="text/javascript" charset="utf-8"&gt; $(document).ready(function () { // declare all DOM elements with class draggable to be draggable $( ".draggable" ).draggable( { revert : 'invalid' }); // declare all DOM elements with class legal to be droppable $(".legal").droppable({ hoverClass : 'legal_hover', drop : function(event, ui) { var c = new Object(); c['die'] = ui.draggable.attr("id"); c['cell'] = $(this).attr("id"); c['authenticity_token'] = encodeURIComponent(window._token); $.ajax({ type: "POST", url: "/placeDie", data: c, timeout: 5000 }); }}); }); &lt;/script&gt; &lt;% end %&gt; </code></pre> <p>undo.js.erb</p> <pre><code>$("#board").html("&lt;%= escape_javascript(render :partial =&gt; 'shared/board', :locals =&gt; { :playable =&gt; true, :restartable =&gt; !session[:challenge]}) %&gt;") // This is where I want to prepare draggables. &lt;%= javascript_include_tag "customdragdrop.js" %&gt; // assuming this file had the draggables code from above in a prepdraggables() function prepdraggables(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload