Skip to content

Instantly share code, notes, and snippets.

@yckart
Last active May 12, 2019 12:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yckart/c893d7db0f49b1ea4dfb to your computer and use it in GitHub Desktop.
Save yckart/c893d7db0f49b1ea4dfb to your computer and use it in GitHub Desktop.

The usage is quite simple, just add a new listender to the node you want to observe and manipulate the classes as usually:

var $node = $('div')

  // listen to class-manipulations
  .on('addClass toggleClass removeClass', function (e, oldClass, newClass) {
    console.log('Changed from %s to %s due %s', oldClass, newClass, e.type);
  })

  // make some changes
  .addClass('foo')
  .removeClass('foo')
  .toggleClass('foo');
/*! jquery.observe.class.js v0.0.1 | MIT License | gist.github.com/yckart/c893d7db0f49b1ea4dfb */
(function ($) {
var methods = ['addClass', 'toggleClass', 'removeClass'];
$.each(methods, function (index, method) {
$.observe(method, function () {
return this[0].className;
});
});
}(window.jQuery || window.Zepto));
/*! jquery.observe.js v0.0.1 | MIT License | gist.github.com/yckart/c893d7db0f49b1ea4dfb */
$.observe = function (method, getter) {
// store the original handler function
var originalMethod = $.fn[method];
$.fn[method] = function () {
// cache $(this)
var self = this;
// store the old value
var oldValue = getter.call(self, arguments);
// execute the original hanlder and store its return value
var result = originalMethod.apply(self, arguments);
// store the new value
var newValue = getter.call(self, arguments);
// trigger the custom event and pass the stored old & new value
self.trigger(method, [oldValue, newValue]);
// return the result from the original handler.
return result;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment