我有一个嵌套 View 模型设置,由于必须有实例,因此需要将其表示为函数(除非我遗漏了某些内容)。一切都在 UI 中运行,我可以嵌套具有嵌套 View 模型的 View 模型等等。
但是在当前形式下我收到错误
JavaScript runtime error: Pass a function that returns the value of the ko.computed
当尝试调用ko.toJSON(x);
时。
当我定义虚拟机而不需要实例时,这有效,但我的嵌套并没有因此改变。
以下是当前情况的示例。
var CityViewModel = function() {
var self = this;
self.Name = ko.observable("");
self.ATMs = ko.observableArray();
self.AddATM = function () {
self.ATMs.push(new ATMViewModel);
}
self.GetJson = function() {
alert(ko.toJSON(self)); //Area of interest
}
}
var ATMViewModel = function() {
var self = this;
self.PostCode = ko.observable("");
self.Features = ko.observableArray();
self.AddFeature = function () {
self.Features.push(new FeaturesViewModel());
}
}
var FeaturesViewModel = function () {
var self = this;
self.Name = ko.observable("");
self.Reference = ko.observable("");
}
ko.applyBindings(CityViewModel);
最佳答案
我也花了一段时间才发现它......缺少 new
关键字
ko.applyBindings(new CityViewModel());
// ====
作为 fiddle :http://jsfiddle.net/Quango/zf0dLLyr/
我推荐 Ryan 的调试建议:
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
事实上没有返回任何内容给了我提示。看 http://www.knockmeout.net/2013/06/knockout-debugging-strategies-plugin.html
关于javascript - 基于函数的 View 模型未转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28238155/