你能帮忙解决这个错误吗?我花了很多时间,但没有进展。谢谢!
错误:
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
预期行为:
该程序应列出id为" catNames" 的div中的cat名称,并更新ID为" cat" 的div strong>使用" data" 可观察数组中第一只猫的信息。接下来,当您从名称列表中单击不同的猫名称时,它应该将" currentCat" 的值设置为单击的猫,而后者应该更新div id " cat" 。
以下是我的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>
答案 0 :(得分:1)
问题实际上是click
内的foreach
绑定。它应该是:
<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
绑定的错误。