Skip to content

Instantly share code, notes, and snippets.

@jkreitzman
Last active January 3, 2020 01:20
Show Gist options
  • Save jkreitzman/cc042a148333fefe15c98af47966c0a6 to your computer and use it in GitHub Desktop.
Save jkreitzman/cc042a148333fefe15c98af47966c0a6 to your computer and use it in GitHub Desktop.
Knockout Binding for Bootstrap's Modal (Typescript)
// A knockout binding for Bootstrap's modal dialog.
// This binding allows a modal to be shown based on the value of a bound property.
// To consume in a webpacked view model:
// import(/* webpackMode: "eager" */ "./knockout-bs-modal.ts"); // eager ensures the module is included.
import(/* webpackMode: "eager" */ "bootstrap");
import $ = require("jquery");
import ko = require("knockout");
ko.bindingHandlers.modal = {
init(element: HTMLElement, valueAccessor: () => ko.Observable, allBindings: any, viewModel: never, bindingContext: ko.BindingContext) {
if (!ko.isObservable(valueAccessor())) {
throw new Error("This binding only works with an observable.");
}
},
update(element: HTMLElement, valueAccessor: () => ko.Observable, allBindings: any, viewModel: never, bindingContext: ko.BindingContext) {
if (!ko.unwrap(valueAccessor())) {
$(element).modal("hide");
} else {
$(element).modal("show");
}
}
};
<!-- Sample of how to implement this binding -->
<!-- "someBoundProperty" should exist on your view model and be an observable. That property becomes the context for the modal-->
<div data-bind="using: someBoundProperty, modal: someBoundProperty" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Confirm</h5>
<button type="button" data-bind="click: $root.cancel.bind($root)" class="close">
<span>x</span>
</button>
</div>
<div class="modal-body">
<p>Are you sure? This is not reversible.</p>
</div>
<div class="modal-footer">
<button type="button" data-bind="click: $root.cancel.bind($root)" class="btn btn-secondary">Cancel</button>
<button type="button" data-bind="click: $root.doIt.bind($root)" class="btn btn-danger">Do it</button>
</div>
</div>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment