简体   繁体   中英

Knockout JS - Observable becomes undefined when added to an array

I have an object called purchase that gets put into one of two observable arrays depending on its status. The purchase object has an observable called integrationStatus that I default to a css class name of integration-status--complete

For some reason the purchases in the Scheduled array are coded green as expected but the purchase in the Unscheduled array throws an error as integrationStatus is undefined

Thanks in advance

JS Fiddle

The issue is related to the mapping configuration within Schedule . The mapping call ko.mapping.fromJS(data, { scheduleDays : scheduleDayMapping }, self) instructs the utility to only customize the mapping of the scheduleDays object from the data variable.

Since that configuration doesn't include an entry for unallocatedHolder , the mapping utility uses the default observable creation behavior instead of the custom behavior. The UnallocatedHolder function is never called, so its purchases array doesn't get the custom mapping. Without that mapping, integrationStatus is not defined for those purchases.

I'd suggest defining a new mapping configuration for Schedule like this:

var scheduleMapping = {
  "scheduleDays": scheduleDayMapping,
  "unallocatedHolder": {
    create: function(options) {
      return new UnallocatedHolder(options.data);
    }
  }
};

Then, reference this new mapping configuration within Schedule by updating the mapping line to

ko.mapping.fromJS(data, scheduleMapping, self);

Revised Fiddle

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