2015-03-13 89 views
0

我只想顯示當前的問題選項。我已將ViewModel中的currentQuestion設置爲數組中的第一個元素。 但它是未定義的。 我安裝了淘汰賽上下文chrome插件,並且所有其他變量似乎設置正確。我不知道爲什麼currentQuestion具有未定義的值。 感謝爲什麼currentQuestion未定義?

<div id="quiz-container"> 
<form action=""> 
    <div data-bind="with: currentQuestion"> 
     <h3 data-bind="text: question"></h3> 

     <div data-bind="foreach: choices"> 

      <input type="radio" data-bind="checkedValue: $data, checked: $parent.selectedAnswer" /> 
      <span data-bind="text: $data">choice</span> 

     </div> 
     <div> 
      <button data-bind="click: $parent.previousQuestion">Previous</button> 
      <button data-bind="click: $parent.nextQuestion">Next</button> 
     </div> 
    </div> 
    <div><input type="submit"/></div> 
</form> 
</div> 
<script src="js/jQuery.js"></script> 

function Question(data) { 
var self = this; 
self.question = data.question; 
self.choices = ko.observableArray([]); 
data.choices.forEach(function (c) { 
    self.choices.push(c); 
}); 
self.answer = data.answer; 
}; 

function QuizViewModel() { 

var self = this; 

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

// Load initial state from server, convert it to Question instances, then populate self.questions 
$.getJSON("js/questions.json", function (allData) { 
    var mappedQuestions = $.map(allData, function (item) { 
     return new Question(item) 
    }); 
    self.questionList(mappedQuestions); 
}); 

self.currentQuestion = ko.observable(self.questionList()[0]); 

this.previousQuestion = function() { 
    var index = self.questionList().indexOf(self.currentQuestion); 
    self.currentQuestion(self.questionList()[index - 1]); 
}; 

this.nextQuestion = function() { 
    var index = self.questionList().indexOf(self.currentQuestion); 
    self.currentQuestion(self.questionList()[index + 1]); 
}; 

}; 

ko.applyBindings(new QuizViewModel()); 
+0

檢查self.questionList()[index-1]是否有正確的值? – 2015-03-13 11:50:29

回答

1

這是因爲它被設置在QuizViewModel被實例化的時間,而問題是異步了。相反,只需創建一個observable,並在異步調用返回時設置它:

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

    //set current question when the async call returns 
    self.currentQuestion(self.questionList()[0]); 
}); 

//initialise as observable 
self.currentQuestion = ko.observable(); 
+0

這是第一次加載的問題..但是當你下一個/上一個時,它應該工作 – 2015-03-13 11:51:38

+0

如果它沒有正確啓動 - indexOf調用總是返回-1,所以以前不會工作(至少直到你點擊下一步),但接下來會好的。無論哪種方式 - 在加載問題後需要正確初始化。您無法將其初始化爲尚未填充數組的成員。 – 2015-03-13 11:53:35

+0

感謝您的快速回復!這就說得通了。現在它被設置爲第一個問題對象。然而綁定似乎不起作用,所以沒有顯示。如果我用'questionList()[0]'替換'with:currentQuestion',它確實顯示正確。有什麼建議麼? – paul 2015-03-13 12:28:52