Skip to main content
1 of 2

inheritance in knockoutJS components within magento 2's knockout framework

've been experimenting with a custom module with KnockoutJs on the frontend in M2.

I've created two components: a ProductPackage and a ProductPackagePopop. Functionaly, the ProductPackage triggers a modal which renders some details about the package's children.

These two components share quite some logic which i would like to share between the components. For example: both have a function 'initTranslations' which retrieves the right translations for this store id.

Since i'm new to the magento2 Knockout implementation, is there some way to create a base component from which my two components inherit the shared logic? Or a trait like in PHP. I've looked at mixins, but it seems to me it's more fit to extend external is.

define(['uiComponent'], function (Component) {

return Component.extend({
    store_id: 0,

    initialize: function (config) {
        this.store_id = config.store_id;
        this.initTranslations(config.productPackage);
    },
    initTranslations: function (productPackage) {
      //some logic here
    },
    children: function(){
     // retrieves children
    }


});

});

I've found this: https://stackoverflow.com/questions/16569810/knockout-viewmodel-base-class-javascript-inheritance , but i find it hard to fit that in the M2 Knockout/RequireJs wrapper.