我正在学习 Knockout.js 并使用 with:binding
更改绑定(bind)上下文,如下所示:
HTML:
<div id="wrap" data-bind="with: currentCat()">
<h2 data-bind="text: name"></h2>
<h3 data-bind="text: level"></h3>
<div data-bind="text: count"></div>
<img src="" alt="cute cat" data-bind="click: $parent.incrementCounter, attr: {src: imgSrc}">
</div>
Javascript:
var cat = function() {
this.name = ko.observable("Fossie");
this.imgSrc = ko.observable("--");
this.count = ko.observable(0);
this.nicknames = ko.observableArray(["Meow", "Johnny"]);
};
var viewModel = function() {
this.currentCat = ko.observable(new cat());
this.incrementCounter = function() {
this.currentCat().count(this.currentCat().count() + 1);
}
};
ko.applyBindings(new viewModel());
当我单击图像时,出现此错误:
未捕获类型错误:this.currentCat 不是函数
相同的代码在不使用 with
绑定(bind)的情况下也能工作。谁能解释一下我改变上下文后发生了什么变化?
最佳答案
this
在用作事件处理程序时会丢失其上下文。使用.bind
this.incrementCounter = function() {
this.currentCat().count(this.currentCat().count() + 1);
}.bind(this);
关于javascript - knockout : XXX is not a function error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35527957/