1

I'm using rails 3.2 with knockout.js and ko.mapping. I'm able to map from my json data and create my viewModel from that, in js console I can view the tree of data fine. In my view I'm using form_for with fields for to render my view. What I can't figure out is how to do a data-binding on my inputs inside the fields_for without having to use KO foreach or with. The structure of my json looks like this.

{
  "ss_sections": [
    {
      "ss_lines": [
        {
          "ss_line_cells": [
            {
              "cell_name": "credits",
              "cell_value": "124795.00",
            },
          ]
        }
      ]
    }
  ]
}

How would I go about writing out my data-bind attribute on my input to directly point to the cell_value without using knockout.js looping since my fields_for is already looping through my elements?

4

1 回答 1

2

The data-bind attributes still need to navigate the object hierarchy generated by ko mapping from the data, so I don't think you can get away without generating something like the following messy html on the server (fiddle: http://jsfiddle.net/NAUeV/1/):

<table id="ss_section0">
    <tr id="ss_line0">
        <td id="cell0">
            <span data-bind="text:ss_sections()[0].ss_lines()[0].ss_line_cells()[0].cell_name"></span>
        </td>
        <td id="cell1">
            <span data-bind="text:ss_sections()[0].ss_lines()[0].ss_line_cells()[1].cell_name"></span>
        </td>        
    </tr>
    <tr id="ss_line1">
        <td id="cell0">
            <span data-bind="text:ss_sections()[0].ss_lines()[1].ss_line_cells()[0].cell_name"></span>
        </td>
        <td id="cell1">
            <span data-bind="text:ss_sections()[0].ss_lines()[1].ss_line_cells()[1].cell_name"></span>
        </td>        
    </tr>    
</table>

It looks pretty uniform and easy to generate though.

Are you sure you need to generate the html on the server? Why not just send the json to the client and use standard foreach/with to generate on the client?

于 2013-11-06T19:28:03.797 回答