I would really like a way to observe changes to a node and trigger functions based on those changes.
I'm going to define "changes" as:
- Attribute edits/additions/deletions to a node and all descendants.
- Text node edits/additions/deletions inside a node and all descendants.
- Events bound/unbound to a node and all descendents.
- The addition/deletion of a descendant.
- CSS changes to a node and all descendents.
- The deletion of a node.
Now maybe I'm going about this the wrong way, but my thought was to doctor the pre-existing jQuery methods that are responsible for modifications like those listed above, and add some code that triggers an event on all of the nodes in the set, and their ancestors (simulating a bubbling event).
Something like this:
$.fn.attrMOD = $.fn.attr;
$.fn.attr = function() {
this.each(function(){
$.fn.trigger.call($(this).parents().add(this), 'modify', { changeType: 'attr', originalTarget: $(this) });
});
return $.fn.attrMOD.apply(this, arguments);
};
And I would do this for many of the methods (css, bind, unbind, etc).
So to subscribe to this "modify" event, you would do something like:
$('div').bind('modify', function() { console.log('Div was modified') })
//this would trigger it
$('div').attr('hello', 'world');
So a couple of questions:
- Am I crazy to try this?
- Am I going about this the right way? Keep in mind the code above isn't close to final, but that is my general idea.
Thanks for reading!