[英]How to import javascript in rails with asset pipeline
在我的應用程序中,我有一個控制器支持一個非常復雜的對象,該對象有很多用 coffescript 編寫的 javascript。
我想將 javascript 安排在幾個單獨的文件上,以便更好地安排代碼,盡管我不知道如何導入這些額外的文件。
例如,我的文件app/assets/javascripts/general_functions.js.coffee
包含以下內容:
# rounds a number
roundNumber = (rnum, rlength = 5) ->
pow = Math.pow( 10, rlength )
newnumber = Math.round(rnum*pow)/pow
parseFloat(newnumber)
# floors a number
floorNumber = (rnum, rlength = 5) ->
pow = Math.pow( 10, rlength )
newnumber = Math.floor(rnum*pow)/pow
parseFloat(newnumber)
# returns true if the str ends with suffix
endsWith = (str, suffix) ->
str.indexOf(suffix, str.length - suffix.length) != -1
# returns the absolute value of a number (always >= 0)
abs = (num) ->
if num < 0 then - num else num
如何將其導入到需要這些功能的app/assets/javascripts/projects.js.coffee
中?
我試過添加
//= require general_functions
到app/assets/javascripts/application.js
,沒有成功
有任何想法嗎?
謝謝,
沒有成功,我猜瀏覽器告訴你你的general_functions.js.coffee
函數都不存在,你會收到如下錯誤:
參考錯誤:roundNumber 未定義
您有一個簡單的范圍界定問題。 CoffeeScript 文件的編譯版本被包裝在一個自執行函數中以防止命名空間污染,因此:
roundNumber = (rnum, rlength = 5) ->
pow = Math.pow( 10, rlength )
newnumber = Math.round(rnum*pow)/pow
parseFloat(newnumber)
當它到達瀏覽器時看起來像這樣:
(function() {
var roundNumber;
roundNumber = function(rnum, rlength) {
// ...
};
})();
並且您定義的所有函數都是隱藏的。 如果你希望你的函數是全局的,那么將它們定義為window
屬性:
window.roundNumber = (rnum, rlength = 5) ->
# ...
或者更好的是,您可以在加載主 (Coffee|Java)Script 之前的某處創建一個特定於應用程序的命名空間:
app = { }
並將您的功能放在那里:
app.roundNumber = (rnum, rlength = 5) ->
# ...
Javascript 應該自動包含在您的 Rails 應用程序中,每個控制器都有自己的 js 文件。 使用下面的說明將包括它們。
您的app/assets/javascripts/application.js.coffee
應包含以下行:
#= require_tree .
或者app/assets/javascripts/application.js
(純 javascript):
//= require_tree .
當您在瀏覽器中查看頁面的源代碼時,您應該會看到如下內容:
<script src="/assets/projects.js?body=1"></script>
您所描述的是具有通用功能的幫助程序或更全局的 js 文件。 您可以將這些添加到 application.js。 此外,使用如下結構將包括 vendor/assets/javascripts/some_generic_feature.js(.coffee)
//= require some_generic_feature
在application.js
中以正確的順序添加兩個文件:
應用程序.js
//= require general_functions
//= require projects
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.