简体   繁体   中英

Making KnockOut observable array property observable

I have a observable array AllItems defined as

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.

I am using it in the below HTML to populate a table.

 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. 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;
  • Use 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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