更新ObservableArray - Knockout.js

时间:2014-07-06 21:55:31

标签: knockout.js

http://jsfiddle.net/kcFpS/5/

每一行都有一个'编辑'按钮。单击此按钮,

  1. 它应填充表格下方各个文本框中的行值。例如:' productName'将填写txtName等

  2. 编辑文本框中的文本将反映表格中的更改。

  3. 但是对了。代码不起作用:

    <td>
       <button data-bind="click: $parent.editProduct">Edit</button>
    </td>
    
    function Product(Name,Qty) {
                pname = ko.observable(Name);
                qty = ko.observable(Qty);
            }
    
            var ViewModel = function () {
                var self = this;
                self.products = ko.observableArray([{ pname: 'Mobile', qty: 5 },
                                                { pname: 'Car', qty: 1}]);
    
                self.SelectedItem = ko.observable(new Product());                
    
                self.editProduct = function (item) {
                    self.SelectedItem(item);
                };
    };  
    
            ko.applyBindings(new ViewModel());
    

1 个答案:

答案 0 :(得分:1)

如果我正确理解你的问题。您需要实现编辑数据数组。我为你勾画了一个例子:

var ViewModel = function() {
var $scope = this;

$scope.array = ko.observableArray([]);
$scope.array.push({ name: ko.observable('Ben'), lastName: ko.observable('Afleck'), editMode: ko.observable(false) });
$scope.array.push({ name: ko.observable('Tom'), lastName: ko.observable('Cruse'), editMode: ko.observable(false) });

$scope.toggleEdit = function(data) {
if (data.editMode()) {
data.editMode(false);
console.log(data.name());
console.log(data.lastName());
}
else
data.editMode(true);
};
return $scope;
};
var vm = new ViewModel();
ko.applyBindings(vm);

http://jsfiddle.net/9X3er