如何从knockout.js中的可观察数组访问可观察元素并更改其值

时间:2015-03-23 10:16:12

标签: javascript jquery html knockout.js

我正在创建一个ViewModel:

function PurchaseOrderViewModel() {
    var self = this;
    self.seqNo = ko.observable(1);
    self.barcode = ko.observable('');
    self.expDate = ko.observable('');
    self.importDate = ko.observable('');
    self.name = ko.observable('');
}

在条形码的按键事件中,addOrder事件被执行:

    function OrderCollection() {
        var self = this;
        self.ShirtOrder = ko.observableArray([new PurchaseOrderViewModel()]);

        self.addOrder = function (data, event) {
            if (event.keyCode == 13) {
//Here before pushing new object to self.ShirtOrder. I want to access current object and change its expDate and importDate value.

                var _SO = new PurchaseOrderViewModel();
                _SO.seqNo = $("#SOBody > tr").length + 1;
                self.ShirtOrder.push(_SO);
            }
        };
    }

HTML:

<tbody data-bind="foreach: ShirtOrder()" id="SOBody">
   <tr>
      <td>
         <input type="text" value="1" class="req measurment" data-bind="value: seqNo" />
      </td>
      <td>
         <input type="text" class="" data-bind="value: barcode, valueUpdate: 'afterkeydown', 
            event: { keypress: $parent.addOrder }" />
      </td>
      <td>
         <input type="date" class="req measurment" data-bind="value: expDate" />
      </td>
      <td>
         <input type="date" class="req measurment" data-bind="value: importDate" />
      </td>
      <td>
         <input type="text" class="req measurment" data-bind="value: name" />
      </td>
   </tr>
</tbody>

在条形码文本框中按Enter键事件时。应更改导入日期和导出日期值,并且还应创建新的TR。我无法更改价值。

1 个答案:

答案 0 :(得分:2)

嗯,你只需要做这样的事情

查看型号:

    function OrderCollection() {
            var self = this;
            self.ShirtOrder = ko.observableArray([new PurchaseOrderViewModel()]);
            self.addOrder = function (data,event) {
                if (event.keyCode == 13) {
                    data.expDate('2014-10-27'); // you get current instance here 
                    data.importDate('2015-01-20');
                    var _SO = new PurchaseOrderViewModel();
                    self.ShirtOrder.push(_SO);
                }
            };
        }

     $(function() {
         ko.applyBindings(new OrderCollection());
    });

此处抓取使用type="date"时,您应始终使用格式yyyy-MM-dd( W3C standard )进行设置。

工作小提琴 here