Created
July 16, 2016 22:36
-
-
Save m3g4p0p/f72028927da3b12a2480e43f70bbfde5 to your computer and use it in GitHub Desktop.
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
(function($) { | |
$.fn.watch = function(callback, once) { | |
var options = { | |
childList: true, | |
subtree: true | |
}; | |
var _callOnNode = function() { | |
callback.call(this); | |
}; | |
var _mutationHandler = function(mutations, observer) { | |
$.each(mutations, function() { | |
$.each(this.removedNodes, _callOnNode); | |
$.each(this.addedNodes, _callOnNode); | |
}); | |
if (once) { | |
observer.disconnect(); | |
} | |
}; | |
$(this).each(function() { | |
var observer = new MutationObserver(_mutationHandler); | |
observer.observe(this, options); | |
}); | |
return this; | |
}; | |
})(window.jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
jQuery watch
Watch an element for descendants to be be added or removed. Takes an event handler as argument where
this
refers to the element being added or removed, and optionally a boolean which can be set totrue
if changes should be observed only once (i.e. the handler will get disconnected after the first observed change).Sample usage