Skip to content

Instantly share code, notes, and snippets.

@padolsey
Last active February 21, 2024 11:50
Show Gist options
  • Select an option

  • Save padolsey/7567323 to your computer and use it in GitHub Desktop.

Select an option

Save padolsey/7567323 to your computer and use it in GitHub Desktop.
jQuery style watcher/thrower
jQuery.throwOnStyle = (function($) {
var watchers = [];
$.style = (function(_style) {
return function(elem, name, value) {
for (var i = 0, l = watchers.length; i < l; ++i) {
var w = watchers[i];
if (
(w.styleMatcher.test ?
w.styleMatcher.test(name) :
w.styleMatcher === name)
&&
(w.valueMatcher.test ?
w.valueMatcher.test(value) :
w.valueMatcher === value)
&& $(elem).is(w.selector)
) {
throw new Error('Matched! ' + w.selector + ':: ' + name + ':' + value);
}
}
return _style.apply(this, arguments);
};
}($.style));
return function(selector, styleMatcher, valueMatcher) {
var addedAt = watchers.push({
selector: selector,
styleMatcher: styleMatcher,
valueMatcher: valueMatcher
}) - 1;
return function() {
watchers.splice(addedAt, 1);
};
};
}(jQuery));
// WARNING: This will potentially be very slow -- use sparingly, even when debugging.
jQuery.throwOnStyle('body', 'color', 'red');
// Throws Exception if someone tries to set the BODY element's color to red via jQuery's CSS API
jQuery.throwOnStyle('.something.foo', /^(?:background|backgroundColor)$/, /purple/);
// Throws Exception if someone tries to set a background or backgroundColor to a value containing
// purple on any element that complies with the CSS selector, '.something.foo'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment