SkuPropertiesHandler example

In order to access SKU properties for a given SKU object using the viewModels/SkuPropertiesHandler module, you must determine the product type the SKU belongs to so it may be passed to the viewModels/SkuPropertiesHandler method that retrieves the property definitions.

The following widget code snippet iterates over the SKUs in a cart, determines the product type for each SKU, retrieves the SKU property definitions for that product type, and then populates an observable array with the label, ID, and values for each SKU property for each SKU in the cart.

// Make sure to import 'viewModels/skuPropertiesHandler' and alias
// as SkuPropertiesHandler

// Iterate over a given set of cart items (SKUs) and populate the properties of
// each SKU
ko.utils.arrayForEach(widget.cart().items(), function(item) {
    widget.populateSkuProperties(item.productData());
});
// Sample function that populates the SKU properties
populateSkuProperties: function(item) {
    var self = this;
    // Property definition array
    var skuPropDefinition = ko.observableArray([]);
    // Variable in the item object to store properties and their values
    item.mySkuPropertyArray = ko.observableArray([]);
    // Get the product type of the SKU
    var productType = 'product';
    if (item.type) {
      productType = item.type;
    }
    // API call to get the property definition of the SKU
    SkuPropertiesHandler.getAll(skuPropDefinition, productType,
      function(skuPropDefinition) {
    // Iterate over each property of the SKU and populate the array, which can
    // then be used in the widget template
    for (var i=0; i < skuPropDefinition().length; i++) {
      var currentProperty = skuPropDefinition()[i];
      var currentSku = item.childSKUs[0];
      if (currentSku[currentProperty.id]) {
        // Add the label, ID, value, etc to a variable that can be accessed
        // by the widget template
        item.mySkuPropertyArray.push({
          'mylabel':currentProperty.label,
          'myid':currentProperty.id,
          'myvalue': currentSku[currentProperty.id]});
      }
    }
  });
}

After creating the observable array, you can use it in the widget’s template to render the SKU properties on the page:

<!-- // Iterate over the array that was created by the 'populateSkuProperties' in widget.js -->
<!-- ko foreach: mySkuPropertyArray -->
    <div>
        <span data-bind="text: mylabel"></span> (<span data-bind="text:
          myid"></span>) : <span data-bind="text: myvalue"></span>
    </div>
<!-- /ko -->