Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未定义淘汰变量-范围问题?_Javascript_Knockout.js - Fatal编程技术网

Javascript 未定义淘汰变量-范围问题?

Javascript 未定义淘汰变量-范围问题?,javascript,knockout.js,Javascript,Knockout.js,我有以下代码: var ObjectViewModel = function (testObject) { //debugger; var self = this; self.id = testSet.id; self.details = testOject.details; self.children = ko.observableArray(testObject.children); self.childCount = ko.computed(

我有以下代码:

var ObjectViewModel = function (testObject) {
    //debugger;
    var self = this;
    self.id = testSet.id;
    self.details = testOject.details;
    self.children = ko.observableArray(testObject.children);
    self.childCount = ko.computed(function() {
        return self.children().length;
    });

    self.addObject = function () {
        //debugger;
        // Pending UI
        // Call API here
        // On success, complete
        self.children.push(dummyObject);
        self.childToAdd("");
    }.bind(self);
    }
    / etc

但是在childCount中,此.children()未定义。我试图让视图实时显示子数组的长度,以便在用户添加/删除项时更新计数。知道这不起作用的原因吗?

您可以通过最后一个参数将执行函数时该的值传递给计算函数:

this.childCount = ko.computed(function() {
    return this.children().length;
}, this);
您还可以将对该的引用存储在计算机外部:

var self = this;
this.childCount = ko.computed(function () {
    return self.children().length;
});

谢谢安德鲁。执行此操作时,childCount始终返回0,并且在数组更改时不更新。“computed”的用法在这里看起来合适吗?@JakeP:我觉得合适——你是如何在可观察数组中添加和删除项目的?@JakeP:是self.cards还是self.children?啊,self.children-我为它重命名了一些变量simplicity@JakeP:嗯,可能需要全部查看才能知道为什么不起作用。我这里有一个简单的例子:效果很好,可能是HTML中的绑定吗?