2017-10-06 72 views
0

您能否帮助解决此错误?我花了很多时间,但没有进展。谢谢!!Knockout不会更新可观察对象的视图

错误:

VM4705 knockout-debug.js:3326 Uncaught ReferenceError: Unable to process binding "with: function(){return currentCat }" 
Message: Unable to process binding "text: function(){return clickCount }" 
Message: clickCount is not defined 

预期的行为:

该计划应列出在div猫名ID为“catNames”和更新具有ID的DIV “猫“与第一只猫的信息从”数据“可观察数组。接下来,当您从名称列表中单击不同的猫名称时,它应该将值“currentCat”设置为单击的猫,然后应该更新ID为“猫”的div。

Link to JsFiddle

下面是我的JS代码:

var cats = [ 
    {name:'cat1', photo: 'https://s20.postimg.org/owgnoq5c9/cat_1.jpg', clicks: 0 }, 
    {name:'cat2', photo: 'https://s20.postimg.org/f9d5f0ccp/cat_2.jpg', clicks: 0 }, 
    {name:'cat3', photo: 'https://s20.postimg.org/su3xe4s5l/cat_3.jpg', clicks: 0 }, 
    {name:'cat4', photo: 'https://s20.postimg.org/xdg5zna15/cat_4.jpg', clicks: 0 }, 
    {name:'cat5', photo: 'https://s20.postimg.org/78yuqivex/cat_5.jpg', clicks: 0 } 
]; 

function CatRecord(cat){ 
    var self = this; 
    self.catName = ko.observable(cat.name); 
    self.imgSrc = ko.observable(cat.photo); 
    self.clickCount= ko.observable(cat.clicks); 
    }; 


var ViewModel = function(){ 
    var self = this; 
    self.data = ko.observableArray([]); 

    // data 
    cats.forEach(function(cat){ 
     self.data.push(new CatRecord(cat)); 
    }); // -- end of for Each 

    // view 
    self.currentCat = ko.observable(self.data()[0]); 

    self.setCurrentCat = function(catIndex){ 
    self.currentCat(self.data()[catIndex]); 
    }; 

    // actions 
    self.incrementClicks = function(){ 
    var clickCount = self.currentCat().clickCount(); 
    self.currentCat().clickCount(clickCount + 1); 
    }; 
}; 


ko.applyBindings(new ViewModel()); 

和HTML:

<body> 

    <div id="catNames"> 
     <ul id="catList" data-bind="foreach: data"> 
     <li data-bind="text: catName, click:$parents[0].currentCat($index()) "></li> 
     </ul> 
    </div> 

    <div id="cat" data-bind="with: currentCat"> 
     <h2 id="clicks" data-bind="text: clickCount"></h2> 
     <img id="photo" src="" alt="cat photo" data-bind=" click: $parent.incrementClicks, 
     attr: {src: imgSrc}"> 

     <h4 id="name" data-bind="text: catName"></h4> 
     <button type="submit">Admin</button> 
    </div> 

    </body> 

回答

1

的问题实际上是与clickforeach结合。它应该是:

<ul id="catList" data-bind="foreach: data"> 
    <li data-bind="text: catName, click:$parent.setCurrentCat"></li> 
</ul> 

setCurrentCat的第一个参数是cat对象触发事件。所以你不需要index。你可以简单地这样做:

self.setCurrentCat = function(cat){ 
    self.currentCat(cat); 
}; 

我仍然不知道为什么你得到错误with结合。

Updated fiddle

+0

它修好了,非常感谢! 所以,来自“foreach”的“猫”对象隐式传递给“setCurrentCat”? – rstreet

+0

@rstreet yes([documentation](http://knockoutjs.com/documentation/click-binding.html#note-1-passing-a-current-item-as-a-parameter-to-your-handler-function ))。 [您也可以使用其他参数调用函数](http://knockoutjs.com/documentation/click-binding.html#note-2-accessing-the-event-object-or-passing-more-parameters) – adiga

相关问题