Extend bootstrap select plugin

丶灬走出姿态 提交于 2019-12-12 10:43:00

问题


In my previous question I was talking about the bootstrap select plugin where the destroy method is doing something that I don't want. I edit manually the plugin but this is not a good practice.

Bootstrap select destroy removes the original select from DOM

I would like to extend the plugin with a custom method so that it can do exactly wat I want.

I extend the plugin with folloing method:

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

This is located in another js file under the bootstrap select script file.

How do I call this new method? I tried the following without success:

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

or

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

Am I missing something?

The original method of the destroy function in the bootstrap select plugin:

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

回答1:


I think, you have the correct answer in other your question:
https://stackoverflow.com/a/31852632/4928642

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

then

$smth.selectpicker("customRemove");



回答2:


You could proxy the function with your own function using a mixin closure, like:

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

Note: this will overweite the prototype for all Bootstrap selects and modify its behaviour.



来源:https://stackoverflow.com/questions/27334426/extend-bootstrap-select-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!