Knockout pureComputed错误绑定

时间:2017-03-08 10:34:41

标签: javascript knockout.js

我有这段代码:

var AddressModel = function (list) {
    var self = this;

    self.selectedItem = ko.observable(null);

    self.list = ko.observableArray(ko.utils.arrayMap(list, function (item) {
        return {
            firstName: item.firstName,
            lastName: item.lastName,
            address: item.address
        };
    }));

    self.Test = ko.pureComputed(function () {
        var firstname = self.selectedItem().firstName;
    }
};

ko.applyBindings(new AddressModel(initialData));

当我运行代码时,在Test函数中我收到此错误:

  

Uncaught TypeError:无法处理绑定“value:function(){return ViewModelToJSON}”   消息:无法读取未定义的属性“firstName”。

但是如果我在测试中放置self.selectedItem(),我会得到所有项目的属性,但我只想要firstName。

InitialData是一个简单的json:

var initialData = [
    {
        firstName: "Jimmy",
        lastName: "Jimbo",
        address: "111 Jimmy's Street, Jimtown"
    },
    {
        firstName: "Don",
        lastName: "Mob boss",
        address: "222 Mafia Street, Jimtown"
    }
];

有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

当你定义一个计算器时,它会运行一次内部函数来获得它的初始值并计算依赖性。

这意味着您的计算值必须能够在定义时正确评估

在您的情况下,会发生这种情况:

self.selectedItem = ko.observable(null);
self.Test = ko.pureComputed(function () {
  var firstname = /* self.selectedItem() */ null.firstName;
}

这会引发错误:



var selection = null;
try {
  selection.firstName
} catch (err) {
  console.log(err.message);
}




您可以通过检查是否有选择来解决它:

self.selectedItem = ko.observable(null);
self.Test = ko.pureComputed(function () {
  var firstname = (self.selectedItem() || {}).firstName
}