7

Knockoutjsでクイズをデザインしています。一度に1つの質問だけを表示したい。質問に答えるたびに1ずつ加算されるグローバルカウント変数について考えていました。しかし、一度に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());
});

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>

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}
        ]
    }
]

}

4

2 に答える 2

9

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>

ご覧のとおり、マークアップでは、変数を入力するだけで、フォームで呼び出すことはありませんfilteredQuestions。今では、「そのforeachはどうなっているのですか?すべてではなく1つの質問だけを表示したいのですが、フィルタリングされたものはどうなっているのですか?」と質問しているかもしれません。

これが私がしていることです:元の質問配列を表示する代わりに、フィルターされたものを表示しています。これは、その中のオブザーバブルが変更されるたびに更新されます。これが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;
    });
});

コードに注意を払うと、質問が1つだけの配列が1つだけ返されます。この配列は、currentQuestionId変数によって設定されたものと同じです。selectedQuestionこれは1つのアプローチですが、多くのアプローチがあります。他の優れたアプローチには、どの値が最初の質問であるかという観測量があります。次に、マークアップでデータバインディングを使用しますwith:selectedQuestion。しかし、これに固執しましょう、あなたは何をするのか推測できますか$parent.nextQuestion

self.nextQuestion = function() {
    var currentQuestionId = self.currentQuestionId();
    self.currentQuestionId(currentQuestionId + 1);
}

まず、ステートメントのために$parent子にいるため、実際のスコープの親を参照するためにキーワードを使用します。この関数は要件に応じて機能しますが、いくつかの落とし穴がある可能性があります(最後の質問で何をしますか?IDが数値的に増加していない場合はどうなりますか?)。その場合、他のアプローチがより役立つ可能性があります。この場合、次のようなものになります。questionforeach

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

最後のアプローチの美しさは?さて、backQuestionはとても簡単です!

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

(明らかに、IndexOutOfBoundsタイプのエラーをチェックする必要があります)。foreachこの最後のアプローチでは、のようなコンテキスト切り替え要素内にいるため、現在の質問をパラメーターとして受け取ることを忘れないでください。お役に立てれば。

于 2013-01-05T18:41:09.777 に答える
1

これが実用的な解決策です。

コードはマッピングプラグインを使用して、ビューモデルの作成を簡素化します。
「questionIndex」および「currentQuestion」オブザーバブルは、現在の質問を追跡します。

function AnswerViewModel(){
  var self = this;
  ko.mapping.fromJS(data, {}, self);

  this.questionIndex = ko.observable(0);
  this.currentQuestion = ko.computed(function(){
     return self.questions()[self.questionIndex()];
  });

this.nextQuestion = function(){
  var questionIndex = self.questionIndex();
  if(self.questions().length - 1 > questionIndex){
    self.questionIndex(questionIndex + 1);
  }
};

this.prevQuestion = function(){
  var questionIndex = self.questionIndex();
  if(questionIndex > 0){
    self.questionIndex(questionIndex - 1);
  }
};

this.checkAnswer = function(item, event){
  $(event.currentTarget).css("background", item.correct() ? "green" : "red");
};  
}

マークアップ:

<!-- ko with: currentQuestion -->
<h3 data-bind="text: question"></h3>
<ul class="list-container" data-bind="foreach: answers">
  <li class="list-item">
     <a class="list-item-content" href="#" data-bind="text: answer, click:$root.checkAnswer"></a>
</li>
</ul>
<!-- /ko -->

ここでは、仮想要素を使用<!-- ko --> <!-- /ko -->して目的のコンテキストを紹介します。

于 2013-01-05T20:39:43.860 に答える