File: watch.coffee

package info (click to toggle)
ruby-gon 6.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 504 kB
  • sloc: ruby: 1,383; makefile: 9
file content (52 lines) | stat: -rw-r--r-- 1,330 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
gon._timers = {}

gon.watch = (name, possibleOptions, possibleCallback, possibleErrorCallback) ->
  return unless $?

  if typeof possibleOptions == 'object'
    options = {}
    for key, value of gon.watchedVariables[name]
      options[key] = value
    for key, value of possibleOptions
      options[key] = value
    callback = possibleCallback
    errorCallback = possibleErrorCallback
  else
    options = gon.watchedVariables[name]
    callback = possibleOptions
    errorCallback = possibleCallback

  performAjax = ->
    xhr = $.ajax
      type: options.type || 'GET'
      url: options.url
      data:
        _method: options.method
        gon_return_variable: true
        gon_watched_variable: name

    if errorCallback
      xhr.done(callback).fail(errorCallback);
    else
      xhr.done(callback)

  if options.interval
    timer = setInterval(performAjax, options.interval)
    gon._timers[name] ?= []
    return gon._timers[name].push
      timer: timer
      fn: callback
  else
    return performAjax()

gon.unwatch = (name, fn) ->
  for timer, index in gon._timers[name] when timer.fn == fn
    clearInterval(timer.timer)
    gon._timers[name].splice(index, 1)
    return

gon.unwatchAll = ->
  for variable, timers of gon._timers
    for timer in timers
      clearInterval(timer.timer)
  gon._timers = {}