Reputation: 2845
I have scenario where I have to display a list of questions to the user. I came across observable array and foreach binding in knockout. I could easily display a list of questions with them.
However, my requirement is the questions are interdependent. say for eg. if the first question has a response of "a", then question 2 must be displayed, if question 2 has a response of "b" then question 4,5 should be displayed. How can I do this with knockout js?
I am thinking about using computed field for each question and defining a visible condition based on them. But I am not able to think of a complete solution. Any suggestions would be extremely helpful. Thanks in advance
Upvotes: 1
Views: 106
Reputation: 3034
Your intuition is correct; the simplest way would be to have a computed observable that is used in a visibility binding. As a simple example, this should work:
var ANSWER = { // psuedo-enum
A : 'a',
B : 'b',
C : 'c',
NONE : null
};
var questionOne = {
text : 'foo',
answer : ko.observable(ANSWER.NONE),
shouldDisplay : true
};
var questionTwo = {
text : 'bar',
answer : ko.observable(ANSWER.NONE),
shouldDisplay : ko.computed(function(){
return questionOne.answer() === ANSWER.B;
})
};
var questionThree = {
text : 'baz',
answer : ko.observable(ANSWER.NONE),
shouldDisplay : ko.computed(function(){
return questionOne.answer() === ANSWER.B && questionTwo.answer() === ANSWER.C;
})
};
var someViewModel = {
questions : ko.observableArray([questionOne, questionTwo, questionThree]);
};
In this case, the elements are hardcoded. Doing it this way isn't very maintainable. Possibly you could devise some means of avoiding the repetition and storing the specifications for each question in a more compact manner. How you do that is outside the scope of a short Stack Overflow answer, though! I would recommend, though, that you have the questions state their dependencies rather than having early questions manage the states of other questions 'at a distance', so to speak.
I hope that's a bit of a clue.
Upvotes: 1