I need to show modal dialog for editing item in single page app when I select an item from list.
Problem: I used visible
binding, but that turned out to be cumbersome, and it does not work properly, as it shows only dialog, without overlay, and fade (if any) does not work.
Html:
<div class="modal hide fade" data-bind="visible:selectedItem, with:selectedItem">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 data-bind="text:name"></h3>
</div>
<div class="modal-body">
<form data-bind="submit:deselectItem">
<!-- editor for item here -->
</form>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-bind="click:deselectItem">Close</a>
</div>
</div>
Model for this is simple object with observableList, obervable selectedItem, and deselectItem function which sets selectedItem to null.
As I figured out, the (probably) best way to do this is to create a ko binding handler, I called it showModal
:
ko.bindingHandlers.showModal = {
init: function (element, valueAccessor) {},
update: function (element, valueAccessor) {
var value = valueAccessor();
if (ko.utils.unwrapObservable(value)) {
$(element).modal('show');
// this is to focus input field inside dialog
$("input", element).focus();
}
else {
$(element).modal('hide');
}
}
};
Usage is like this:
<div class="modal hide fade" data-bind="showModal:selectedItem, with:selectedItem">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 data-bind="text:name"></h3>
</div>
<div class="modal-body">
<form data-bind="submit:deselectItem">
<!-- editor for item here -->
</form>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-bind="click:deselectItem">Close</a>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With