hugh 的个人博客

抽离bootstrap的modal开发knockout组件

本篇中涉及到对ko改造的部分,后续一一列出

1、找到bootstrap中modal相关代码,简单做个处理

(function (factory) {
  // Module systems magic dance.

if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
// CommonJS or Node: hard-coded dependency on "knockout"
factory(require("jquery"));
} else if (typeof define === "function" && define["amd"]) {
// AMD anonymous module with hard-coded dependency on "knockout"
define(["jquery"]);
} else {
// <script> tag: use the global ko object, attaching a mapping property
factory(window.jQuery);
}
})(function ($) {
'use strict';

// MODAL CLASS DEFINITION
// ======================

var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false

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.3.7'

Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150

Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
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)

if (this.isShown || e.isDefaultPrevented()) return

this.isShown = true

this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')

this.escape()
this.resize()

this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))

this.$dialog.on('mousedown.dismiss.bs.modal', function () {
  that.$element.one('mouseup.dismiss.bs.modal', function (e) {
    if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
  })
})

this.backdrop(function () {
  var transition = $.support.transition &amp;&amp; that.$element.hasClass('fade')

  if (!that.$element.parent().length) {
    that.$element.appendTo(that.$body) // don't move modals dom position
  }

  that.$element
  .show()
  .scrollTop(0)

  that.adjustDialog()

  if (transition) {
    that.$element[0].offsetWidth // force reflow
  }

  that.$element.addClass('in')

  that.enforceFocus()

  var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })

  transition ?
    that.$dialog // wait for modal to slide in
    .one('bsTransitionEnd', function () {
      that.$element.trigger('focus').trigger(e)
    })
    .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
    that.$element.trigger('focus').trigger(e)
})

}

Modal.prototype.hide = function (e) {
if (e) e.preventDefault()

e = $.Event('hide.bs.modal')

this.$element.trigger(e)

if (!this.isShown || e.isDefaultPrevented()) return

this.isShown = false

this.escape()
this.resize()

$(document).off('focusin.bs.modal')

this.$element
.removeClass('in')
.off('click.dismiss.bs.modal')
.off('mouseup.dismiss.bs.modal')

this.$dialog.off('mousedown.dismiss.bs.modal')

$.support.transition &amp;&amp; this.$element.hasClass('fade') ?
  this.$element
  .one('bsTransitionEnd', $.proxy(this.hideModal, this))
  .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
  this.hideModal()

}

Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (document !== e.target &&
this.$element[0] !== e.target &&
!this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}

Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}

Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}

Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}

Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}

Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''

if (this.isShown &amp;&amp; this.options.backdrop) {
  var doAnimate = $.support.transition &amp;&amp; animate

  this.$backdrop = $(document.createElement('div'))
  .addClass('modal-backdrop ' + animate)
  .appendTo(this.$body)

  this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
    if (this.ignoreBackdropClick) {
      this.ignoreBackdropClick = false
      return
    }
    if (e.target !== e.currentTarget) return
    this.options.backdrop == 'static'
      ? this.$element[0].focus()
      : this.hide()
  }, this))

  if (doAnimate) this.$backdrop[0].offsetWidth // force reflow

  this.$backdrop.addClass('in')

  if (!callback) return

  doAnimate ?
    this.$backdrop
    .one('bsTransitionEnd', callback)
    .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
    callback()

} else if (!this.isShown &amp;&amp; this.$backdrop) {
  this.$backdrop.removeClass('in')

  var callbackRemove = function () {
    that.removeBackdrop()
    callback &amp;&amp; callback()
  }
  $.support.transition &amp;&amp; this.$element.hasClass('fade') ?
    this.$backdrop
    .one('bsTransitionEnd', callbackRemove)
    .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
    callbackRemove()

} else if (callback) {
  callback()
}

}

// these following methods are used to handle overflowing modals

Modal.prototype.handleUpdate = function () {
this.adjustDialog()
}

Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight

this.$element.css({
  paddingLeft:  !this.bodyIsOverflowing &amp;&amp; modalIsOverflowing ? this.scrollbarWidth : '',
  paddingRight: this.bodyIsOverflowing &amp;&amp; !modalIsOverflowing ? this.scrollbarWidth : ''
})

}

Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}

Modal.prototype.checkScrollbar = function () {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}

Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}

Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', this.originalBodyPad)
}

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
// =======================

function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)

  if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
  if (typeof option == 'string') data[option](_relatedTarget)
  else if (options.show) data.show(_relatedTarget)
})

}

var old = $.fn.modal

$.fn.modal = Plugin
$.fn.modal.Constructor = Modal

// MODAL NO CONFLICT
// =================

$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}

// MODAL DATA-API
// ==============

$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())

if ($this.is('a')) e.preventDefault()

$target.one('show.bs.modal', function (showEvent) {
  if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
  $target.one('hidden.bs.modal', function () {
    $this.is(':visible') &amp;&amp; $this.trigger('focus')
  })
})
Plugin.call($target, option, this)

})

});

 

2、编写ko的组件

<template>
  <div class="modal fade" tabindex="-1" role="dialog" data-bind="css: baseCss">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header" data-slot="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" data-bind="title"></h4>
        </div>
        <div class="modal-body" data-slot="modal-body">
    &lt;/div&gt;
    &lt;div class="modal-footer" data-slot="modal-footer"&gt;
      &lt;button type="button" class="btn btn-default" data-dismiss="modal"&gt;关闭&lt;/button&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

</div>
</template>

<script>
define(["jquery","knockout","state","../modal"],function ($, ko, state) {

var Model = function (params, components) {
params = params || {};
var ele = components.element;
var isShown = false;
var thisModel = $(ele).find(".modal");
this.baseCss = params.class? params.class:"";
this.title = params.title? params.title:"";
if(params.show){
if(params.show() && !isShown){
thisModel.modal("show");
isShown = true;
}
params.show.subscribe(function (value) {
if(value && !isShown){
thisModel.modal("show");
isShown = true;
}
if(!value && isShown){
thisModel.modal("hide");
}
})
}
thisModel.on("hidden.bs.modal",function () {
isShown = false;
//重置父級的屬性
if(params.show){
params.show(false);
}
// do hide modal
if(params.onHidden && typeof params.onHidden == "function"){
params.onHidden.call(this);
}
})
}
state.pushComponent("modal", {});
return {
viewModel: Model
}
})

</script>

<style lang="less" scoped rel="stylesheet/less" type="text/css">

@import "../assets/style/common.less";

@zindex-modal: 1050;
@modal-inner-padding: 15px;

//** Padding applied to the modal title
@modal-title-padding: 15px;
//** Modal title line-height
@modal-title-line-height: @grey-4;

//** Background color of modal content area
@modal-content-bg: #fff;
//** Modal content border color
@modal-content-border-color: rgba(0,0,0,.2);
//** Modal content border color for IE8
@modal-content-fallback-border-color: #999;

//** Modal header border color
@modal-header-border-color: #e5e5e5;
//** Modal footer border color
@modal-footer-border-color: @grey-4;
@border-radius-large: 4px;

@modal-lg: 900px;
@modal-md: 600px;
@modal-sm: 300px;
//
// Modals
// --------------------------------------------------

// .modal-open - body class for killing the scroll
// .modal - container to scroll within
// .modal-dialog - positioning shell for the actual modal
// .modal-content - actual modal w/ bg and corners and shit

// Kill the scroll on the body
.modal-open {
overflow: hidden;
}

// Container that the modal scrolls within
.modal {
display: none;
overflow: hidden;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: @zindex-modal;
-webkit-overflow-scrolling: touch;

// Prevent Chrome on Windows from adding a focus outline. For details, see
// https://github.com/twbs/bootstrap/pull/10951.
outline: 0;

// When fading in the modal, animate it to slide down
&amp;.fade .modal-dialog {
  -webkit-transition: -webkit-transform .3s ease-out;
  -o-transition:      -o-transform .3s ease-out;
  transition:         transform .3s ease-out;
  -webkit-transform: translate3d(0, -25%, 0);
  -o-transform: translate3d(0, -25%, 0);
  transform: translate3d(0, -25%, 0);
}
&amp;.in .modal-dialog {  -webkit-transform: translate3d(0, 0, 0);
  -o-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0); }

}
.modal-open .modal {
overflow-x: hidden;
overflow-y: auto;
}

// Shell div to position the modal with bottom padding
.modal-dialog {
position: relative;
width: @modal-md;
margin: 30px auto;
}

// Actual modal
.modal-content {
position: relative;
background-color: @modal-content-bg;
border: 1px solid @modal-content-fallback-border-color; //old browsers fallback (ie8 etc)
border: 1px solid @modal-content-border-color;
border-radius: @border-radius-large;
.box-shadow(0 3px 9px rgba(0,0,0,.5));
background-clip: padding-box;
// Remove focus outline from opened modal
outline: 0;
}

// Modal header
// Top section of the modal w/ title and dismiss
.modal-header {
padding: @modal-title-padding;
border-bottom: 1px solid @modal-header-border-color;
&:extend(.clearfix all);
}
// Close icon
.modal-header .close {
margin-top: -2px;
}

// Title text within header
.modal-title {
margin: 0;
line-height: @modal-title-line-height;
}

// Modal body
// Where all modal content resides (sibling of .modal-header and .modal-footer)
.modal-body {
position: relative;
padding: @modal-inner-padding;
}

// Footer (for actions)
.modal-footer {
padding: @modal-inner-padding;
text-align: right; // right align buttons
border-top: 1px solid @modal-footer-border-color;
&:extend(.clearfix all); // clear it in case folks use .pull-* classes on buttons

// Properly space out buttons
.btn + .btn {
  margin-left: 5px;
  margin-bottom: 0; // account for input[type="submit"] which gets the bottom margin like all other inputs
}
// but override that for button groups
.btn-group .btn + .btn {
  margin-left: -1px;
}
// and override it for block buttons as well
.btn-block + .btn-block {
  margin-left: 0;
}

}

// Measure scrollbar width for padding body during modal show/hide
.modal-scrollbar-measure {
position: absolute;
top: -9999px;
width: 50px;
height: 50px;
overflow: scroll;
}

</style>
<style lang="less" rel="stylesheet/less" type="text/css">
@import "../assets/style/common.less";
@zindex-modal-background: 1040;
//** Modal backdrop background color
@modal-backdrop-bg: #000;
//** Modal backdrop opacity
@modal-backdrop-opacity: .5;
// Modal background
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: @zindex-modal-background;
background-color: @modal-backdrop-bg;
// Fade for backdrop
&.fade { .opacity(0); }
&.in { .opacity(@modal-backdrop-opacity); }
}

</style>



3、调用

<modal params="show: model.show, class: model.baseCss">
    <div name ="modal-header" class="modal-header">
      <h3>title</h3>
    </div>
    <div name ="modal-body" class="modal-body" >
      <h3>title</h3>
    </div>
  </modal>

标题:抽离bootstrap的modal开发knockout组件
作者:hugh0524
地址:https://blog.uproject.cn/articles/2017/11/29/1511958644531.html