0

我是 knockout.JS 的新手。我将一个 JSON 集合绑定到一个表。

<tbody data-bind="foreach: Collection">
            <tr>
                <td>
                    <span data-bind="text: FirstName" ></span>
                </td>
                <td>
                    <span data-bind="text: LastName" ></span> 
                </td>
                <td>
                    <input type="button" data-bind="click: function(){ obj.RemoveItem($data) }" value="Del" />
                </td>
                <td>
                    <input type="button" data-bind="click: function(){ obj.SaveItems($data.Id) }" value="Edit/Save" />
                </td>
            </tr>
        </tbody>

function viewModel(collection) {
            var self = this;
            this.Collection = ko.observableArray(collection);
            this.AddItem = function() {
                this.Collection.push({FirstName:"", LastName:""});
            };
            this.RemoveItem = function(data) {
                this.Collection.remove(data);
            };
            this.SaveItems = function(id) {
                alert("New Collection: " + ko.utils.stringifyJson(self.Collection));
            }
        };

        var obj = new viewModel([
            { Id: 1,FirstName: "John", LastName: "Saleth" },
            { Id: 2, FirstName: "John", LastName: "Kennedy" }
        ]);

        ko.applyBindings(obj);

在每一行中,我保留了一个编辑按钮,单击该按钮会在所有 TD 中插入一个文本框,其值为 span。在保存单击时,我正在使用文本框的值更新 span 元素的值。

问题是 span 元素的新值没有反映在 JSON 集合中。如何在单击保存按钮时使用更新的跨度值更新 JSON 源?

4

1 回答 1

0

您还应该使 Collection 数组的每个属性都可观察。

function ItemModel(item) {
    this.Id = ko.observable(item.Id);       
    this.FirstName = ko.observable(item.FirstName);
    this.LastName = ko.observable(item.LastName);     
};


function viewModel(collection) {
    var self = this;
    this.Collection = ko.observableArray();
    ko.utils.arrayForEach(collection, function (i) { self.Collection.push(new ItemModel(i));  });
    this.AddItem = function() {
        this.Collection.push(new ItemModel({
            FirstName: "",
            LastName: ""
        }));
    };
    ...
};
于 2012-10-01T10:22:23.410 回答