添加自定义函数到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
到自定义引导方法?
你不可能按原样做。Model用来调用函数的代码没有考虑参数;
$.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
}
我仍在试验,以确保这个更改不会产生任何不良的副作用,但到目前为止,一切都如预期的那样工作。我们欢迎任何更优雅的解决方案。
相关文章:
- Bootstrap CSS和JS我必须将它们包含在单独的文件中,或者可以编译它们
- jquery.proxy in the bootstrap-typeahead.js context
- 理解bootstrap.js变量声明
- parent和iframe中的Bootstrap.js文件
- 如何扩展bootstrap-typeahead.js这样的库
- Rails - Bootstrap popover js
- 使用节点js的Bootstrap和Jquery
- Node.js & Express 不能用简单的 Bootstrap 表单发布/错误
- Charts.js & Bootstrap Accordion
- Bootstrap, CSS, JS - Bootstrap 文件菜单栏在点击后悬停
- Angular js bootstrap模式在bootstrap的低级版本中是不可滚动的
- react JS bootstrap JS not working
- Knockout.js + Bootstrap -奇怪的事情发生了
- JS Bootstrap模式的执行顺序
- 如何使用Angular Js + bootstrap设置弹出窗口
- 格式化Angular JS/Bootstrap选项卡
- HTML/JS - Bootstrap Datepicker
- fbAlbum2.js, bootstrap-tooltip and Magnific-Popup
- jQuery, react.js, bootstrap,验证密码
- console.log和html操作的行为不期望使用node.js, bootstrap和jquery