Created
April 24, 2010 22:12
-
-
Save cowboy/377986 to your computer and use it in GitHub Desktop.
"domchanged" event idea for ralph holzmann
This file contains hidden or 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
// Rough implementation, untested, etc | |
// Will obviously fail when non-overridden methods are used to change the DOM | |
(function($){ | |
// All "DOM modifying" methods (probably not complete). | |
var methods = 'unwrap html wrapApp wrapInner append appendTo html prepend prependTo text after before insertAfter insertBefore'.split(' '); | |
$.each( methods, function( i, method ) { | |
// Store a reference to the original method. | |
var orig = $.fn[ method ]; | |
// Override the original method. | |
$.fn[ method ] = function(){ | |
var args = arguments, | |
elems = [], | |
filtered = []; | |
// For each selected element... | |
this.each(function(){ | |
// Store the initial HTML. | |
var html = this.innerHTML; | |
// Execute the original method. | |
orig.apply( $(this), args ); | |
// If the HTML has changed, add this element to the list of elements. | |
if ( this.innerHTML !== html ) { | |
elems.push( this ); | |
} | |
}); | |
// Unique the elements list, and iterate over it. The goal here is, since | |
// the "domchanged" event will bubble, to remove any elements that are | |
// ancestors of other elements from the internal list. | |
$.each( $.unique( elems ), function( i, elem ){ | |
var push = true; | |
filtered = $.map( filtered, function( item ){ | |
if ( $.contains( elem, item ) ) { | |
// Since elem is an ancestor of filtered list item, discard elem. | |
push = false; | |
} else if ( $.contains( item, elem ) ) { | |
// Since elem is a descendant of filtered list item, replace item | |
// with elem. | |
push = false; | |
return elem; | |
} | |
}); | |
// If elem wasn't discarded, push it onto the filtered items list. | |
push && filtered.push( elem ); | |
}); | |
// Trigger a custom 'domchanged' event that will bubble! | |
// TODO: filter out "parent" elements to avoid unnecessary triggering! | |
$(filtered).trigger( 'domchanged' ); | |
return this; | |
}; | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment