如果我想通过替换其中一个函数来调整 jQuery UI 对象的某些功能,我该怎么做呢?
示例:假设我想修改 jQuery 自动完成小部件呈现建议的方式。自动完成对象上有一个方法,如下所示:
_renderItem: function( ul, item) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
},
我可以更换这个吗?
我想这可能会被称为猴子补丁.
如何?我会使用什么语法?
我不了解 jQuery UI,但一般来说,这就是重新定义函数的方式:
(function() {
var _oldFunc = _renderItem;
_renderItem = function(ul,item) {
// do your thing
// and optionally call the original function:
return _oldFunc(ul,item);
}
})();
将其包装在匿名函数中的原因是为了创建一个闭包来存储原始函数。这样它就永远不会干扰全局变量。
EDIT
要对 jQuery UI 小部件上的 fn 执行此操作,请使用以下语法:
仅供参考:获取该功能的方式是这样的:
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
};
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)