这是我的淘汰模型的简化示例。我遇到的问题是,只要页面加载,就会加载测验。为什么它会立即运行,我怎么能阻止它,以便它只在我想要的时候运行,比如点击按钮?
我是否甚至需要使用subscribe
来执行此操作?
HTML:
<h1>Test</h1>
<button class="btn btn-primary" data-bind="click: quizCount(quizCount() + 1)">
Click Me
</button>
<hr />
<div data-bind="visible: !loaded()">No Quiz</div>
<div data-bind="visible: loaded">Quiz Loaded!</div>
<hr />
<h3>Debug</h3>
<div data-bind="text: ko.toJSON(quizModel)"></div>
使用Javascript:
<script type="text/javascript">
var quizModel = { };
// DOM ready.
$(function () {
function QuizViewModel() {
var self = this;
self.loaded = ko.observable(false);
self.questions = ko.observable();
self.quizCount = ko.observable();
};
quizModel = new QuizViewModel();
quizModel.quizCount.subscribe(function (newCount) {
$.getJSON('@Url.Action("GetNew", "api/quiz")', function (data) {
quizModel.questions(data.Questions);
}).complete(function () {
quizModel.loaded(true);
});
});
ko.applyBindings(quizModel);
})
</script>
答案 0 :(得分:1)
订阅仅用于监听observable中的更改,因此只要observable获取值,它就会立即运行。
您需要将此函数作为方法添加到viewmodel中,可能称为getQuestions:
function QuizViewModel() {
var self = this;
self.loaded = ko.observable(false);
self.questions = ko.observable();
self.quizCount = ko.observable();
self.getQuestions = function(){
$.getJSON('@Url.Action("GetNew", "api/quiz")', function (data) {
self.questions(data.Questions);
}).complete(function () {
self.loaded(true);
});
}
};
然后你可以轻松地点击一个按钮或某种与此方法相关的东西:
<button data-bind="click: getQuestions">Get questions</button>