一个简单的HTML网页,使用SystemJS 0.21加载从TypeScript编译的JavaScript模块。 HTML网页有一个onclick=""
风格的事件处理程序,它调用模块文件中声明的函数:
{
"compilerOptions": {
"module": "system",
"moduleResolution": "node"
}
}
export function onButtonClick( e: Event, btn: HTMLButtonElement ): boolean {
console.log( 'clicked!' );
return true;
}
我在网站(不是SPA)的HTML页面中使用SystemJS,如下所示:
System.config( {
map: { /* ... */ },
packages: {
'/scripts/': { defaultExtension: 'js' }
}
} );
System.import( '/scripts/Page' );
<html>
<head>
<script src="/scripts/system.src.js"></script>
<script src="/scripts/system.config.js"></script>
</head>
<body>
<button onclick="onButtonClick( event, this )">Click me and check the browser console</button>
</body>
</html>
这不起作用,因为onButtonClick
函数在Page.js
中定义为模块中的函数,这意味着它不会在使用脚本时作为属性导入到全局(Window
)对象中。所以我在控制台窗口中得到了这个输出:
未捕获的
ReferenceError
:onButtonClick
未在HTMLButtonElement.onclick中定义(Page.html:8)
那么我怎样才能让我的qazxsw poi在qazxsw poi / qazxsw poi中使用qazxsw poi?
我现在开发了一个解决方案:
<button onclick="onButtonClick( event, this )"
对象接口以添加新的全局函数。function onButtonClick
上分配那些声明的函数属性。这与使用SystemJS将模块导入Page.ts
对象(这是我最初想要的)不同,这种方法也要求我修改我导入的模块,但它现在可以工作。
像这样:
Page.js
不再需要导出Window
函数。通过直接分配函数,可以使这更加简洁:
window
因为window
/ declare global {
declare interface Window {
onButtonClick( e: Event, btn: HTMLButtonElement ): boolean;
}
}
function onButtonClick( e: Event, btn: HTMLButtonElement ): boolean {
console.log( 'clicked!' );
return true;
}
window.onButtonClick = onButtonClick;
模块是异步加载的,所以它确实意味着当onButtonClick
加载时,declare global {
declare interface Window {
onButtonClick( e: Event, btn: HTMLButtonElement ): boolean;
}
}
window.onButtonClick = onButtonClick( e: Event, btn: HTMLButtonElement ): boolean {
console.log( 'clicked!' );
return true;
};
属性在加载模块之前不会起作用 - 但假设在页面加载后很快发生,则不会出现任何用户体验问题。