Knockout.js:未在JSON源中反映的标签元素的更新

时间:2012-10-01 09:54:01

标签: javascript knockout.js

我是淘汰赛的新手.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元素的新值没有反映在JSON集合中。如何在单击保存按钮时使用更新的跨度值更新JSON源?

1 个答案:

答案 0 :(得分: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: ""
        }));
    };
    ...
};