bootstrap modal
by rniemeyer
HTML
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<div class="modal fade hide" data-bind="modal: selected">
<div class="modal-header">
<button class="close" data-dismiss="modal">x</button>
<h3>Edit Record</h3>
</div>
<div class="modal-body">
<input data-bind="value: name" />
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal">Close</a>
</div>
</div>
<ul data-bind="foreach: missions">
<li>
<a href="#" data-bind="text: name, click: $parent.selected"></a>
</li>
</ul>
JavaScript
ko.bindingHandlers.modal = {
init: function(element, valueAccessor) {
var data = valueAccessor();
//make sure that we clear the observable no matter how the modal is closed
$(element).modal({ show: false }).on("hidden", function() {
if (ko.isWriteableObservable(data)) {
data(null);
}
});
//wrap the real "with" binding
return ko.bindingHandlers["with"].init.apply(this, arguments);
},
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");
//wrap the real "with" binding
return ko.bindingHandlers["with"].update.apply(this, arguments);
}
};
ko.applyBindings({
selected: ko.observable(),
missions: [
{ name: ko.observable("one")},
{ name: ko.observable("two")},
{ name: ko.observable("three")}
]
});