Button click event binding in Electron js

 ̄綄美尐妖づ 提交于 2019-12-21 03:36:11

问题


I have started using electron js to develop desktop application.

I want to know that how to bind button click event with javascript function so that I can perform other operation.

I used below HTML code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Manav Finance</title>
  </head>
  <body>
    <input type="button" onclick="getData()" value="Get Data" />
  </body>

  <script>
    // You can also require other files to run in this process
    require('./renderer.js')
  </script>
</html>

My renderer.js code looks like this:

function getData(){
        console.log('Called!!!');
    }

But I am getting error that:

Uncaught ReferenceError: getData is not defined at HTMLInputElement.onclick

Am I doing something wrong?

Update

Updated HTML document and removed require() method and its working now:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Manav Finance</title>
    <script src="renderer.js"></script>
  </head>
  <body>
    <input type="button" id="btnEd" value="Get Data" onclick="getData()" />
  </body>
</html>

回答1:


To explain this for future users. <script> tag's in an HTML document are executed in the global scope, this means that this === window, I.e. any function or variable declared in the script inherently becomes global.

When you require a script it becomes isolated in it's own context (it is wrapped in another function so this !== window, I.e. any function or variable declared in the script is not available globally.

The correct way to do this is to use require('./renderer.js') and to use this code

function getData() {
    ...
}

document.querySelector('#btnEd').addEventListener('click', () => {
    getData()
})


来源:https://stackoverflow.com/questions/43102216/button-click-event-binding-in-electron-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!