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

前端 未结 7 1568
攒了一身酷
攒了一身酷 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:37

    I noticed your function test() is indented, which suggests it is nested. If you define a function in the scope of another function, it will not be available outside of it.

    For example this should work, using jQuery:

    function test() { /* do something */ }
    
    // another file or inline script
    
    $(function() {
       test();
    });
    

    But this won't

    (function() {
       function test() {}
    })();
    
    // another file
    
    test(); // undefined
    

提交回复
热议问题