I'm using the knockout mapping plugin to map an object from my server.
I want to resend this object, therefore, I need in the end, to convert this object into string. I use the knockout function ko.toJSON in a computed function so that a hidden field can take this value.
Here's a jsFiddle: http://jsfiddle.net/etiennenoel/4EXSy/13/
Here's my view model
function appViewModel() {
var self = this;
self.playersEvaluation = ko.observableArray();
self.exportToJSON = ko.computed(function() {
return ko.toJSON(self.playersEvaluation)
}, this);
}
var viewModel = new appViewModel();
var dataContent = [{
playerId: 2,
playerName: "allo",
evaluatedExercises: [{
id: 1,
evaluationExerciseId: 1,
numberOfTries: 6,
tries: [{
id: 0,
number: 0,
result: 0
}, {
id: 0,
number: 0,
result: 0
}]
}]
}, {
playerId: 2,
playerName: "allo",
evaluatedExercises: [{
id: 1,
evaluationExerciseId: 1,
numberOfTries: 6,
tries: [{
id: 0,
number: 0,
result: 0
}, {
id: 0,
number: 0,
result: 0
}]
}]
}]
viewModel.playersEvaluation = ko.mapping.fromJS(dataContent);
ko.applyBindings(viewModel)
Here's what I do in html:
<input type="hidden" name="a" data-bind="value: exportToJSON()" />
<pre data-bind="text: exportToJSON()">
</pre>
Why is it only showing an empty string and not the content of self.playersEvaluation in JSON format ?