javascript - knockout : XXX is not a function error

标签 javascript knockout.js

我正在学习 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/

相关文章:

javascript - 仅在 IE 中使用 jQuery 发布数据时出现错误请求错误

javascript - 内联此范围 'binding'

javascript - 如何使用jquery将数据属性发送到php变量?

data-binding - 不显眼的 knockout 没有dom污染

javascript - ko 可观察对象或函数

javascript - 如何在同一输入元素中绑定(bind) value 和 keydown 事件?

javascript - 在 knockout 控制流模板中使用基于字符串的变量

Javascript 使用整月的日期差异

javascript - jQuery 以 noConflict 模式加载,即使作为函数参数传递也无法访问 $

javascript - 断断续续的 Canvas 动画 - EaselJS