简体   繁体   English

JSON.stringify一个具有Knockout JS变量的对象

[英]JSON.stringify an object with Knockout JS variables

Current scenario: 目前的情况:

function Employee(data) {
var self = this;

// variables
this.Forename = ko.observable(data.Forename);
this.Surname = ko.observable(data.Surname);

this.Save = function () {
    var obj = JSON.stringify(self); // Without ko.observables, this works fine. self() doesn't work obviously.
    console.log(obj);
};
}

I think what I'm trying to do is pretty straight forward, get all the observable values without going through every single one of them, and creating a JSON string using the stringify function. 我认为我要做的是非常简单,获取所有可观察的值而不经过它们中的每一个,并使用stringify函数创建一个JSON字符串。 This is easy to do without observables, is there a simple way to do it with them? 没有可观察量这很容易做到,有没有一种简单的方法可以用它们做到?

Knockout has a built in toJSON function to do exactly this: Knockout有一个内置的toJSON函数来完成这个:

var json = ko.toJSON(viewModel);

ko.toJSON — this produces a JSON string representing your view model's data. ko.toJSON - 这会生成一个表示视图模型数据的JSON字符串。 Internally, it simply calls ko.toJS on your view model, and then uses the browser's native JSON serializer on the result. 在内部,它只是在视图模型上调用ko.toJS,然后在结果上使用浏览器的本机JSON序列化程序。 Note: for this to work on older browsers that have no native JSON serializer (eg, IE 7 or earlier), you must also reference the json2.js library. 注意:为了在没有本机JSON序列化程序的旧浏览器(例如,IE 7或更早版本)上工作,您还必须引用json2.js库。

You can do this by 2 ways : 你可以通过两种方式做到这一点:

first: 第一:

      var json = ko.toJSON(ko.mapping.toJS(viewModel))

Second 第二

      var json = JSON.stringify(ko.mapping.toJS(viewModel))

你看过淘汰映射插件了吗?

var unmapped = ko.mapping.toJS(viewModel);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM