如何将模块导出的函数导入HTML onclick =“”事件处理程序的全局范围?

问题描述 投票:0回答:1

一个简单的HTML网页,使用SystemJS 0.21加载从TypeScript编译的JavaScript模块。 HTML网页有一个onclick=""风格的事件处理程序,它调用模块文件中声明的函数:

tsconfig.json

{
    "compilerOptions": {
        "module": "system",
        "moduleResolution": "node"
    }
}

Page.ts

export function onButtonClick( e: Event, btn: HTMLButtonElement ): boolean {

    console.log( 'clicked!' );
    return true;
}

我在网站(不是SPA)的HTML页面中使用SystemJS,如下所示:

system.config.js

System.config( {

    map: { /* ... */ },

    packages: {
        '/scripts/': { defaultExtension: 'js' }
    }

} );

System.import( '/scripts/Page' );

page.html中

<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)对象中。所以我在控制台窗口中得到了这个输出:

未捕获的ReferenceErroronButtonClick未在HTMLButtonElement.onclick中定义(Page.html:8)

那么我怎样才能让我的qazxsw poi在qazxsw poi / qazxsw poi中使用qazxsw poi?

javascript module systemjs
1个回答
0
投票

我现在开发了一个解决方案:

  1. 在TypeScript模块中扩展全局<button onclick="onButtonClick( event, this )"对象接口以添加新的全局函数。
  2. 在模块的“顶级”函数中,在function onButtonClick上分配那些声明的函数属性。

这与使用SystemJS将模块导入Page.ts对象(这是我最初想要的)不同,这种方法也要求我修改我导入的模块,但它现在可以工作。

像这样:

Page.ts

Page.js

不再需要导出Window函数。通过直接分配函数,可以使这更加简洁:

Page.ts

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; }; 属性在加载模块之前不会起作用 - 但假设在页面加载后很快发生,则不会出现任何用户体验问题。

© www.soinside.com 2019 - 2024. All rights reserved.