2017-12-06 3 views
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の私が何かを逃したのですか?

答えて

3

click bindingは、実行する式ではなく関数参照を必要とします。あなたが提供した式は、バインディングが初期化されたときすぐに実行されます。機能を提供するためにバインディングを変更する必要があります:

data-bind="click: incrementCount" 
+0

incrementCount()は初期化中に実行されます.. !! – aman

関連する問題