【问题标题】:module.exports method that interacts with HTML page does not work与 HTML 页面交互的 module.exports 方法不起作用
【发布时间】:2017-07-15 03:03:36
【问题描述】:

我正在运行一个电子应用程序,其中我的index.html 页面由scripts.js 中的函数更新。

我正在尝试通过将函数“移动”到同一 js 目录中的单独文件中来清理 scripts.js 文件,但每当我这样做并将该函数导入回 scripts.js 以在render() 方法,不起作用。

例如,我将currencyExchange() 函数放入名为currencyAPI.js 的单独文件中:

var currencyExchange = function(){ 
    //code here 
} 

module.exports.currencyExchange = currencyExchange

然后,我将它导入到我的scripts.js 文件中:

var currency = require(./currencyAPI.js);

然后在我的render() 函数中调用它,如下所示:

function render(){
    // ...
    setInterval(currency.currencyExchange, 1500)
}

但是,当运行currency.currencyExhchange 时,它说该文档未定义。

这是我的app 中的scripts.js 文件

【问题讨论】:

  • “不起作用”什么也没告诉我们。更具体。
  • @jfriend00 这个问题也被标记为 Electron,它是一个 npm 模块,它提供了一个简单的 Chromium fork,您可以使用它来编写桌面应用程序。例如,Electron(在 BrowserWindow 内)使您能够使用文档和窗口。

标签: javascript node.js electron


【解决方案1】:

在 index.html 中放置一个带有currencyAPI.js 的脚本标签,并且currencyAPI.js 的所有功能都将在scripts.js 中可用。 html页面无需导入导出。

html 页面中的所有脚本都作为全局脚本工作,脚本函数和变量可供所有其他脚本访问。

所以你可以直接在scripts.js中的任何地方使用currencyExchange函数

【讨论】:

    【解决方案2】:

    以下对我有用。

    // a.js:
    const currencyExchange = function (foo) {
        console.log('currencyExchange(): ', foo);
        return foo;
    }
    
    module.exports.currencyExchange = currencyExchange
    
    // b.js
    const currency = require('./a');
    
    const render = function() {
        const bar = 'dummy';
        setInterval( currency.currencyExchange, 1500, bar);
    };
    
    render();

    运行这个...

    node b.js
    

    ...输出这个:

    currencyExchange():  bar
    render():  bar
    

    【讨论】:

    • 我认为 OP 有额外的代码,他们应该在说“它对我有用”之前分享这些代码。这并没有真正的帮助....
    • @montrealist,我现在更新了这个问题。我在模块的原始导出中的代码中输入了一个错字,但现在已经解决(并导致了另一个问题)。
    • 如何以及在哪里执行 scripts.js 中的render()?您可能会遇到this 的值在setInterval 内部不同的问题。阅读更多here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多