Wednesday, May 2, 2018

Typescript KnockoutJS - Uncaught TypeError: is not a constructor - During ko.applyBindings()

In an ASP.NET MVC project that is using a Typescript version of KnockoutJS, i received an error that i was unable to resolve using the suggestions currently found through searching online.

I modeled the view after another view that already existed and so in comparison (using "Find Usage" in VS) there was no reason i could see as to why i was seeing this error on one view.


The Error:

Uncaught TypeError: <class> is not a constructor
Javascript

<script type="text/javascript">
    $(document).ready(function () {
        ko.applyBindings(new Northwind.ZendeskRootViewModel());
    });
</script>
Typescript

namespace Northwind {
    export class ZendeskRootViewModel {
        constructor() {
        }
                
        public onAllow() {
            ...
        }

        public onDeny() {
            ...
        }
     
    }
}

Things i tried:
1. Ensure the model being instantiated has been declared before it's use. Source1 Source2
2. Ensure constructor signature matches the parameters i'm sending for it's instantiation and i'm referencing the correct model Source
3. Ensuring that the applyBindings() code is at the bottom of my source file to ensure the items exist in the DOM. Source

Solution:
What i was forgetting is that i'm using TypeScript. Which means that the files referenced in the IDE during compile time are not the final output files. Typescript compiles to .js files. And being an MVC project, those files aren't referenced directly in the views, but rather are a part of the BundleConfig.cs

I had forgotten to include the output .js files in the BundleConfig and so they were never being loaded on that page. Doh! :)

No comments :