【问题标题】:Accessing object fields in observable array of objects. KnockoutJS访问可观察对象数组中的对象字段。淘汰赛JS
【发布时间】:2013-04-17 21:30:57
【问题描述】:

我有一个表,它通过数据绑定填充来自可观察对象(人)数组的数据。当我单击表格的某个单元格时,行的索引和单元格的索引被写入变量“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() 后面加上圆括号 '()'。但是第二个问题来了。据我所知,当输入失去焦点时,必须自动更改值。但我的没有改变......

【问题讨论】:

    标签: javascript knockout.js ko.observablearray


    【解决方案1】:

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

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

    希望有帮助。

    【讨论】:

    • 好的,但是如果我不知道字段的名称?有没有可能通过索引或类似的东西来获得它的名字?
    • 找到答案,使用 Object.keys(persons()[index]),我有一个键数组,所以现在我可以取所需的字段名称。
    猜你喜欢
    • 2023-04-06
    • 2014-08-08
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 2013-05-30
    • 2013-05-19
    • 1970-01-01
    相关资源
    最近更新 更多