Usage gon watch

Philippe Vaucher edited this page Feb 16, 2014 · 11 revisions

Use of gon.watched allows you to render data in your variable without reloading of a page. This functionality can be used to refresh data with cycle with n-milliseconds periods or just once, when it's is called by some action.

Here you are fun samples without details: unix top

I would also like to show you a  simple example, which would renew count of users on your page each second without reloading the page at all:

  1. Instead of just gon.variable_name you should use gon.watch.variable_name:

    app/controllers/home_controller.rb

    def index
      @users_count = User.count
      gon.watch.users_count = @users_count
    end
  2. OPTIONAL: if you want to be explicit, you can pass option :watch => true to include_gon helper (but it is not required as it is automatically detected when you use gon.watch in your controllers) :

    app/views/layouts/application.html.erb

    <head>
      <title>some title</title>
      <%= include_gon(watch: true) %>
      <!-- include your action js code -->
      ...
  3. Part of your index page displaying count of users:

    app/views/home/index.html.erb

    ...
    <div id='users-counter'>
      <%= @users_count %>
    </div>
    ...
    <a href='#' id='stop-renewing'>
      Stop renewing
    </a>
    ...
  4. 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 (in gon.watch.a = 123 it will be 'a')
    • options - currently all options are optional:
      • interval - this option allows you to make cycle for gon.watch. Each n milliseconds which you pass with this option gon.watch will make ajax request and call callback after success. You can stop executing this cycle by calling gon.unwatch with same name and callback as for gon.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 an identifier for cycle in case when you use option interval and intend 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