[英]Javascript functions in the rails 4 asset pipeline tree
當我將JavaScript函數放入Rails Asset Pipeline清單中時,我試圖通過Chrome控制台使用JavaScript函數。 這是我創建和設置簡單的Rails 4.2.4 App所采取的步驟
$ rails new JavascriptExample
$ cd JavascriptExample
$ rails g scaffold Bear name:string
$ rake db:migrate
然后,我編輯app/assets/javascripts/bears.coffee
並添加控制台日志和功能。
console.log("asset pipeline sucks")
square = (x) -> x * x
然后我啟動服務器
$ rails s
我訪問了localhost:3000/bears
,在Chrome控制台中,我看到第一行代碼已經起作用。 但是,當我嘗試命令square(5);
在控制台中,我收到一個錯誤: Uncaught ReferenceError: square is not defined(…)
當此函數明確加載到application.js
時,為什么不能這樣做呢?
這是您的coffeescript被編譯為javascript的內容
(function() {
var square;
console.log("asset pipeline sucks");
square = function(x) {
return x * x;
};
}).call(this);
從這個 : the var keyword is reserved in CoffeeScript, and will trigger a syntax error if used. Local variables are created implicitly by default
the var keyword is reserved in CoffeeScript, and will trigger a syntax error if used. Local variables are created implicitly by default
,因此按您的期望在全局范圍內不可用
為了使它起作用,我們可以改為執行以下操作:
console.log("asset pipeline sucks")
@square = (x) -> x * x
請注意,我們有@
,現在編譯的javascript將是:
(function() {
console.log("asset pipeline sucks");
this.square = function(x) {
return x * x;
};
}).call(this);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.