扩展bootstrap select插件

Miv*_*web 6 jquery twitter-bootstrap bootstrap-select

在我之前的问题中,我在讨论bootstrap select插件,其中destroy方法正在做我不想要的事情.我手动编辑插件,但这不是一个好习惯.

Bootstrap select destroy从DOM中删除原始选择

我想用自定义方法扩展插件,以便它可以完成我想要的扫描.

我用以下方法扩展插件:

$.extend(true, $.fn.selectpicker.prototype, {
    customRemove: function () {
        this.$newElement.remove();
        this.$element.show();
    }
});
Run Code Online (Sandbox Code Playgroud)

它位于bootstrap select脚本文件下的另一个js文件中.

我该如何称呼这种新方法?我尝试了以下但没有成功:

$('select#begin' + _week + _day).selectpicker("customRemove");
Run Code Online (Sandbox Code Playgroud)

要么

$('select#begin' + _week + _day).selectpicker().customRemove();
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

bootstrap select插件中destroy函数的原始方法:

remove: function () {
  this.$newElement.remove();
  this.$element.show();
}
Run Code Online (Sandbox Code Playgroud)

cli*_*all 1

您可以使用 mixin 闭包用您自己的函数代理该函数,例如:

(function()
{
  // grab a reference to the existing remove function
  var _remove = $.fn.selectpicker.prototype.remove;

  // anything declared in here is private to this closure
  // so you could declare helper functions or variables
  // ...

  // extend the prototype with your mixin
  $.extend(true, $.fn.selectpicker.prototype, 
  {
    // this will replace the original $.fn.selectpicker.prototype.remove function
    remove: function () 
    {
      // call whatever code you want here
      // ...
      // ... like grabbing the DOM element
      // ...
      // then call the original remove function
      _remove.apply(this, arguments);

      // then call whatever you want here, like re-adding the DOM element
    }
  });
}());
Run Code Online (Sandbox Code Playgroud)

注意:这将覆盖所有 Bootstrap 选择的原型并修改其行为。