Skip to content

Instantly share code, notes, and snippets.

@jessejjohnson
Forked from zjlgdx/dialog.js
Last active October 28, 2015 00:56
Show Gist options
  • Save jessejjohnson/f46c6d9508bc6f7ae4d4 to your computer and use it in GitHub Desktop.
Save jessejjohnson/f46c6d9508bc6f7ae4d4 to your computer and use it in GitHub Desktop.
Knockout Modal Binding
ko.bindingHandlers.dialog = {
init: function(element, valueAccessor, allBindingsAccessor) {
var options = ko.utils.unwrapObservable(valueAccessor()) || {};
options.close = function() {
allBindingsAccessor().dialogVisible(false);
};
$(element).dialog(options);
//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);
$(element).dialog(shouldBeOpen ? "open" : "close");
}
};
var Item = function(title) {
this.title = ko.observable(title);
this.isOpen = ko.observable(false);
};
Item.prototype = {
open: function() { this.isOpen(true); },
close: function() { this.isOpen(false); }
};
var viewModel = {
items: [
new Item("one"),
new Item("two"),
new Item("three")
]
};
ko.applyBindings(viewModel, document.getElementById('app'));
<div id="app">
<ul data-bind="foreach: items">
<li>
<a href="#" data-bind="text: title, click: open"></a>
<div id="dialog" data-bind="dialog: {autoOpen: false, title: 'testing' }, dialogVisible: isOpen">
<input data-bind="value: title" />
<a href="#" data-bind="click: close">close</a>
</div>
</li>
</ul>
<hr/>
<div data-bind="text: ko.toJSON($root)"></div>
</div>​
.header {
font-size: 16px;
font-family: sans-serif;
font-weight: bold;
margin-bottom: 20px;
}​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment