0

我最近遇到了一种情况,我想从根本上改变 Bootstrap 的默认行为。我想向Modal该类添加一个自定义方法,以便可以像任何其他库存方法一样调用自定义Modal方法:

$('#my-modal').modal('myMethod', myParameter);

我通过向Modal的构造函数添加一个函数来实现这一点:

$.fn.modal.Constructor.prototype.myMethod = function (myParameter) {
  ...
}

但是,myParameter变量没有被传递。如何访问/传递myParameter给自定义 Bootstrap 方法?

4

2 回答 2

0

您无法按原样执行此操作。模型用来调用函数的代码不考虑参数;

  $.fn.modal = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('modal')
        , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
      if (!data) $this.data('modal', (data = new Modal(this, options)))
      if (typeof option == 'string') data[option]() // <-- here
      else if (options.show) data.show()
    })
  }

最好的办法是向 中添加一个方法$.fn,然后Model通过 检索实例$(this).data('modal'),因为这是 Bootstrap 存储实例的地方;

$.fn.foo = function (param) {
    return this.each(function () {
        var model = $(this).data('modal');

        // blah blah blah
    });
}
于 2013-03-06T20:04:25.147 回答
0

我找到了一种方法来做到这一点,尽管不幸的是它涉及到对 Bootstrap 源的更改。执行实际方法调用的代码如下:

$.fn.modal = function (option) {
  return this.each(function () {
    var $this = $(this)
      , data = $this.data('modal')
      , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
    if (!data) $this.data('modal', (data = new Modal(this, options)))
    if (typeof option == 'string') data[option]()
    else if (options.show) data.show()
  })
}

要更改这一点,应修改第 7 行(源代码中的第 206 行)以传递最初传递给封闭函数的任何附加参数。此外,必须为 jQuery.each()函数的每次迭代提供原始参数。这是工作代码:

$.fn.modal = function (option) {
  return this.each(function () {
    var $this = $(this)
      , data = $this.data('modal')
      , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
    if (!data) $this.data('modal', (data = new Modal(this, options)))
    if (typeof option == 'string') data[option].apply($this.data('modal'), Array.prototype.slice.call(arguments, 1)); // pass the parameters on
    else if (options.show) data.show()
  }, arguments) // execute each iteration with the original parameters
}

我仍在尝试确保此更改不会产生任何不良副作用,但到目前为止,一切都按预期工作。欢迎任何更优雅的解决方案。

于 2013-03-06T22:42:16.903 回答