从淘汰赛中关闭Bootstrap的模式

时间:2019-11-08 07:29:02

标签: javascript jquery knockout.js bootstrap-4 modal-dialog

我编写了一个函数(基于我在Internet上找到的其他函数),该函数可帮助显示动态生成的模式,而无需在页面的HTML中创建模式。

为简化代码分析,请简要介绍:

  • 我向Knockout添加了新的绑定处理程序,以允许在特定元素上禁用绑定
  • 模态是使用Mustache从模板生成的
  • 小胡子填写模态的相关部分(标题,正文,按钮)
  • 模态包装在div中,它将停止数据绑定(modalWrapper
  • ...以便我可以使用ko.applyBindings
  • 将自定义viewmodel应用于模式
  • 按钮会根据描述自动生成,例如:

    {
        label: "OK",
        cssClass: "default",
        handler: "handleClick", // sets data-bind="click: handleClick"
        autoClose: true // adds data-dismiss="modal"
    }
    

代码的相关部分如下:

ko.bindingHandlers.stopBinding = {
    init: function () {
        return { controlsDescendantBindings: true };
    }
};

var modalTemplate = '<div class="modal fade">\
    <div class="modal-dialog {{size}}">\
        <div class="modal-content">\
            <div class="modal-header">\
                <h5 class="modal-title">{{title}}</h5>\
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>\
            </div>\
            <div class="modal-body">{{&body}}</div>\
            <div class="modal-footer">{{&buttons}}</div>\
        </div>\
    </div>\
</div>';

/**
 * Displays modal on the screen.
 * @param {Object} options Options
 * @param {string} options.title Title of the modal
 * @param {html} options.body Body of the modal
 * @param {string} options.size Size of the modal. Can be small, default, large or xlarge.
 * @param {Object} options.actions Describes buttons to display on the modal. For each, specify label, cssClass, handler and optionally autoClose.
 */
var showModal = function(options) {

    options = options || {};

    options = $.extend({
        title: '',
        body: '',
        size: false,
        actions: false,
        viewModel: {}
    }, options);

    var modalClass = {
        small: "modal-sm",
        default: "",
        large: "modal-lg",
        xlarge: "modal-xl"
    };

    var modalWrapper = $('<div data-bind="stopBinding: true"></div>').appendTo('body');

    var buttons;
    if (options.actions === false) {

        buttons = '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
    } else {

        buttons = "";

        for (var i = 0, len = options.actions.length; i < len; i++) {

            var currentButton = $.extend({

                label: '&lt;No label&gt;',
                cssClass: 'default',
                handler: '',
                autoClose: true
            }, options.actions[i]);

            var btn = '<button type="button" class="btn ' +
                options.actions[i].cssClass +
                '" data-bind="click: ' +
                options.actions[i].handler +
                (options.actions[i].autoClose === true ? '" data-dismiss="modal"' : '')
                + '>'
                + options.actions[i].label
                + '</button>';

            buttons += btn;
        }
    }

    var templateData = {

        title: options.title,
        body: options.body,
        size: modalClass[options.size],
        buttons: buttons
    };

    var modalHtml = Mustache.render(modalTemplate, templateData);

    var $modal = $(modalHtml).appendTo(modalWrapper);

    $modal.on('hidden.bs.modal', function (e) {

        modalWrapper.remove();
    });

    ko.applyBindings(options.viewModel, $modal.get()[0]);

    $modal.modal(options);
};

此自动关闭功能存在问题。如果启用,则视图模型将处理click,模态将由Bootstrap机制关闭,然后在隐藏后从DOM中删除。

但是当我希望按钮不自动关闭时,我无法从viewmodel中关闭模式。我想到的解决方案是为viewmodel注入一种方法,例如:

viewmodel['close'] = function() { $modal.modal('hide'); };

但是,这似乎是一个棘手的解决方案(即使对于Javascript也是如此)。同样,我可以将$modal本身注入到视图模型中,但这将更加难看。

那么从模态的视图模型中关闭模态的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

我通过将(自动生成) id分配给模式div标记来解决了类似的要求。

var modalId = ('modal' + Math.random()).replace('.', '');
var modalTemplate = '<div class="modal fade" id="' + modalId + '">'\ // remaining code here

然后,将id传递给viewmodel,从而允许它通过来关闭相应的模态

$('#' + _self.modalId).modal('hide'); 

'hidden.bs.modal'的类似事件订阅处理清除。

答案 1 :(得分:0)

我将创建一个自定义的Knockout绑定,以处理模式的可见性。 该绑定将绑定的模态元素连接到提供的可观察模型。现在,模型中的点击处理程序只需管理此可观察项即可控制模式可见性。

例如,您可以在您的modalTemplate变量中使用此绑定:var modalTemplate = `<div class="modal fade" data-bind="bootstrapModalVisible: yourObservable">\ ...

在您的情况下,我尚未合并该绑定,但是以下是此绑定的工作示例。

  • modalVisible observable初始化为true,因此模态立即显示
  • 关闭按钮通过将observable设置为false,立即隐藏模态
  • 右上角的关闭按钮由于data-dismiss="modal"而关闭了模式。绑定的init中的事件处理程序将确保将正确的状态写入观察对象。
  • “保存”按钮仅在确认后才关闭模态,表明有可能推迟关闭模态

ko.bindingHandlers['bootstrapModalVisible'] = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
      $(element).on('hidden.bs.modal', function () { valueAccessor()(false); })
      $(element).on('shown.bs.modal', function () { valueAccessor()(true); })
    },
    update: function (element, valueAccessor) {
      if (ko.unwrap(valueAccessor())) {
          $(element).modal('show');
      } else {
          $(element).modal('hide');
      }
    }
};

function Test() {
  var self = this;
  self.modalVisible = ko.observable(true);
  self.showModal = function() {
    self.modalVisible(true);
  };
  self.hideModal = function() {
    self.modalVisible(false);
  };
  self.save = function() {
    if (window.confirm('Close modal?')) {
      self.modalVisible(false);
    }
  }
}

ko.applyBindings(new Test());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<button type="button" class="btn btn-primary" data-bind="click: showModal">
  Launch demo modal
</button>

<div class="modal fade" data-bind="bootstrapModalVisible: modalVisible">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Example modal</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bind="click: hideModal">Close</button>
        <button type="button" class="btn btn-primary" data-bind="click: save">Save changes</button>
      </div>
    </div>
  </div>
</div>