jquery ui dialog + knockoutjs
Having a problem getting the dialog to show; dialog retains 'display: none' property despite call to 'open'
HTML
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css">
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<h1 class="header" data-bind="text: label"></h1>
<label>
dialog's title:
<input type="text" data-bind="value: mytitle" />
</label>
<div id="dialog" data-bind="dialog: {'autoOpen': false, 'title': mytitle }, dialogVisible: isOpen">
Some content
<button data-bind="click: close">Close</button>
</div>
<div>
<button data-bind="click: open">Open</button>
<button data-bind="click: close" >Close</button>
</div>
<hr/>
<div data-bind="text: ko.toJSON($root)"></div>
CSS
.header {
font-size: 16px;
font-family: sans-serif;
font-weight: bold;
margin-bottom: 20px;
}
JavaScript
ko.bindingHandlers.dialog = {
init: function(element, valueAccessor, allBindingsAccessor) {
var options = ko.utils.unwrapObservable(valueAccessor()) || {};
//do in a setTimeout, so the applyBindings doesn't bind twice from element being copied and moved to bottom
setTimeout(function() {
options.close = function() {
allBindingsAccessor().dialogVisible(false);
};
$(element).dialog(ko.toJS(options));
}, 0);
//handle disposal (not strictly necessary in this scenario)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).dialog("destroy");
});
},
update: function(element, valueAccessor, allBindingsAccessor) {
var shouldBeOpen = ko.utils.unwrapObservable(allBindingsAccessor().dialogVisible),
$el = $(element),
dialog = $el.data("uiDialog") || $el.data("dialog"),
options = valueAccessor();
//don't call dialog methods before initilization
if (dialog) {
$el.dialog(shouldBeOpen ? "open" : "close");
for (var key in options) {
if (ko.isObservable(options[key])) {
$el.dialog("option", key, options[key]());
}
}
}
}
};
var viewModel = {
label: ko.observable('dialog test'),
isOpen: ko.observable(false),
open: function() {
this.isOpen(true);
},
close: function() {
this.isOpen(false);
},
mytitle: ko.observable("Default title")
};
ko.applyBindings(viewModel);