扩展bootstrap select插件

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

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

我想用自定义方法扩展插件,以便它可以完全按照我想要的方式执行。

我用以下方法扩展插件:

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

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

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

 $('select#begin' + _week + _day).selectpicker("customRemove"); 

要么

 $('select#begin' + _week + _day).selectpicker().customRemove(); 

我错过了什么吗?

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

 remove: function () { this.$newElement.remove(); this.$element.show(); } 

您可以使用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 } }); }()); 

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

我想,你在其他问题中得到了正确答案:
https://stackoverflow.com/a/31852632/4928642

 jQuery.fn.selectpicker.Constructor.prototype.customRemove = function () { this.$newElement.remove(); this.$element.show(); }; 

然后

 $smth.selectpicker("customRemove");