Rails / Javascript:如何注入rails变量到(非常)简单的javascript [英] Rails/Javascript: How to inject rails variables into (very) simple javascript
问题描述
我想在rails中写一个非常简单的javascript计算器,它将输入字段的数量乘以存储在rails变量中的数字(@ item.base_price)
I want to write up a very simple javascript calculator in rails which multiplies the quantity of an input field by a number stored in a rails variable (@item.base_price)
因此,在javascript / coffeescript方面,这是粗略的:
So, on the javascript/coffeescript side of things, it's crudely this:
# app/assets/javascript/items.js.coffee
$ ->
$('#item_quantity').change ->
quantity_val = $(this).val()
$('#total_amount').html(quantity_val * <%= I_WANT_@ITEM.BASE_PRICE_HERE %>)
我知道我怎么能通过ajax调用每个change()调用,但我认为有
I'm aware of how I can do this via an ajax call on each change() call, but I figure there has to be an elegant, hopefully unobtrusive rails way which doesn't hit the server each time.
任何建议非常感谢
推荐答案
如果您使用rails 3.1,您可以利用资源管道对javascript文件进行一些预处理,然后再提供它们。为此,只需更改文件扩展名:
If you are using rails 3.1 you can take advantage of the assets pipeline to do some pre-processing on the javascript files before you serve them up. To do this just change the file extension from:
items.js.coffee
到
items.js.coffee.erb
那么你可以添加ruby到你的javascript,就像在你的视图中使用< ;%=%>
标记。你可能遇到的唯一的问题是,你的items.js文件将提供给每个请求任何应用程序的控制器方法。因此,最好编写一个只在实例变量初始化时返回值的辅助方法
then you can add ruby to your javascript just like in your view with <%= %>
tags. The only gotcha you might run into, is that your items.js file will be served to every request to any of your app's controller methods. So its best to write a helper method that will return the value only if the instance variable is initialized
例如在items_helper.rb
For example in items_helper.rb
def item_price
if @item
@item.base_price
else
0
end
end
编辑:更多关于资产管道的信息:
more about assets pipeline here:
http://guides.rubyonrails.org/asset_pipeline.html
这篇关于Rails / Javascript:如何注入rails变量到(非常)简单的javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!