-
-
Notifications
You must be signed in to change notification settings - Fork 183
Usage gon watch
New feature gon.watch
allows you to renew your gon variable data through ajax super easy!
The idea is in calling your action for using your controller logic, where you added watched variable, but render only needed value of needed variable.
Fun samples without details: unix top
Simple example which allows you renew count of users each second on page without reloading:
-
Instead of just
gon.variable_name
you should usegon.watch.variable_name
:app/controllers/home_controller.rb
def index @users_count = User.count gon.watch.users_count = @users end
-
You should pass option
:watch => true
toinclude_gon
helper:app/views/layouts/application.html.erb
<head> <title>some title</title> <%= include_gon(watch: true) %> <!-- include your action js code --> ...
-
Part of your index page where displayed count of users:
app/views/home/index.html.erb
... <div id='users-counter'> <%= @users_count %> </div> ... <a href='#' id='stop-renewing'> Stop renewing </a> ...
-
In your js file (or coffee or whatever) you can call
gon.watch
function which accepts next parameters:gon.watch(name_of_variable, options, callback)
-
name_of_variable
- name of variable from controller (ingon.watch.a = 123
it will be 'a') -
options
- in current realization all options are optional:-
interval
- this option allows you to make cycle forgon.watch
. Eachn
milliseconds which you pass with this optiongon.watch
will make ajax request and call callback after success. You can stop executing this cycle by callinggon.unwatch
with same name and callback as forgon.watch
. -
method
- this method will be used in ajax request -
url
- url for ajax request
-
-
callback
- function, which will be called with data from success ajax response. It is identifier for cycle in case when you use optioninterval
and want to stop this cycle after a while. Or when you want to renew one variable with different options.
app/assets/javascripts/home.js.coffee
renewUsers = (count) -> $('#users-counter').text(count) gon.watch('users_count', interval: 1000, renewUsers) $('#stop-renewing').click -> gon.unwatch('users_count', renewUsers) return false
-