Bootstrap前端框架js插件部分浅析
写这些东西都是为了让自己能够学以致用,学到更多东西吧。
Let's go
1.结构 Bootstrap所有的js模块都是基于最新版本的jQuery所开发的插件。 以bootstrap-modal.js为例:
!function ($) {
var Modal = function (content, options) {
//.....
}
Modal.prototype = {
//....
}
function xx() { //功能函数,多个
}
$.fn.modal = function (option) {
//集成到jQuery
}
$.fn.modal.defaults = {
//默认参数
}
$.fn.modal.Constructor = Modal //维护原型链
$(function () {
$('body').on('click.modal.data-api', '[data-toggle=modal]', function (e) {
//集成自动功能,加上 data-toggle="modal" 属性,则自动绑定事件。
}
}
}
2.浅析 这种结构我们应该是很熟悉的,我们平时自己开发jQuery插件也多是这种结构。
主要对Bootstrap最后一个自动调用的代码进行分析。
首先都是采取 委托事件 的方式来绑定事件,这种事件绑定方式一般情况下肯定性能是不咋的。然后就是自动功能了,代码写的很巧妙,充分利用jQuery的.data()这个数据缓存技术。大家自己去体会吧。
不过这刚开始差点让我产生歧义。
You can activate modals on your page easily without having to write a single line of javascript. Just set data-toggle="modal" on a controller element with a data-target="#foo" or href="#foo" which corresponds to a modal element id, and when clicked, it will launch your modal.
英文不好害死人那,如果是我们自己调用的话,那就不需要加 data-toggle="modal" data-target="#foo" or href="#foo" 这些属性了。加上它就表明是让Bootstrap自己绑定事件了。
$(document).ready(function () {
$('按钮').on('click',function () {
$('模块').modal({});
})
});