我可以替换或修改jQuery UI小部件上的功能吗?如何? (猴子修补) [英] Can I replace or modify a function on a jQuery UI widget? How? (Monkey Patching)
问题描述
如果我想通过替换其中一个功能来调整jQuery UI对象的某些功能,我该怎么做呢?
If I want to tweak some of the capability of a jQuery UI object, by replacing one of the functions, how would I go about doing that?
示例:假设我想修改jQuery自动完成小部件呈现建议的方式.在自动完成对象上有一个方法如下:
Example: suppose I wanted to modify the way the jQuery autocomplete widget rendered the suggestions. There's a method on the autocomplete object that looks like this:
_renderItem: function( ul, item) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
},
我可以代替它吗?
我认为这可以称为 Monkey Patching .
如何?我会使用什么语法?
How? What syntax would I use?
推荐答案
我不了解jQuery UI,但是通常,这是您重新定义函数的方式:
I don't know about jQuery UI, but in general, this is how you redefine a function:
(function() {
var _oldFunc = _renderItem;
_renderItem = function(ul,item) {
// do your thing
// and optionally call the original function:
return _oldFunc(ul,item);
}
})();
将其包装在匿名函数中的原因是创建一个用于存储原始函数的闭包.这样,它就永远不会干扰全局变量.
The reason this is wrapped in an anonymous function is to create a closure for storing the original function. This way it can never interfere with global variables.
编辑
要在jQuery UI小部件上对fn执行此操作,请使用以下语法:
EDIT
To do this to a fn on a jQuery UI widget, use this syntax:
仅供参考:获取功能的方法如下:
FYI: the way to grab the function is like this:
function monkeyPatchAutocomplete() {
// don't really need this, but in case I did, I could store it and chain
var oldFn = $.ui.autocomplete.prototype._renderItem;
$.ui.autocomplete.prototype._renderItem = function( ul, item) {
// whatever
};
}
这篇关于我可以替换或修改jQuery UI小部件上的功能吗?如何? (猴子修补)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!