jQuery UI 위젯에서 함수를 교체하거나 수정할 수 있습니까? 어떻게? (원숭이 패치)

StackOverflow https://stackoverflow.com/questions/2436315

  •  19-09-2019
  •  | 
  •  

문제

함수 중 하나를 대체하여 jQuery UI 객체의 기능 중 일부를 조정하려면 어떻게해야합니까?

예 : JQuery AutoComplete 위젯이 제안을하는 방식을 수정하고 싶다고 가정합니다. 자동 완성 객체에 다음과 같이 보이는 메소드가 있습니다.

_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);
   }
})();

이것이 익명 함수로 래핑되는 이유는 원래 기능을 저장하기위한 클로저를 작성하는 것입니다. 이렇게하면 글로벌 변수를 방해 할 수 없습니다.


편집하다
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
  }; 
} 

다른 팁

나는 그것이 오래된 질문이라는 것을 알고 있지만, 오래된 프로젝트에서 버그를 해결해야했고 이런 종류의 패치에 문제가있었습니다.

옵션 객체를 통해 기능을 사용할 수있게 한 다음 특정 논리를 거기에 넣으십시오.

반점:

(function monkeyPatchJQueryAutocomplete($) {

  /**
   * Proxies a private
   * prototype method to the
   * options Object
   *
   * @param  {Object} obj
   * @param  {String} funcName
   */
  function proxyPrivateMethodToOptions(obj, funcName) {
    var __super = obj.prototype[funcName];
    obj.prototype[funcName] = function() {
      if (this.options[funcName]) {
        return this.options[funcName].apply(this, arguments);
      }
      return __super.apply(this, arguments);
    };
  }

  // Make the private _renderItem
  // method available through the options Object
  proxyPrivateMethodToOptions($.ui.autocomplete, '_renderItem');

  // We can do this for other methods as well:
  proxyPrivateMethodToOptions($.ui.autocomplete, '_renderMenu');

}($));

사용-예 :

$('.some-input').autocomplete({
  _renderItem: function(ul, item) {
    console.log('here we can reference the old func via: ', __super);
    return $("<li>")
      .append($("<a>").text(item.label))
      .appendTo(ul);
  }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top