简体   繁体   中英

Using functions defined in typescript code from html

I have the following typescript files (pseudo code) Calculator.ts

export class calculator{
  someFunction
}

Main.ts

Import calculator from calculator.ts

function callSomeFunction()
{
  Calculator.somefunction();
}

Question: if tsc compiler bundles and generates code using systemjs or some other module syntax, will I be able to call callSomeFunction method from html which has bundle.js as script reference. If not then do I need to do window.callSomeFunction = callSomeFunction? Is there any other way?

The best way would be for the JavaScript to attach listeners to elements itself - for the JavaScript (your entire bundle) to depend on the HTML markup, but for the HTML markup to not (directly) depend on your JavaScript.

For example, instead of

<button onclick="doSomething()">click</button>

do

<button class="some-button">click</button>
// JavaScript that gets bundled
document.querySelector('.some-button').addEventListener('click', doSomething);

This way, doSomething doesn't need to be global, and you get to avoid inline handlers (which should never be used anyway).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM