0
votes

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 ?

2

2 Answers

2
votes

You are replacing the value of playersEvaluation and hence the computed with this use of equals:

viewModel.playersEvaluation = ko.mapping.fromJS(dataContent);

Needs to be this:

viewModel.playersEvaluation(ko.mapping.fromJS(dataContent));

in order to set, not replace, the observableArray.

Updated fiddle: http://jsfiddle.net/dV5GM/1/

0
votes

The text bindings on input and pre are not correct , it should just be the observalbale's name without brackets '()', also since playersEvaluation is already observable , you should assign the value in knockout way which is

 viewModel.playersEvaluation(ko.mapping.fromJS(dataContent));  

<input type="hidden" name="a" data-bind="value: exportToJSON" />
<pre data-bind="text: exportToJSON">

</pre> 

here is the updated jsfiddle: http://jsfiddle.net/4EXSy/15/