How to bind a Knockout js model to a wizard style UI
http://stackoverflow.com/questions/7428677/how-to-bind-a-knockout-js-model-to-a-wizard-style-ui
by patelsan
HTML
<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<select data-bind="options: stepModels, optionsText: 'name', value: currentStep"></select>
<hr />
<div data-bind="template: { name: 'currentTmpl', data: currentStep }"></div>
<script id="currentTmpl" type="text/html">
<h2 data-bind="text: name"></h2>
<div data-bind="template: { name: getTemplate, data: model }"></div>
</script>
<script id="basicTmpl" type="text/html">
<div data-bind="text: message"></div>
</script>
<script id="choiceTmpl" type="text/html">
<input type="checkbox" data-bind="checked: choiceOne" /> Choice One <br/>
<input type="checkbox" data-bind="checked: choiceTwo" /> Choice Two
</script>
<script id="confirmTmpl" type="text/html">
<button data-bind="click: confirm">Confirm</button>
</script>
JavaScript
function Step(id, name, template, model) {
var self = this;
self.id = id;
self.name = ko.observable(name);
self.template = template;
self.model = ko.observable(model);
self.getTemplate = function() {
return self.template;
}
}
var viewModel = {
stepModels: ko.observableArray([
new Step(1, "Welcome", "basicTmpl", { message: "hello and welcome!" }),
new Step(1, "Choices", "choiceTmpl", { choiceOne: ko.observable(false), choiceTwo: ko.observable(false) }),
new Step(1, "Confirmation", "confirmTmpl", { confirm: function() { viewModel.currentStep(viewModel.stepModels()[3]); } } ),
new Step(4, "Congratulations!", "basicTmpl", { message: "you are finished!" })
]),
currentStep: ko.observable(),
getTemplate: function(data) {
return viewModel.currentStep().template();
}
};
ko.applyBindings(viewModel);