Very good and detailed example and reasons to use is considered in railscast by Ryan Bates
When you need to send some start data from your controller to your js
you might be doing something like this:
Write this data in controller(presenter/model) to some variable
In view for this action you put this variable to some objects by data
attributes, or write js right in view
Then there can be two ways in js:
+ if you previously wrote data in data
attributes - you should parse this attributes and write data to some
js variable.
+ if you wrote js right in view (many frontenders would shame you for
that) - you just use data from this js - OK.
You can use your data in your js
And every time when you need to send some data from action to js you do this.
With gon you configure it firstly - just put in layout one tag, and add
gem line to your Gemfile and do the following:
Write variables by
gon.variable_name=variable_value# or new syntaxgon.push({:user_id=>1,:user_role=>"admin"})gon.push(any_object)# any_object with respond_to? :each_pair
In your js you get this by
gon.variable_name
profit?
With the gon.watch feature you can easily renew data in gon variables!
Simply call gon.watch from your js file. It's super useful
in modern web applications!
Usage
More details about configuration and usage you can find in gon wiki
app/views/layouts/application.html.erb
<head><title>some title</title><%=Gon::Base.render_data%><!-- include your action js code -->
...
If your site uses AMD modules you can use the include_gon_amd helper to
include the variables and watch function as a module. Options are mostly
the same as for include_gon, except for namespace_check, which does
nothing and namespace, which is used as the name of the defined module.
The end result will look somewhat like the following:
请发表评论