「on DOM change event」を実現するために、$.prepend()
(そしておそらくの)機能を変更したいと思います。$.append()
次のような簡単なことはできますか?
$.prepend = function() { alert('Hello World'); };
$.extend()
または、関数 or$.prototype.prepend
またはを使用する必要がありますか$.fn.prepend
?
[関数の元のソースを新しい関数に含める必要があることに気付きましたprepend()
。そうしないと、jQuery が壊れます!]
編集::最終的な解決策
興味のある方へ:
$.extend($, {
domChangeStack: [],
onDomChange: function(selector, fn, unbind, removeFromStack) {
/* Needs to store: selector, function, unbind flag, removeFromStack flag */
jQuery.domChangeStack.push([selector, fn, unbind, removeFromStack]);
},
domChangeEvent: function() {
/* Ideally should only affect inserted HTML/altered DOM, but this doesn't */
var stackItem, newStack = [];
while (stackItem = jQuery.domChangeStack.pop()) {
var selector = stackItem[0],
fn = stackItem[1],
unbind = stackItem[2],
remove = stackItem[3];
if (unbind) { $(selector).unbind(); }
// Need to pass the jQuery object as fn is anonymous
fn($(selector));
if (!remove) { newStack.push(stackItem); }
}
jQuery.domChangeStack = newStack;
// Show something happened!
console.log("domChangeEvent: stack size = " + newStack.length);
}
});
$.fn.prepend = function() {
var result = this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
// Need to actually alter DOM above before calling the DOMChange event
$.domChangeEvent();
return result;
};
そして使用法:
/* Run the given function on the elements found by the selector,
* don't run unbind() beforehand and don't pop this DOMChange
* event off the stack.
*/
$.onDomChange(".element_class", function(jObj) {
jObj.do_something_awesome();
}, false, false);