Bootstrap的Model原始碼詳細註釋 (轉)

風靈使發表於2018-12-31
/* ========================================================================
 * Bootstrap: modal.js v3.2.0
 * http://getbootstrap.com/javascript/#modals
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */
 
//這裡的 +function($){}(jQuery) 和 (function($){})(jQuery) 一個意思
+function($) {
    'use strict';
 
    // MODAL CLASS DEFINITION
    // ======================
 
    var Modal = function(element, options) {
        this.options = options
        this.$body = $(document.body)
        this.$element = $(element)
        this.$backdrop = this.isShown = null
        this.scrollbarWidth = 0
 
        // 如果是遠端內容,就載入,並觸發loaded.bs.modal事件
        if (this.options.remote) {
            this.$element.find('.modal-content').load(this.options.remote,
                $.proxy(function() {
                    this.$element.trigger('loaded.bs.modal')
                }, this))
        }
    }
 
    Modal.VERSION = '3.2.0'
     
    // 預設配置
    Modal.DEFAULTS = {
        backdrop : true, // 預設配置,要背景div(單擊觸發hide方法)
        keyboard : true, // 要desc鍵按了就消失的功能
        show : true // 模態框初始化之後就立即顯示出來
    }
 
    // 如果是顯示的狀態,就隱藏,如果是未顯示,則顯示
    Modal.prototype.toggle = function(_relatedTarget) {
        return this.isShown ? this.hide() : this.show(_relatedTarget)
    }
 
    // 顯示彈出框方法
    Modal.prototype.show = function(_relatedTarget) {
        var that = this
        var e = $.Event('show.bs.modal', {relatedTarget : _relatedTarget})
 
        this.$element.trigger(e)// 觸發show.bs.modal事件
 
        // 如果已經顯示了, 或者上面事件回撥中呼叫了e.preventDefault 就 直接不處理,直接返回
        if (this.isShown || e.isDefaultPrevented()) return
         
        //改變顯示狀態為顯示中
        this.isShown = true
     
        //有滾動條的話,就設定滾動條的寬度
        this.checkScrollbar()
        //overflow:hidden
        this.$body.addClass('modal-open')
        //padding-right 屬性在原來的基礎上 + 上面算出來的滾動條的寬度
        this.setScrollbar()
         
        //如果options.keyboard配置為true則監聽keyup.dismiss.bs.modal事件, 功能就是按esc鍵,就呼叫hide方法
        this.escape()
     
        //為包含data-dismiss="modal"屬性的元素註冊關閉處理器(比如點x按鈕,就隱藏模態框功能)
        this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
     
        //backdrop函式:背景邏輯, 回撥函式功能:顯示model邏輯
        this.backdrop(function () {
            // 瀏覽器是否支援動畫 & model的元素包含fade class
            var transition = $.support.transition && that.$element.hasClass('fade')
 
            // 沒有父元素(例:還未append的$("<div></div>")),則將model附加到body上,
            if (!that.$element.parent().length) {
                that.$element.appendTo(that.$body) // don't move modals dom position
            }
             
            // 將model元素設定成顯示(jq.show方法), 並移動到最上面
            that.$element.show().scrollTop(0)
     
            //動畫效果準備
            if (transition) {
                that.$element[0].offsetWidth // force reflow
            }
     
            //設定不透明opacity:1, 設定顯示(aria,給不方便人士用的)aria-hidden:false
            that.$element.addClass('in').attr('aria-hidden', false);
             
            //解綁併為document物件註冊focusin.bs.modal事件, 具體處理是:如果不是model產生的,就觸發model的facus事件
            //簡單的說,就是聚焦,哈哈,看著我,看著我
            that.enforceFocus()
             
            //準備觸發shown.bs.modal事件
            var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
             
            //有動畫,就動畫完成後觸發focus事件和shown.bs.modal事件
            transition ?
            that.$element.find('.modal-dialog') // wait for modal to slide in
                .one('bsTransitionEnd', function () {
                    that.$element.trigger('focus').trigger(e)
                })
                .emulateTransitionEnd(300) :
                that.$element.trigger('focus').trigger(e)
        })
    }
 
    //隱藏model方法
    Modal.prototype.hide = function(e) {
        if (e) e.preventDefault() //不清楚作用場景
         
        //準備觸發隱藏事件, 並觸發
        e = $.Event('hide.bs.modal')
        this.$element.trigger(e)
         
        //如果model狀態以及為未顯示 或者上面事件回撥函式中呼叫了preventDefault, 就不處理
        if (!this.isShown || e.isDefaultPrevented()) return
         
        //設定狀態為不顯示
        this.isShown = false
         
        //去掉顯示時加上的class, 具體就是overflow:hidden
        this.$body.removeClass('modal-open')
         
        //還原padding-right屬性 設定為'' (對應show中的setScrollbar) 
        this.resetScrollbar()
         
        ////解除keyup.dismiss.bs.modal, 與show方法裡的對應
        this.escape()
         
        //解除document物件的focusin.bs.modal事件繫結, (對應show中enforceFocus)
        $(document).off('focusin.bs.modal')
         
        //移除不透明設定(in), 設定為隱藏, 移除關閉處理器(比如點x按鈕,就隱藏模態框功能)
        this.$element.removeClass('in').attr('aria-hidden', true).off('click.dismiss.bs.modal')
         
        //動畫,然後呼叫hideModal方法(加上背景div的關聯處理)
        $.support.transition && this.$element.hasClass('fade') ? this.$element
            .one('bsTransitionEnd', $.proxy(this.hideModal, this))
            .emulateTransitionEnd(300) : this.hideModal()
    }
     
    //解綁併為document物件註冊focusin.bs.modal事件, 具體處理是:如果不是model產生的,就觸發model的facus事件
    Modal.prototype.enforceFocus = function () {
        $(document).off('focusin.bs.modal') // guard against infinite focus loop
            .on('focusin.bs.modal', $.proxy(function (e) {
                if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
                    this.$element.trigger('focus')
                }
            }, this))
    }
     
    //實現按下esc鍵時,隱藏model功能,(根據配置)
    Modal.prototype.escape = function () {
        if (this.isShown && this.options.keyboard) {
            this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) {
                e.which == 27 && this.hide()
            }, this))
        } else if (!this.isShown) {
            this.$element.off('keyup.dismiss.bs.modal')
        }
    }
     
    //隱藏關聯方法,隱藏元素,並處理背景div,並觸發隱藏完成事件
    Modal.prototype.hideModal = function () {
        var that = this
        //隱藏model自身(jq.hide)
        this.$element.hide()
        //隱藏背景邏輯
        this.backdrop(function () {
            //觸發隱藏完成事件
            that.$element.trigger('hidden.bs.modal')
        })
    }
     
    //移除背景div
    Modal.prototype.removeBackdrop = function () {
        this.$backdrop && this.$backdrop.remove()
        this.$backdrop = null
    }
     
    //callback為具體的model的隱藏或顯示邏輯,backdrop負責背景div邏輯
    Modal.prototype.backdrop = function (callback) {
        var that = this
     
        //是否包含fade樣式(動畫)
        var animate = this.$element.hasClass('fade') ? 'fade' : ''
 
        //如果為顯示中 且 要背景div
        if (this.isShown && this.options.backdrop) {
            var doAnimate = $.support.transition && animate
 
            //新增背景div
            this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />').appendTo(this.$body)
 
            //繫結click.dismiss.bs.modal事件, 
            this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
                //冒泡來的事件不管,不過一般model都在最外面,so,這裡一般不會返回false;
                if (e.target !== e.currentTarget) return
 
                //如果backdrop配置引數為static, 則獲取焦點,否則,呼叫隱藏方法
                this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this)
            }, this))
 
            //準備動畫
            if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
     
            //設定背景div半透明opacity:0.5
            this.$backdrop.addClass('in')
     
            if (!callback) return
     
            //啊,背景div有動畫就動畫後回撥,沒有直接回撥, 回撥是指(顯示或關閉邏輯)
            doAnimate ? this.$backdrop.one('bsTransitionEnd', callback).emulateTransitionEnd(150) : callback()
         
        } else if (!this.isShown && this.$backdrop) {//狀態為未顯示,且要背景div
            //去掉半透明效果
            this.$backdrop.removeClass('in')
 
            //回撥函式: 移除遮罩div後回撥
            var callbackRemove = function () {
                that.removeBackdrop()
                callback && callback()
            }
             
            //啊,能動畫,就動畫後回撥上面的函式
            $.support.transition && this.$element.hasClass('fade') ?
                this.$backdrop.one('bsTransitionEnd', callbackRemove)
                .emulateTransitionEnd(150) : callbackRemove()
 
        } else if (callback) {//顯示但是不要背景div,且回撥不為空,這裡回撥是顯示model邏輯
            callback()
        }
    }
     
    //檢查是否有滾動條,並計算滾動條寬度(猜的-.-!)
    Modal.prototype.checkScrollbar = function() {
        if (document.body.clientWidth >= window.innerWidth) return
        this.scrollbarWidth = this.scrollbarWidth || this.measureScrollbar()
    }
     
    //設定又內邊距(估計和滾動條有關)
    Modal.prototype.setScrollbar = function() {
        var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
        if (this.scrollbarWidth) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
    }
     
    //還原上面內邊距設定
    Modal.prototype.resetScrollbar = function() {
        this.$body.css('padding-right', '')
    }
     
    //猜測是計算滾動條寬度的一種方法
    Modal.prototype.measureScrollbar = function() { // thx walsh
        var scrollDiv = document.createElement('div')
        scrollDiv.className = 'modal-scrollbar-measure'
        this.$body.append(scrollDiv)
        var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
        this.$body[0].removeChild(scrollDiv)
        return scrollbarWidth
    }
 
 
    // MODAL PLUGIN DEFINITION
    // =======================
     
    //對model的包裝,支援批量操作,快取,配置合併,方法呼叫,
    //option:model配置,   _relatedTarget:show.bs.modal和shown.bs.modal事件的關聯relatedTarget
    function Plugin(option, _relatedTarget) {
        return this.each(function () {
            var $this   = $(this)
            //取快取model物件
            var data    = $this.data('bs.modal')//快取
            //合併配置引數
            var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
             
            //快取沒有,就new一個model
            if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
            //如果引數為字串(一般是'toggle','show','hien')
            if (typeof option == 'string') data[option](_relatedTarget)
            //如果配置為初始顯示,就顯示
            else if (options.show) data.show(_relatedTarget)
        })
    }
     
    //儲存老的model屬性,防衝突
    var old = $.fn.modal
     
    //匯出
    $.fn.modal             = Plugin
    $.fn.modal.Constructor = Modal
 
 
    // MODAL NO CONFLICT
    // =================
 
    //有衝突時,還原$.fn.modal的引用,然後返回自己
    $.fn.modal.noConflict = function () {
        $.fn.modal = old
        return this
    }
 
 
    // MODAL DATA-API
    // ==============
 
    //為保護[data-toggle="modal"]屬性的元素繫結單擊事件:click.bs.modal.data-api
    //例如<a data-toggle="modal" data-target="#model1" href="http://localhost:8080/ysdai-mobile/">連結</a>\
    //對應上面的元素,外掛就會為它繫結單擊事件,使用$('#model1')來載入href,然後顯示,我這裡碰到,多次點選會產生多層背景div的問題,等有時間找找原因
    $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
        var $this   = $(this)
        var href    = $this.attr('href')
        //通過jq獲取對應的model元素(根據當前元素data-target屬性 或 href屬性)
        var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
        //model元素有快取 ? 直接呼叫toggle方法 : 沒有就遠端獲取href內容顯示
        var option  = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
         
        //阻止a標籤瀏覽器預設行為
        if ($this.is('a')) e.preventDefault()
         
        //為model繫結show.bs.modal(顯示前)事件
        $target.one('show.bs.modal', function (showEvent) {
            //如果前面註冊的事件處理器一定呼叫了preventDefault方法,就不會顯示,後面也就不繫結隱藏事件了,所以這裡也不要處理了.
            if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
             
            //為model繫結hidden.bs.modal(隱藏後)事件, 如果當前元素可見,就觸發當前元素焦點事件
            $target.one('hidden.bs.modal', function () {
                $this.is(':visible') && $this.trigger('focus')
            })
        })
         
        //呼叫Model.toggle方法,或者建立新的model物件,並從遠處載入內容
        Plugin.call($target, option, this)
    })
     
}(jQuery);

相關文章