Knockout.groupedOptions: non-conventional
HTML
<script src="https://rawgithub.com/Supertext/knockout.groupedOptions/master/knockout-groupedOptions.min.js"></script>
<select data-bind="groupedOptions: { groups: { coll: Groups, label: 'DisplayText', options: { coll: 'Items', text: 'Display', value: 'Val' } }, value: SelectedOption }"></select>
<span data-bind="visible: SelectedOption(), text: SelectedText"></span>
JavaScript
// this is the data for our view-model, and which we'll render inside the <select> element
var demoGroups = [{
"Label": "group 1",
"Options": [{
"Text": "item 1 - 1",
"Value": "1-1"
},
{
"Text": "item 1 - 2",
"Value": "1-2"
},
{
"Text": "item 1 - 3",
"Value": "1-3"
}]
},
{
"Label": "group 2",
"Options": [{
"Text": "item 2 - 1",
"Value": "2-1"
},
{
"Text": "item 2 - 2",
"Value": "2-2"
},
{
"Text": "item 2 - 3",
"Value": "2-3"
}]
}];
var vmMain_NonConventional = function(groups) {
var self = this;
// This is the outermost collection which is bound to the <select> element.
// This must always be stated in the 'data-bind' declaration.
self.Groups = ko.observableArray();
// This property holds the selected item from the options list
self.SelectedOption = ko.observable();
self.SelectedText = ko.computed(function() {
if (self.SelectedOption()) {
return "You selected \"" + self.SelectedOption().Display() + "\"";
}
return "";
});
if (typeof(groups) !== "undefined" && groups) {
for (var i = 0, iMax = groups.length; i < iMax; i++) {
self.Groups.push(new vmGroup_NonConventional(groups[i]));
}
}
}
// a view-model to represent an <optgroup> element
var vmGroup_NonConventional = function(group) {
var self = this;
// This is the text which appears inside each <optgroup> element, using the
// element's 'label' attribute.
// This property DOES NOT use the conventional name and must consequently be
// stated in the 'data-bind' declaration.
self.DisplayText = ko.observable();
// This is the collection which represents the <option> elements for the context
// <optgroup>.
// This property DOES NOT use the conventional name and must...