Skip to content Skip to sidebar Skip to footer

Mapping A Nested Object As An Observable From A Complex Json Using The Create Callback

I've got a complex object in a JSON format. I'm using Knockout Mapping, customizing the create callback, and trying to make sure that every object that should be an observable - wo

Solution 1:

In the transition from ViewModel -> plain object -> ViewModel you loose the relation between the products in your cart and the ones in your handlerVM.

A common solution is to, when loading a plain object, manually search for the existing viewmodels and reference those instead. I.e.:

  • We create a new cartItemVM from the plain object
  • Inside its cartItemName, there's an object that does not exist in handlerVM.
  • We look in handlerVM for a product that resembles this object, and replace the object by the one we find.

In code, inside loadCart, before setting the new viewmodels:

loadedCartItems().forEach(
    ci => {
      // Find out which product we have:const newProduct = ci.cartItemName().productName;
      const linkedProduct = self.availableProducts()
          .find(p => p.productName().english === newProduct.english());

      // Replace the newProduct by the one that is in `handlerVM`
      ci.cartItemName(linkedProduct)
    }
)

Fiddle: https://jsfiddle.net/7z6010jz/

As you can see, the equality comparison is kind of ugly. We look for the english product name and use it to determine the match. You can also see there's a difference in what is observable and what isn't.

My advice would be to use unique id properties for your product, and start using those. You can create a simpler optionsValue binding and matching new and old values happens automatically. If you like, I can show you an example of this refactor as well. Let me know if that'd help.

Post a Comment for "Mapping A Nested Object As An Observable From A Complex Json Using The Create Callback"