繁体   English   中英

向Bootstrap.js添加自定义函数

[英]Adding custom function to Bootstrap.js

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

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

我通过向Modal的构造函数添加一个函数来完成此工作:

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

但是,未传递myParameter变量。 如何将myParameter访问/传递给自定义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]() // <-- here
      else if (options.show) data.show()
    })
  }

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

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

        // blah blah blah
    });
}

我发现了一种方法,尽管不幸的是,它涉及到对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
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM