简体   繁体   中英

updating an item in a knockout bound list

I have a list of questions and each question has a list of answers and I am using knockout to display each question 1 at a time. What I am doing is setting up my model with the full list and then making a currentQuestion property observable and after each question is answered, I increment this to the next question. Problem is that I have to change some data on the question when the user hovers it but cant figure out how to make the answers observable.

I've put together a jsfiddle and what I want to do is change the answer text to 'modified' when the user clicks the answer.

How do I make the AnswerText observable so that when the click handler changes its value this is reflected in the UI.

Any ideas where I am going wrong would be appreciated.

jsfiddle code if below:

<div class="top">
  <div data-bind="foreach: currentQuestion().Answers">
    <div data-bind="click: $root.answerClicked">
      <div data-bind="text: AnswerText"></div>
    </div>
  </div>
</div>


function MyVM() {
  var self = this;

  this.session = {
    Questions: [
      {
        QuestionText: "Q1",
        Answers: [
          {
            AnswerText: "Q1A1"
          },
          {
            AnswerText: "Q1A2"
          }
        ]
      },
      {
        QuestionText: "Q2",
        Answers: [
          {
            AnswerText: "Q2A1"
          },
          {
            AnswerText: "Q2A2"
          }
        ]
      }
        ]
  };

  this.currentQuestion = ko.observable();
  this.currentQuestion(self.session.Questions[1]);

  this.answerClicked = function (selectedAnswer, event) {
    alert('hello');
    selectedAnswer.AnswerText = 'modified1';
    selectedAnswer.AnswerText('modified');
  };
}

var model = new MyVM();
ko.applyBindings(model);

Currently you're binding the UI to a static string. In order to make the UI reflect changes the string must be wrapped in an observable as you stated so it sounds like you were on the right track. All you need to do is use an observable in each answer object.

    Answers: [
      {
        AnswerText: ko.observable("Q2A1")
      },
      {
        AnswerText: ko.observable("Q2A2")
      }
    ]

Then in the click function you'll want to get rid of the first assignment operator where it would be replacing the observable and use only the second line where a value is assigned to the observable instead.

  this.answerClicked = function (selectedAnswer, event) {
    alert('hello');
    //selectedAnswer.AnswerText = 'modified1';
    selectedAnswer.AnswerText('modified');
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM