Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show twitter bootstrap modal dialog automatically with knockout

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">&times;</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.

like image 944
Goran Obradovic Avatar asked Feb 04 '13 09:02

Goran Obradovic


1 Answers

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">&times;</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>
like image 147
Goran Obradovic Avatar answered Oct 07 '22 12:10

Goran Obradovic