Browser how to access main.js functions

I can get it to work with the browser, but I'm a little confused about how to access functions in bundle.js from the DOM.

I have three files -

message.js

module.exports = function (){ return "Hello"; }; 

main.js

 var getMessage = require('./message'); //This shows the alert when script loads alert(getMessage()); //cannot find this function from index.html function fnClick(){ alert(getMessage()); } 

index.html

 <!DOCTYPE html> <html> <head> <title></title> <script src="js/bundle.js"></script> </head> <body> <button onclick="fnClick();">Click</button> </body> </html> 

In the browser, when the script loads alert(getMessage()); in main.js, a warning is displayed, but the debugger, fnClick is undefined, and I can work with the scope.

thanks

+5
source share
3 answers

Any code in the login file is executed in close. If you look at the bundle.js created, you will see something like this there.

 function(require, module, exports) { function fnClick() { alert(getMessage()); } } 

Everything that you create here will simply be hidden in the global space unless you explicitly use the window object (but do not ) to open it.


As @elclanrs explained in the comments above, just attach only the receiver in your code instead of HTML. If you do not want to use external libraries, you can do this with difficulty.

 var button = document.getElementById('my-button'); // add id="my-button" into html button.addEventListener('click', fnClick); 

Or with a library like the popular jQuery that you just call.

 $('#my-button').click(fnClick) 
+17
source

Would you like to consider the domready package? For a detailed example, see Is the browser and documents ready? .

If you are usind domready, your example would look like this:

message.js (remains unchanged)

 module.exports = function (){ return "Hello"; }; 

main.js (note the changes)

 var domready = require("domready"); var getMessage = require('./message'); domready(function () { //This shows the alert when script loads alert(getMessage()); function fnClick(){ alert(getMessage()); } }); 

index.html (remains unchanged)

 <!DOCTYPE html> <html> <head> <title></title> <script src="js/bundle.js"></script> </head> <body> <button onclick="fnClick();">Click</button> </body> </html> 
+1
source

1) set dom-event-listener as: https://www.npmjs.com/package/dom-event-listener

2) in main.js add something like:

 var domEventListener = require('dom-event-listener'); var element = document.getElementById('my-button'); domEventListener.add(element, 'click', function(event) { console.log(event); }); 
+1
source

Source: https://habr.com/ru/post/1201197/


All Articles