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

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

    Assuming you are using asset pipeline & coffeescript: Don't write code in application.js

    In order to keep clean structure, create a folder (eg: application) in app/assets/javascripts

    then require it in your application.js

    //= require jquery
    //= require jquery_ujs
    
    //= require_tree ./application
    

    Create a coffee file (eg: app/assets/javascripts/application/my_feature.js.coffee

    @test = ->
      alert('Hello world')
    

    Coffee output:

    (function() {
    
      this.test = function() {
        return alert('Hello world');
      };
    
    }).call(this);
    

    It's preferable to use namespaces:

    @myGreatFeature =
      test: ->
        alert('Hello world')
    

    or according to the coffeescript FAQ, you could write

    namespace = (target, name, block) ->
      [target, name, block] = [(if typeof exports isnt 'undefined' then exports else window), arguments...] if arguments.length < 3
      top    = target
      target = target[item] or= {} for item in name.split '.'
      block target, top
    
    namespace 'myGreatFeature', (exports) ->
      exports.test = ->
        alert('Hello world')
    

    then you can call myGreatFeature.test() everywhere

提交回复
热议问题