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!
It looks like it would work to me... however it might be worth noting to anyone who reads this thread (as I'm sure the asker is aware), that modify event would only be triggered if an attribute was modified via jQuery's attr(key,val) method. Any attempt to alter an attribute otherwise wouldn't kick it off.
Also... you'll want to be sure to add one to .css(x,y)
and .width(val)
, .height(val)
, as well as .addClass(val)
, .removeClass(val)
off the top of my head... and probably more. There's probably a lot you'll want to do.
I'm more curious about the "why?" you want to do this... lol.
精彩评论