13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-04-30
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

13
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?