How do you create javascript functions that are available project-wide in Ruby on Rails?

前端 未结 7 1532
攒了一身酷
攒了一身酷 2020-12-25 14:05

I put the following function in my application.js:

function test() {
  alert(\"See Me\")
}

classrooms/_new_small.html.haml:



        
7条回答
  •  被撕碎了的回忆
    2020-12-25 14:42

    I tried this without an issue. Here's how I did it.

    // application.js

    var test=function(){
      alert("hello");
    }
    

    // in a view, whichever one, i have a content_for :additional_javascripts

    <% content_for :additional_javascripts do %>
      <%= javascript_tag do %>
        test();
      <% end %>
    <% end %>
    

    // in application layout

    <%= javascript_include_tag "application" %>
    <%= yeild(:additional_javascripts) %>
    

    Furthermore, if I want to alert this dynamically later on I could append it to the page and call it then, or put it in a click listener or something.

    I like the syntax var functionName = function(){...} because it properly scopes the method. Also, because of the way javascripts are compiled through the asset pipeline, adding the ; at the end of every executed line is very important.

    This also worked for me as far as loading the script dynamically and calling it from anywhere in the page:

    $("#click_me").live("click", function(){
      $("
    
                                     
                  
提交回复
热议问题