1

我有一个表,它通过数据绑定填充来自可观察对象(人)数组的数据。当我单击表格的某个单元格时,行的索引和单元格的索引被写入变量“self.currentLine”和“self.currentCell”,而输入出现在上面,宽度为 100%,高度为 100%,覆盖了数据与自身。是否有可能仅使用字段索引而不是使用字段名称来访问可观察数组中某些对象的某些字段?(例如,不是 self.persons[0]'name',而是 self.persons[0][0])

这是一个代码(JS):

function person(fullname, age, sex, married)
{
    this.name = ko.observable(fullname); //string, only observable field, while i'm trying to get this working properly.
    this.age = age;                      //Data
    this.sex = sex;                      //string
    this.married = married;              //bool
};

function personViewModel()
{
    var self = this;
    self.currentLine = ko.observable();
    self.currentCell = ko.observable();
    self.columnNames = ko.observableArray([
                'Name',
                'Age',
                'Sex',
                'Married'
    ]);

    self.persons = ko.observableArray([...]);

    };
    self.setLine = function(index)
    {
        self.currentLine(index);
    };
    self.setCell= function(cellIndex)
    {
        self.currentCell(cellIndex);
    };
};
ko.applyBindings(new personViewModel());

我使用的 HTML 代码:

<table>
        <thead data-bind="template: { name: 'tableHeader', data: columnNames }" />
        <tbody data-bind="template: { name: 'tableContent', foreach: persons }" />
    </table>

    <script id="tableHeader" type="text/html">
        <tr data-bind="foreach: $data">
                <td data-bind="text: $data,
                               css: { 'active': $root.currentItem() == $data }">
                </td>
        </tr>
    </script>

    <script id="tableContent" type="text/html">
        <tr data-bind="click: $root.setLine.bind($data, $index())">
            <td data-bind="click: $root.setCell.bind($data, $element.cellIndex)">
                <span data-bind="text: name"></span>
                <input type="text" data-bind="visible: $root.currentCell() == 0 && $index() == $root.currentLine(),
                                              value: name"/> <!--fixed-->
            </td>
        </tr>
    </script>

在 html 中,我根据在表格中单击的单元格设置输入可见。所以现在我需要将一个单元格的值传递给输入,所以我可以编辑这些数据。

更新:像往常一样,我忘记在输入中的 value: name() 后面加上圆括号 '()'。但是第二个问题来了。据我所知,当输入失去焦点时,必须自动更改值。但是我的没变...

4

1 回答 1

3

使用输入value绑定来传递单元格的值:

AFAIK,没有办法访问具有假定索引的字段,要从 observableArray 中的对象读取字段,您可以使用以下语法 : persons()[index].fieldName(),因为该字段也是可观察的。

希望它有所帮助。

于 2013-04-17T12:15:19.530 回答