我想要改變$.prepend()
(可能是$.append()
)的功能,以便實現「關於DOM更改事件」。使用原型來更改現有jQuery函數的功能
我可以做簡單的東西如:
$.prepend = function() { alert('Hello World'); };
或者我需要使用$.extend()
功能或$.prototype.prepend
或$.fn.prepend
?
[我意識到我需要包括在我的新的,否則jQuery將打破prepend()
功能原始出處!]
編輯::最終解決
對於有興趣的人:
$.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);
你打我吧! ;) – mekwall 2011-05-19 09:15:46
兩個正確的答案比沒有答案好:) – mck89 2011-05-19 09:26:06
當然。儘管主要問題本身已得到解答,但我傾向於詳細說明我的答案,以使其通用。希望能幫助其他人提出類似的問題:) – mekwall 2011-05-19 09:29:56