javascript - 基于函数的 View 模型未转换为 JSON

标签 javascript json knockout.js

我有一个嵌套 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/

相关文章:

c# - 如何在代码中写入 JSON 字符串值?

javascript - knockout js 在 ko.utils.arrayForEach 中添加/删除 css 类

javascript - Backbone - 未捕获类型错误 : Cannot call method 'unbind' of undefined

javascript - 如何在 Highcharts 中显示错误消息?

json - Flutter实时数据库onValue解析

javascript - Knockout.js 中未定义的绑定(bind)

data-binding - Knockout.js 单选按钮的 boolean 数据绑定(bind)问题

javascript - 在数字中插入破折号

javascript - 如何验证在单击按钮之前是否单击了 anchor 标记(使用 javaScript)

java - 将非标准化数据集设置为嵌套文档