JSON.stringify一个具有Knockout JS变量的对象 [英] JSON.stringify an object with Knockout JS variables

查看:122
本文介绍了JSON.stringify一个具有Knockout JS变量的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前情况:

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);
};
}

我认为我想做的事情非常简单,全部可观察的值,而不经过它们中的每一个,并使用stringify函数创建一个JSON字符串。这很容易做到没有observables,有没有一个简单的方法来做它?

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. This is easy to do without observables, is there a simple way to do it with them?

推荐答案

Knockout内置< a href =http://knockoutjs.com/documentation/json-data.html> toJSON 功能就是这样做:

Knockout has a built in toJSON function to do exactly this:

var json = ko.toJSON(viewModel);




ko.toJSON - 这会产生一个表示视图模型数据的JSON字符串。在内部,它只是在视图模型上调用ko.toJS,然后在结果上使用浏览器的本机JSON序列化程序。 注意:为了能够在没有本机JSON序列化程序的旧浏览器(例如,IE 7或更早版本)上工作,您还必须引用json2.js库。

ko.toJSON — this produces a JSON string representing your view model’s data. Internally, it simply calls ko.toJS on your view model, and then uses the browser’s native JSON serializer on the result. Note: for this to work on older browsers that have no native JSON serializer (e.g., IE 7 or earlier), you must also reference the json2.js library.

这篇关于JSON.stringify一个具有Knockout JS变量的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆