开发者

Template for a single dimension array with Knockout.js and ko.mapping

I have a JSON string that I am mapping with ko.mapping plugin and I need to create observable bindings for one of the mapped arrays. The array is in the JSON as [1,2,3,4,5] so it has no index.

I have the following code working to a certain point:

<script id="statRowTemplate" type="text/html">
    {{if type() != "column"}}
    <tr>
            <td><label>Name: </label><input data-bind="value: name" /></td>
            <td><label>Plot Points: </label><ul data-bind="template: {name: 'dataTemplate' , foreach: data}"></ul> </td>
    </tr>
    {{/if}}
</script>
<script type="text/html" id="dataTemplate">         
<li>
    <p>${this.data}</p>
        <input data-bind="value: this.data" />
</li>
</script>
<button data-bind="click: saveChanges">Save Changes</button>

So everything is working as expected except <input data-bind="value: this.data" /> That field remains blank ... ${this.data} Shows the correct value however.

Overall, I am tying to update a JSON string and re-save it in a flat file. I can bind the data array: [1,2,3,4] directly to the input value but then it does not update as an array.

Here is the viewModel: var viewModel = {};

$.getJSON('/data-forecast-accuracy.json', function(result) {

    viewModel.stats = ko.mapping.fromJS(result);
    console.log(result)
    viewModel.saveChanges = function() {

        var unmapped = ko.mapping.toJSON(viewModel.stats);
        console.log(unmapped);

        $.post('save-changes.php', {data: unmapped})
        .success(function() { console.log("second success"); })
        .error(function() {  console.log("error"); })
        .complete(function() {  console.log("complete"); });
    }

    ko.applyBindings(viewModel);
});

Here is the JSON:

[ 开发者_运维百科 { "type":"spline", "marker":{ "symbol":"diamond" }, "name":"Cumulative", "data":[10,17,18,18,16,17,18,19] }, { "type":"spline", "marker":{ "symbol":"circle" }, "name":"Monthly", "data":[10,22,20,19,8,20,25,23] } ]

Any help would be greatly appreciated. Also open to suggestions if I am approaching this from the wrong angle. Ultimately just want to be able to modify the JSON sting through a UI and then save it.

Thanks in advance.


To properly edit a value in the array, you will want to map the original array to a structure that contains an actual property to bind against [1,2,3] becomes [{val: 1}, {val: 2}, {val: 3}]. Binding against $data will not work, as KO is not able to determine how to update it from user input (currently not able to understand that it is located at some index in an array).

I like to do something like: http://jsfiddle.net/rniemeyer/vv2Wx/

This uses this technique to make the array look like the original automatically when it is turned into JSON.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜