Last active
February 19, 2017 08:54
-
-
Save tomsoderlund/e31972aefe3e80c434e6c04d98a57561 to your computer and use it in GitHub Desktop.
SuperWatcher in JavaScript: watches a function/value, triggers a callback when changed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ----- 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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