简体   繁体   English

使KnockOut可观察的数组属性可观察

[英]Making KnockOut observable array property observable

I have a observable array AllItems defined as 我有一个可观察的数组AllItems定义为

var ViewModel = function () { 
  var self = this; 
  self.AllItems = ko.observableArray([]);
}

It gets filled by data from a ajax call and I just add the properties received from the Ajax call directly to the array without defining them. 它由来自ajax调用的数据填充,我只是将从Ajax调用接收的属性直接添加到数组中,而无需定义它们。

I am using it in the below HTML to populate a table. 我在下面的HTML中使用它来填充表格。

 var ViewModel = function() { var self = this; self.AllItems = ko.observableArray([]); } $(document).ready(function() { ko.applyBindings(new ViewModel()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js"></script> <table> <tbody data-bind="foreach: AllItems"> <td> <span>$</span><span data-bind="text: $data.RequestedPrice"></span> </td> <!-- ko ifnot: (Number(RequestedPrice) > Number(ItemDetails.SmPrice)) --> <input type="button" disabled value="Approve" id="Approved" data-bind="click: $root.ApproveItem" style="background-color:#e1eae5 !important" /> <!-- /ko --> <!-- ko ifnot: (Number(RequestedPrice) > Number(ItemDetails.SmPrice)) --> <input type="button" disabled value="Approve" id="Approved" data-bind="click: $root.ApproveItem" style="background-color:#e1eae5 !important" /> <!-- /ko --> <nobr>$ <input type="text" class="priceChange" onkeypress="return isNumberKey(event)" style="display:inline !important" data-bind="value: $data.RequestedPrice" /> </nobr> </tbody> </table> 

SO i have three things in the above HTML. 所以我在上面的HTML中有三件事。 First I am just displaying the text of the requested price. 首先,我只显示要求价格的文本。 Second I am using it to disable a button and third I am making it a editable field. 第二,我使用它来禁用按钮,第三,我将其设为可编辑字段。

The issue is that when I change the value it is not reflected in the text and also the second case where it is used to disable a button is not updated. 问题是,当我更改该值时,它不会反映在文本中,并且用于禁用按钮的第二种情况也不会更新。 Can someone please tell me what I need to achieve this. 有人可以告诉我实现此目标需要什么。

Three options: 三种选择:

  • Write a custom mapping from your js(on) coming from the back end to objects that do have observable properties; 从您的js(on)编写一个从后端到确实具有可观察属性的对象的自定义映射;
  • Use ko.mapping ; 使用ko.mapping ;
  • Use knockout.es5 with some custom code; 使用带有一些自定义代码的基因敲除

Knockout, as oppossed to Angular 1, requires you by default to be explicit about which stuff you want to be observable (when using ko.mapping you're explicitly saying all the stuff is observable). 与Angular 1相对,淘汰赛要求您默认情况下要明确指出要观察的东西(使用ko.mapping时,您明确地说所有东西都是可观察的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM