JSFiddle - React, Tailwind, and code Playground
by pmamode
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-debug.js"></script>
<div data-bind="text:name"></div>
<div data-bind="foreach:answers">
<label>
<span data-bind="text: name"></span>
<input type="radio" name="uniqueQuestionName" data-bind="click: $root.setCorrectAnswer" />
</label>
<br />
</div>
<hr/>
<pre data-bind="text: JSON.stringify(ko.toJS($root), null, 2)"></pre>
JavaScript
function Question() {
var self = this;
this.name = "Channel:";
var i = 0;
this.answers = ko.observableArray([
new Answer(++i, "RM-2020", false),
new Answer(++i, "RM-2000", true)
]);
this.setCorrectAnswer = function(correct) {
if (correct !== self.correctAnswer()) {
ko.utils.arrayForEach(self.answers(), function(answer) {
answer.isRight(correct === answer);
});
self.correctAnswer(correct);
}
return true;
};
this.correctAnswer = ko.observable();
this.correctAnswer.subscribe(function(newValue) {
alert("The correct answer to " + this.name + " is now " + this.correctAnswer().name());
}, this);
}
function Answer(id, name, isRight) {
this.id = ko.observable(id);
this.name = ko.observable(name);
this.isRight = ko.observable(isRight);
}
ko.applyBindings(new Question());