Created
July 25, 2012 15:13
-
-
Save roselan/3176700 to your computer and use it in GitHub Desktop.
jquery observe mutations plugin
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.observe = function( callback, options ) { | |
var settings = $.extend( { | |
attributes: true, | |
childList: true, | |
characterData: true | |
}, | |
options ); | |
return this.each(function() { | |
var self = this, | |
observer, | |
MutationObserver = window.MutationObserver || | |
window.WebKitMutationObserver || | |
window.MozMutationObserver; | |
if (MutationObserver && callback) { | |
observer = new MutationObserver(function(mutations) { | |
callback.call(self, mutations); | |
}); | |
observer.observe(this, settings); | |
} | |
}); | |
}; | |
})( jQuery ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The new MutationObserver thingy is implemented in current versions of FF and Chrome. It nicely replaces the DomSubTreeModified event... with some quirks.
This plugin aims to simplify and streamline the "listening", I mean observing, of mutations.
plugin usage:
In this particular example, the callback will be fired when the span is appended, not when the class is added. MutationRecord groups changes which occur over a short span of time. So it will not fire until all changes are made, and the final element state is reached.
In order to limit observed "events", 3 options for the observer are present: attributes, childList and characterData, usage:
MutationRecord isn't yet complete, and this plugin, even if limited in it's scope, increases MutationRecord utility. It's most useful with $.clone(). You can trace document versions, and it can help for debugging. But you can too clone windows in real time, even on different computers with a bit of ajaxing and server forwarding! This is extremely promising: web apps might be able to provide efficient real time pure html "remote desktop" support. As well, it provides userscripts writers who have to look up for ajax DOM updates with a more elegant method than setTimeout check loops.
Still lots to do...$.on() ( $ ('table').observeChidldren('td', callback); ), which should loop MutationRecord to select only records affecting children.
A "state" shall be added in order to able to destroy/disconnect observers, even if overloading an element with observers scales extraordinarily well. Maybe some kind of "container" can be added too, as the
You can check this fiddle for a live demo (and copy the plugin for your needs until I find a way to git it )