allBlogsList

Extending Typescript Classes in an Insite Project

Inheriting from a base class is a great way to reuse common functionality without having redundant blocks of code sprinkled throughout your project. Creating a base class to expose this core functionality promotes cleaner code that is easier to maintain. Read on to see how to create and extend a typescript base class in an Insite project. 

Let’s start by creating our base class which will contain functionality that all derived classes can use. Our base class will be called ProductListBase and for simplicity sake will have one method called isLoggedIn.

module xc.catalog {
    export class ProductListBase {
        isLoggedIn(): boolean {
            return false;
        }
    }
}

We now create a new controller class named FavoritesProductList that inherits from ProductListBase. FavoritesProductList and any other class that inherits from ProductListBase will now have access to any and methods exposed in the base class.

module xc.catalog {
    class FavoritesProductList extends ProductListBase {
        constructor() {
            alert("this.isLoggedIn " + this.isLoggedIn());
        }
    }
}

If we run this code now we would get the following error:

angular.js:11655 Error: [ng:areq] Argument 'favoritesProductListController' is not a function, got undefined

This error is a little deceptive but what’s happening here is the favoritesProductListController can’t find the “ProductListBase” class. This is because our TypeScript classes are bundled alphabetically. Since FavoritesProductList comes before ProductListBase the favoritesProductList can’t see it and does not know about the base class and does not have access to it. In order to ensure that our base class is loaded prior to any classes that inherit from it we can add the name of our class to the custom.XML file which resides in themes/demoTheme/scripts/custom/custom.xml.

Notice in the code sample below that the file extension is .js and not .ts. This is because all TypeScript classes are transpiled to javascript prior to bundling. /Custom/Catalog/xc.productlistbase.controller.js

<?xml version="1.0" encoding="utf-8" ?>
<!-- add files paths here to include them after base scripts but before automatically included custom scripts in global.min.js -->
<files>
   <file>/Custom/Catalog/xc.productlistbase.controller.js</file>
</files>

Now if we run our project we can see that the code fires and everything functions as expected. Extending a base class can be summarized in the following 3 steps.

  1. Create a base class
  2. Create one or more classes that extend the base class
  3. Add the file path of the base class to the custom.xml file