I put the following function in my application.js:
function test() {
alert(\"See Me\")
}
classrooms/_new_small.html.haml:
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