无法从html调用静态方法

我有一个带有静态方法的类,试图从html页面调用它。当我尝试使用Class.Method()语法调用该方法时,出现一个错误:“未定义<类名>”。当我从其他javascript类的实例调用相同的静态方法时,静态方法可以正常工作。

我设法一起解决了一个变通方法,但是看起来不正确:

window.dlg = Dialogs;       // static methods only // do I have to do this?

This question appears to validate my belief that I should be able to call my method using Class.Method() syntax.

This question appears to address the issue but does not explain how a static method might be called from html.

我究竟做错了什么?

// main.js

import { Site } from './site.js';
import { Dialogs } from './dialogs.js';

(async function ($) {
    "use strict";
    window.site = new Site();   // instance methods

    // hack:
    window.dlg = Dialogs;       // static methods only // do I have to do this?
    await window.site.Init();
})(jQuery);

// dialogs.js

class Dialogs {
    static ShowLoginDialog() {
        $('#login-dialog').modal('show');
    }
}
export { Dialogs };

// html

// works            
<a href="#" onclick="window.dlg.ShowLoginDialog()"><i class="icofont-login"/>&nbsp;Log in</a>

// does not work but I think it should. Error msg:  Dialogs is not defined.
<a href="#" onclick="Dialogs.ShowLoginDialog()"><i class="icofont-login"/>&nbsp;Log in</a>
评论
  • April
    April 回复

    Avoid inline handlers, they have way too many problems to be worth using in a modern codebase. Since you're using modules, the Dialogs won't be available globally unless you explicitly assign it to the global object which, as you've noticed, is an ugly hack (and inline handlers can only reference global variables). You should attach the event listener properly using Javascript instead: select the element inside your script, and call addEventListener on it:

    // main.js
    
    import { Site } from './site.js';
    import { Dialogs } from './dialogs.js';
    
    (async function ($) {
        "use strict";
        window.site = new Site();   // instance methods
    
        document.querySelector('a.login-anchor').addEventListener('click', () => {
            Dialogs.ShowLoginDialog()
        });
        await window.site.Init();
    })(jQuery);
    

    where a.login-anchor can be replaced with whatever selector you want to target the <a> with the listener:

    <a href="#" class="login-anchor"><i class="icofont-login"/>&nbsp;Log in</a>