Ruby on Rails 4 - coffee scriptで作った関数をhtml(view)側で呼び出す
3324 ワード
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();
のような形で実行できる。
Author And Source
この問題について(Ruby on Rails 4 - coffee scriptで作った関数をhtml(view)側で呼び出す), 我々は、より多くの情報をここで見つけました https://qiita.com/azusanakano/items/b3caa6d6f309b2476947著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .