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. This is easy to do without observables, is there a simple way to do it with them?
stringify() JSON stringification is the process of converting a Javascript object to a flat JSON string that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. stringify() , as the Javascript standard specifies.
prototype. loadNote = function (id) { var self = this; $. getJSON(uri + '/' + id, function (data) { self. note(data); }); }; // Apply bindings ko.
unwrap method is used to read it), the current viewModel and bindingContext. Whenever the passed value changes the binding will print updated information to console. This binding cannot be used with virtual elements (in html comments), only on real elements, since ko.
JSON.stringify() The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Knockout has a built in toJSON function to do exactly this:
var json = ko.toJSON(viewModel);
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With