且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Ruby on Rails 中创建项目范围内可用的 javascript 函数?

更新时间:2021-08-19 06:23:05

假设您正在使用资产管道 &coffeescript: 不要在 application.js 中编写代码

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

为了保持结构清晰,在app/assets/javascripts

然后在你的 application.js 中要求它

then require it in your application.js

//= require jquery
//= require jquery_ujs

//= require_tree ./application

创建一个咖啡文件(例如:app/assets/javascripts/application/my_feature.js.coffee

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

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

咖啡输出:

(function() {

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

}).call(this);

***使用命名空间:

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

或者根据coffeescript FAQ,你可以写

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')

然后你可以在任何地方调用myGreatFeature.test()

then you can call myGreatFeature.test() everywhere