@@ -3,8 +3,10 @@ class Watch < Gon
33 class << self
44
55 JS_FUNCTION = \
6- "window.gon.watch = function(name, possibleOptions, possibleCallback) {
7- var callback, key, options, value, xhr, _ref;
6+ "gon._timers = {};
7+
8+ gon.watch = function(name, possibleOptions, possibleCallback) {
9+ var callback, key, options, performAjax, timer, value, _base, _ref, _ref1;
810 if (typeof $ === 'undefined' || $ === null) {
911 return;
1012 }
@@ -24,17 +26,44 @@ class << self
2426 options = gon.watchedVariables[name];
2527 callback = possibleOptions;
2628 }
27- xhr = $.ajax({
28- type: options.type || 'GET',
29- url: options.url,
30- data: {
31- _method: options.method,
32- gon_return_variable: true,
33- gon_watched_variable: name
29+ performAjax = function() {
30+ var xhr;
31+ xhr = $.ajax({
32+ type: options.type || 'GET',
33+ url: options.url,
34+ data: {
35+ _method: options.method,
36+ gon_return_variable: true,
37+ gon_watched_variable: name
38+ }
39+ });
40+ return xhr.done(callback);
41+ };
42+ if (options.interval) {
43+ timer = setInterval(performAjax, options.interval);
44+ if ((_ref1 = (_base = gon._timers)[name]) == null) {
45+ _base[name] = [];
46+ }
47+ return gon._timers[name].push({
48+ timer: timer,
49+ fn: callback
50+ });
51+ } else {
52+ return performAjax;
53+ }
54+ };
55+
56+ gon.unwatch = function(name, fn) {
57+ var index, timer, _i, _len, _ref;
58+ _ref = gon._timers[name];
59+ for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
60+ timer = _ref[index];
61+ if (timer.fn === fn) {
62+ clearInterval(timer.timer);
63+ gon._timers[name].splice(index, 1);
64+ return;
3465 }
35- });
36- xhr.done(callback);
37- return true;
66+ }
3867 };"
3968
4069 def render
0 commit comments