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。
下面是我的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>
它修好了,非常感謝! 所以,來自「foreach」的「貓」對象隱式傳遞給「setCurrentCat」? – rstreet
@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