Ruby on Rails 4 - coffee scriptで作った関数をhtml(view)側で呼び出す


foo.js.coffee
foo = () ->
  alert('foo')

と書いてしまうと

foo.js
(function() {
  foo = function() {
    alert('foo');
  };
}).call(this);

のようにラップされてしまうので、hamlやerb側で普通のjavascriptとして実行したいときに、見つからないと言われる。

foo.js.coffee
@foo = () ->
  alert('foo')

関数名を@fooとすることで、

foo.js
(function() {
  this.foo = function() {
    alert('foo');
  };
}).call(this);

のような変換になる。

このthisはwindowなので、これで普通のjavascriptの関数呼び出しで実行できる

foo.html.haml
%script
  $(document).ready(foo());

や、単純に

foo.html.haml
%script
  foo();

のような形で実行できる。

※参考URL
http://qiita.com/imk2o/items/9a854d19132bea621548