0
次はHTMLとJSのコードイメージをクリックするとknockoutJSの値が増えます
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の私が何かを逃したのですか?
incrementCount()は初期化中に実行されます.. !! – aman