[英]Is there a way to use ActionView Helpers in Coffeescript/Javascript in Rails 4?
例如,如果我想在kites.js.coffee中做類似的事情:
= select_tag :kite, options_for_select([["kite1","1"],["kite2","2"]], selected: nil), {class: 'form-control', name: "kite[tail]"}
其中KITE_OPTIONS = [[“ kite1”,“ 1”],[“ kite2”,“ 2”]等]
重點是不必手動編寫如下的javascript代碼:
js_variable = "<select>....<option>kite1</option></select>";
您不應該這樣做,如果您在CofeeScript模板中包含ruby代碼,那么通過在每個請求上編譯CofeeScript將會增加性能開銷。 這就是為什么您沒有一種簡便的方法將ruby代碼包含到coffeescript中,其目的是避免這種情況。
您可以從視圖中提供javascript變量,然后在coffeeescript模板中使用它們:
javascript:
var options_for_select = '#{options_for_select([["kite1","1"],["kite2","2"]]}';
coffee:
$(document).ready ->
alert(options_for_select);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.