我有真正的问题理解为什么这个简单的测试会引发运行时错误。
我有一个淘汰计算属性'Level'作为我的FilterClause对象的一部分,我已经按照文档的说法,但它仍然会引发运行时错误......
JavaScript runtime error: Object doesn't support property or method 'Level'
我认为它与在声明计算属性函数的构造时未实例化的对象有关。但它接下来,或者至少似乎遵循了淘汰文件。
困惑!!
这是我的代码:
var FilterClause = function (json, parent) {
this.FilterClauseID = ko.observable();
this.Type = ko.observable();
this.Left = ko.observable();
this.Right = ko.observable();
this.ParentID = ko.observable();
this.Parent = ko.observable(parent);
this.Children = ko.observableArray();
this.Level = ko.observable(0);
// computed
this.Padding = ko.computed(function () {
return this.Level().ToString() + "px";
});
var mapping = {
'Children': {
create: function (args) {
return new FilterClause(args.data, this);
}
},
'ignore': ["Parent"]
};
ko.mapping.fromJS(json, mapping, this);
}
答案 0 :(得分:2)
你有计算中的上下文问题。有两种方法可以修复错误。首先是将此作为第二个参数添加到计算中:
this.Padding = ko.computed(function () {
return this.Level().ToString() + "px";
}, this);
工作小提琴:http://jsfiddle.net/bajGm/1/
或者第二 - 将其分配给变量:
var self = this;
self.FilterClauseID = ko.observable();
self.Type = ko.observable();
self.Left = ko.observable();
self.Right = ko.observable();
self.ParentID = ko.observable();
self.Parent = ko.observable(parent);
self.Children = ko.observableArray();
self.Level = ko.observable(0);
// computed
self.Padding = ko.computed(function () {
return self.Level().toString() + "px";
})
工作小提琴:http://jsfiddle.net/bajGm/3/
仔细阅读本文http://knockoutjs.com/documentation/computedObservables.html。它详细解释了您的问题的根本原因。
答案 1 :(得分:1)
在计算的填充中,这指的是窗口。
为避免这种情况,您应该创建一个自私字段:
var self = this;
self.FilterClauseID = ko.observable();
self.Type = ko.observable();
self.Left = ko.observable();
self.Right = ko.observable();
self.ParentID = ko.observable();
self.Parent = ko.observable(parent);
self.Children = ko.observableArray();
self.Level = ko.observable(0);
// computed
this.Padding = ko.computed(function () {
return self.Level().toString() + "px";
});