3

I want to call a typescript function from the HTML body. However, I am unable to call my function(D2O_main()) from HTML as I don't fully understand the generated js code. Any help is greatly appreciated.

I generated the js using the following command: tsc --module umd main.ts

Here's the html file.

<head>
    <script type="text/javascript" src="main.js"></script>
</head>
<body onload="D2O_main();">
    <canvas id="canvas-001"></canvas>
</body>
</html>

Here's the main.ts file:

import {Init} from "./Core/IO/Init"
let init:Init;
function D2O_main() {
    init = new Init("canvas-001");
}

Here's the generated main.js file:

(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "./Core/IO/Init"], factory);
    }
})(function (require, exports) {
    "use strict";
    exports.__esModule = true;
    var Init_1 = require("./Core/IO/Init");
    var init;
    function D2O_main() {
        init = new Init_1.Init("canvas-001");
    }
});

I'm getting the following error at the browser console:

Uncaught ReferenceError: D2O_main is not defined at onload

Once again, any help is greatly appreciated.

1 Answer 1

1

It's because nested functions are function-scoped - you'd need to move function D20_main outside of the IIFE it is contained in, effectively making it a globally accessible function:

(function (factory) {...})(function (require, exports) {...}); 
function D20_main() {...}
Sign up to request clarification or add additional context in comments.

1 Comment

I do not want to change the js file manually since it is autogenerated. Please suggest a modification to the .ts file or .html file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.