<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.js"></script>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<p>A composite data structure. Questions have answers, answers have questions, etc.</p>
<div data-bind="foreach: questions">
<h3 data-bind="text:text"></h3>
<div data-bind="foreach:answers">
<div><input type="radio" data-bind="value:id,text:text,attr:{'id':id,'name':'q'+$parent.id},checked:$parent.selectedAnswer" /><label data-bind="attr:{'for':id},text:text"></label></div>
<!-- Here, I need to do a foreach on answer.questions and APPEND them into the childQuestionsN DIV. How can this sort of "forward looking" into the template rendering
be accomplished and in an append rather than replace fashion?-->
</div>
<div data-bind="attr:{id:'childQuestions'+id}"></div>
</div>
</body>
</html>
JavaScript
var id = 1;
function Answer(text, questions){
var self = this;
self.id = id++;
self.text=text;
self.questions=questions;
}
function Question(text,isVisible,answers){
var self = this;
self.id = id++;
self.text=text;
self.answers = answers;
self.selectedAnswer = ko.observable();
self.isVisble = ko.observable(isVisible);
var setChildQuestionVisibility = ko.computed(function () {
var selectedAnswer = this.selectedAnswer();
$.each(this.answers, function (i, answer) {
if (answer.id === selectedAnswer) {
if (answer.questions) {
$.each(answer.questions, function (i, question) { question.isVisible = true; });
}
return false;
}
});
},this);
}
function MyViewModel(questions){
var self=this;
self.questions=questions;
}
$(document).ready(function () {
var myModel = new MyViewModel([
new Question('Question1',true,[
new Answer('Answer1',[
new Question('Question3',false,[
new Answer('Answer5'),
new Answer('Answer6')
])]),
new Answer('Answer2',[
new Question('Question4',false,[
new Answer('Answer7'),
new Answer('Answer8')
])])]),
new Question('Question2',true,[
new Answer('Answer3'),
new Answer('Answer4')
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.