如果我想调整一些jQuery UI对象的功能,通过替换其中一个函数,我将如何去做呢?
示例:假设我想修改jQuery自动完成小部件呈现建议的方式.自动完成对象上有一个方法如下所示:
_renderItem: function( ul,item) {
return $( "<li></li>" )
.data( "item.autocomplete",item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
},
我可以替换它吗?
我想这可能叫做Monkey Patching.
怎么样?我会用什么语法?
解决方法
我不知道jQuery UI,但一般来说,这就是重新定义函数的方法:
(function() {
var _oldFunc = _renderItem;
_renderItem = function(ul,item) {
// do your thing
// and optionally call the original function:
return _oldFunc(ul,item);
}
})();
这包含在匿名函数中的原因是创建一个用于存储原始函数的闭包.这样它就不会干扰全局变量.
编辑
要在jQuery UI小部件上执行此操作,请使用以下语法:
仅供参考:获取功能的方式如下:
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
};
}