以下是html和JS代码
HTML正文。
<h2 data-bind="text: currentCat().name" id="cat-name"></h2>
<div data-bind="text: currentCat().clickCount" id="cat-count"></div>
<img src="" data-bind="click: incrementCount(), attr: {src: currentCat().imgSrc}" id="cat-img" alt="cute cat">
<h4>NickNames</h4>
<ul data-bind="foreach: currentCat().nickNames">
<li data-bind="text: name"></li>
</ul>
</div>
<script src="js/lib/knockout-3.2.0.js"></script>
<script src="js/app.js"></script>
JS代码
var ViewModel = function() {
this.currentCat = ko.observable( new Cat() );
console.log(this.currentCat().clickCount())
this.incrementCount = function(){
this.currentCat().clickCount(this.currentCat().clickCount() + 1);
};
}
var Cat = function() {
this.clickCount = ko.observable(0);
this.name = ko.observable('Tabby');
this.imgSrc = ko.observable('tabby.jpg');
this.imgAttribution = ko.observable('XXXX');
this.nickNames = ko.observableArray(
[
{name: 'Tabtab'},
{name: 'T-bone'},
{name: 'Mr. T'},
{name: 'Tabitha Tab Tabby'}
]
);
}
ko.applyBindings(new ViewModel())
但是,在渲染HTML页面时,点击次数为1而不是预期值0.我错过了什么吗?
答案 0 :(得分:3)
click
binding需要函数引用,而不是要运行的表达式。初始化绑定时,您提供的表达式会立即运行。您需要更改绑定以提供函数本身:
data-bind="click: incrementCount"