我可以替换或修改jQuery UI小部件上的函数吗?怎么样?(猴子补丁)

Che*_*eso 10 jquery monkeypatching

如果我想调整jQuery UI对象的一些功能,通过替换其中一个函数,我将如何去做呢?

示例:假设我想修改jQuery自动完成小部件呈现建议的方式.自动完成对象上有一个方法如下所示:

_renderItem: function( ul, item) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + item.label + "</a>" )
        .appendTo( ul );
},
Run Code Online (Sandbox Code Playgroud)

我可以替换它吗?

我想这可能叫做Monkey Patching.

怎么样?我会用什么语法?

Phi*_*ert 18

我不知道jQuery UI,但总的来说,这就是你重新定义一个函数的方法:

(function() {
   var _oldFunc = _renderItem;

   _renderItem = function(ul,item) {
      // do your thing
      // and optionally call the original function:
      return _oldFunc(ul,item);
   }
})();
Run Code Online (Sandbox Code Playgroud)

这包含在一个匿名函数中的原因是创建一个用于存储原始函数的闭包.这样它就不会干扰全局变量.


编辑
要在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
  }; 
} 
Run Code Online (Sandbox Code Playgroud)

  • 猴子修补或,正如保罗爱尔兰解释,鸭子冲孔:) - http://paulirish.com/2010/duck-punching-with-jquery/ (4认同)