我正在使用twitter bootstrap v3.0和knockout.js v2.3.0。
当我点击addAnswer按钮并从answerOption1读取值时,它会返回如下方法:
function c(){if(0<arguments.length)return c.equalityComparer&&c.equalityComparer(d,arguments[0])||(c.K(),d=arguments[0],c.J()),this;a.q.bb(c);return d}
而不是实际文本avlue:“我是一个答案文本”。
来源:
function Question(data) {
this.title = data.title;
this.question = data.question;
}
function Answer(data) {
this.type = data.type;
this.inputText = ko.observable(data.inputText);
this.correctAnswer = ko.observable(data.correctAnswer);
this.explanation = ko.observable(data.explanation);
this.isCorrect = ko.observable(data.isCorrect);
}
var AnswerType = {
MULTI_CHOICE : "multichoice",
YES_NO : "yesno",
INPUT_TEXT : "inputtext"
}
function QuestionViewModel() {
var self = this;
self.title = ko.observable("my title");
self.question = ko.observable("my question");
self.currentAnswerType = AnswerType.MULTI_CHOICE;
self.currentAnswer = ko.observable("add new answer..");
self.currentExplanation = ko.observable("");
self.isCorrect = ko.observable("");
/* Answers operations */
self.multipleAnswers = ko.observableArray([]);
self.addAnswer = function(){
if(self.currentAnswerType == AnswerType.MULTI_CHOICE){
self.multipleAnswers.push(new Answer({type : this.currentAnswerType, inputText: this.currentAnswer, correctAnswer : '', explanation: this.currentExplanation, isCorrect: this.isCorrect}));
}else if(self.currentAnswerType == AnswerType.YES_NO){
}else{
}
}
/* Question operations */
self.questions = ko.observableArray([]);
self.addQuestion = function() {
self.questions.push(new Question({
title : this.title(),
question : this.question()
}))
}
}
<div class="panel-body">
<div class="form-group">
<label class="col-lg-2 control-label" for="answerOption1">Add
new answer</label>
<div class="col-lg-8">
<input type="text" class="form-control" id="answerOption1" data-bind="value: currentAnswer">
<button type="submit" class="btn btn-primary"
data-bind="click: addAnswer">Add</button>
</div>
<div class="col-lg-1 text-center">
<input type="checkbox" class="form-control" id="answerOption1">
</div>
<div class="col-lg-1 text-center">
<span class="glyphicon glyphicon-edit"></span>
</div>
</div>
</div>
答案 0 :(得分:2)
observables是函数,当你在javascript代码中使用它们时,你需要使用它们来获取它们的返回值。
self.multipleAnswers.push(new Answer({type : this.currentAnswerType, inputText: this.currentAnswer, correctAnswer : '', explanation: this.currentExplanation, isCorrect: this.isCorrect}));
应该是
self.multipleAnswers.push(new Answer({type : this.currentAnswerType, inputText: this.currentAnswer(), correctAnswer : '', explanation: this.currentExplanation(), isCorrect: this.isCorrect()}));