Skip to content

Instantly share code, notes, and snippets.

@tomsoderlund
Last active February 19, 2017 08:54
Show Gist options
  • Save tomsoderlund/e31972aefe3e80c434e6c04d98a57561 to your computer and use it in GitHub Desktop.
Save tomsoderlund/e31972aefe3e80c434e6c04d98a57561 to your computer and use it in GitHub Desktop.
SuperWatcher in JavaScript: watches a function/value, triggers a callback when changed
// ----- SuperWatcher JQuery extension -----
var watcher = new SuperWatcher();
// Dynamically modify a CSS property when function result changes
$.fn.dynamicCss = function (prop, func) {
// Currying the $.css method
watcher.add(func.bind(this), this.css.bind(this, prop), prop);
// For function chaining
return this;
}
/*
SuperWatcher: watches a function/value, triggers a callback when changed
Usage:
watcher.add(myFunction, callbackWhenChanged);
*/
function SuperWatcher() {
var watchers = [];
var getValueOf = function(val) {
return (typeof(val) === 'function' ? val() : val);
};
var checkWatchers = function() {
for (var i in watchers) {
if (watchers[i].lastValue !== getValueOf(watchers[i].watching)) {
watchers[i].lastValue = getValueOf(watchers[i].watching);
// Trigger callback
if (watchers[i].callback) {
watchers[i].callback(watchers[i].lastValue);
}
}
}
};
// Timer
var timerId = setInterval(checkWatchers, 1000);
// ----- Public methods -----
this.add = function(val, cb) {
watchers.push({
watching: val,
lastValue: getValueOf(val),
callback: cb
});
// Do an initial callback
cb(getValueOf(val));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment