Knockout Quiz
by Mark Heath
HTML
<div data-bind="html: currentQuestion().question" ></div>
<div data-bind="foreach: currentQuestion().answers">
<div data-bind="html: answer, css: { selected: selected }, click: $parent.currentQuestion().select"></div>
</div>
<button data-bind="click: prev, enable: index() > 0">Previous</button>
<button data-bind="click: next, enable: index() < questions.length -1">Next</button>
CSS
.selected {
background: yellow;
}
JavaScript
var viewModel = function() {
var self = this;
self.index = ko.observable(0);
self.questions = [
new questionViewModel("Choose a Goalkeeper", ["Szczesny", "Fabianski", "Mannone", "Martinez"]),
new questionViewModel("Choose a Rightback", ["Jenkinson", "Sagna"]),
new questionViewModel("Choose a Leftback", ["Gibbs", "Monreal", ]),
];
self.currentQuestion = ko.observable(self.questions[0]);
self.next = function() {
self.index(self.index() + 1);
self.currentQuestion(self.questions[self.index()]);
}
self.prev = function() {
self.index(self.index() - 1);
self.currentQuestion(self.questions[self.index()]);
}
return self;
};
var answerViewModel = function(answer) {
this.answer = answer;
this.selected = ko.observable(false);
return this;
};
var questionViewModel = function(question, answers) {
var self = this;
self.question = question;
self.answers = [];
for (var n = 0; n < answers.length; n++) {
self.answers.push(new answerViewModel(answers[n]));
}
self.select = function(answer) {
self.answers.forEach(function(a) { a.selected(false); });
answer.selected(true);
}
return self;
};
ko.applyBindings(new viewModel());