Search code examples
c#jqueryasp.net-mvctypescriptsystemjs

How to call function through onclick when JS is loaded through System.js


I'm have an typescript file in my MVC project that has gotten quite large. I want to break it up use System.js to load the files.

I have included the system.js reference within my _Layout.cshtml view.

<script src="~/Scripts/system.js"></script>
<script>
    $(document).ready(function ()
    {
        System.import("Scripts/main.js");
    });
</script>

My main.ts file has a function that loads an item.

function load(id: string): void
{
    // Stuff
}

In my Index.cshtml view I have a div that calls the function when it's clicked.

<div onclick="load('@item.Id')"></div>

But everytime I click on the div I get the following error in the console:

Uncaught ReferenceError: load is not defined at HTMLDivElement.onclick ((index):41)

Looking at the network traffic I can see that main.js is loaded by system.js. But for some reason the functions cannot be accessed via the HTML. Am I doing the something in the wrong spot? Or is there a specific way I need to setup my typescript file to call the function?

Thanks for any help.


Solution

  • <div onclick="load('@item.Id')"></div> This old-school-pure-html way of binding event listener requires load to be a global scope function.

    System.js import your main.js, but it kinda scopes it up in a closure I guess. load is no longer accessible in global scope, thus the bug.