Skip to content

Instantly share code, notes, and snippets.

@dmr
Created July 31, 2013 09:17
Show Gist options
  • Save dmr/6120628 to your computer and use it in GitHub Desktop.
Save dmr/6120628 to your computer and use it in GitHub Desktop.
I have an improved version of http://stackoverflow.com/a/16160300/2630724 to share. All you need in addition to this is one element for the modal <div class="modal fade" data-bind="modal: currentModal"> </div> somewhere on your page and then you open a dialog by writing to the currentModal observable and you close the dialog by nulling it: curre…
ko.bindingHandlers.modal = {
init: function(element, valueAccessor, allBindings, vm, context) {
var modal = valueAccessor();
//init the modal and make sure that we clear the observable no matter how the modal is closed
$(element).modal({show: false}).on("hidden.bs.modal", function() {
if (ko.isWriteableObservable(modal)) {
modal(null);
}
});
var template_computed = ko.computed({
read: function() {
var value = modal();
return value ? value : {'if': false};
},
disposeWhenNodeIsRemoved: element
});
//apply the template binding to this element
return ko.applyBindingsToNode(element, { template: template_computed }, context);
},
update: function(element, valueAccessor) {
var data = ko.utils.unwrapObservable(valueAccessor());
//show or hide the modal depending on whether the associated data is populated
$(element).modal(data ? "show" : "hide");
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment