通过索引从observableArray获取对象

MrJ*_*rJM 6 knockout.js

我正在用Knockoutjs设计一个测验.我想一次只显示一个问题.我正在考虑一个全局计数var,每次回答问题时都会加1.但是,我似乎无法找到一种方法来获得当时只有一个问题.我怎么能最好地接近这个?我是Knockoutjs的新手.我尝试了问题()[编号],但似乎没有用.

谢谢

JS

$(document).ready(function(){
function Answer(data) {
    this.answer = ko.observable(data.answer);
    this.correct = ko.observable(data.correct);
}

function Question(data){
    this.id = ko.observable(data.id);
    this.question = ko.observable(data.question);
    this.answers = ko.observableArray([]);
    var mappedAnswers = $.map(data.answers, function(item) {return new Answer(item) });
    this.answers(mappedAnswers);
}


function AnswerViewModel(){
    // Data
    var self = this;

    self.questions =  ko.observableArray([]);

    self.checkAnswer = function(item, event){
            if (item.juist() == true){
               $(event.currentTarget).css("background", "green");

            }else{
                $(event.currentTarget).css("background", "red");
            }
    }

    $.getJSON("../res/json/quiz.json", function(allData) {
        var mappedQuestions = $.map(allData.questions, function(item) {return new Question(item) });
        self.questions(mappedQuestions);
    });
}

ko.applyBindings(AnswerViewModel());
});
Run Code Online (Sandbox Code Playgroud)

HTML

<h3 data-bind="questions()[1].question"></h3>
<ul class="list-container"  data-bind="foreach: questions()[1].answers">
    <li class="list-item">
         <a class="list-item-content" href="#" data-bind="text: answer, click:checkAnswer"></a>
    </li>
</ul>
<button>Next question</button>
Run Code Online (Sandbox Code Playgroud)

JSON

{
"questions" :
[
    {
        "id": 1,
        "question": "This is the first question",
        "answers" :
        [
            {"answer": "q1a1", "correct": false},
            {"answer": "q1a2", "correct": false} ,
            {"answer": "q1a3", "correct": true},
            {"answer": "q1a4", "correct": false}
        ]
    },
    {
        "id": 2,
       "question": "This is the 2nd question",
        "answers" :
        [
            {"answer": "q2a1", "correct": false},
            {"answer": "q2a2", "correct": false} ,
            {"answer": "q2a3", "correct": false},
            {"answer": "q2a4", "correct": true}
        ]
    }
]
Run Code Online (Sandbox Code Playgroud)

}

jjp*_*aga 8

Jsfiddle很有趣所以我不能在那里发布代码,但它很简单:你几乎就在那里!这是一个小推动.

首先,除非必要,否则调用标记中的方法并不是一个好的做法,并且为函数提供参数可能意味着您可以使用observable.在这种情况下:

<div data-bind="foreach: filteredQuestions">
<ul class="list-container"  data-bind="foreach: answers">
    <li class="list-item">
         <a class="list-item-content" href="#" data-bind="text: answer"></a>
    </li>

</ul>
<button data-bind="click: $parent.nextQuestion">Next question</button>
</div>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,在标记中我只是放置变量,而不是在表单中调用它filteredQuestions.到现在为止,你可能会问:"这个foreach有什么用?我只想展示一个问题,而不是所有问题.过滤后的东西是什么?"

这就是我正在做的事情:我没有显示原始问题数组,而是显示一个已过滤的数组,每当其中的任何可观察数据发生变化时,都会更新.这是filteredQuestions的代码.

self.currentQuestionId = ko.observable("1");
self.filteredQuestions = ko.computed(function() {
    var currentQuestion = self.currentQuestionId();
    return ko.utils.arrayFilter(self.question(), function(question) {
        return question.id() == currentQuestion;
    });
});
Run Code Online (Sandbox Code Playgroud)

如果你注意代码,我只返回一个只有一个问题的数组,其中Id与currentQuestionId变量设置的数组相同.这是一种方法,虽然有很多种:其他好的方法有一个可观察的,叫做selectedQuestion哪个价值是第一个问题; 然后在标记中使用数据绑定with:selectedQuestion.但是,让我们坚持这一个,你能猜出它$parent.nextQuestion做了什么?

self.nextQuestion = function() {
    var currentQuestionId = self.currentQuestionId();
    self.currentQuestionId(currentQuestionId + 1);
}
Run Code Online (Sandbox Code Playgroud)

首先,我们使用$parent关键字来浏览实际范围的父级,因为我们question因为foreach语句而在子级中.这个功能因你的要求而起作用,但可能存在一些陷阱(我们在最后一个问题中做了什么?如果id没有在数字上增加怎么办?).那时另一种方法可能更有用,在这种情况下,你会有这样的东西:

self.nextQuestion = function(question) {
    var index = self.questions().indexOf(question);
    self.selectedQuestion(self.questions()[index + 1]);
}
Run Code Online (Sandbox Code Playgroud)

最后一种方法的美丽?好吧,backQuestion很容易!

self.backQuestion = function(question) {
    var index = self.questions().indexOf(question);
    self.selectedQuestion(self.questions()[index - 1]);
}
Run Code Online (Sandbox Code Playgroud)

(您显然需要检查IndexOutOfBounds类型错误).在最后一种方法中,不要忘记,因为我们在上下文切换元素中foreach,我们接收当前问题作为参数.希望这可以帮助.