Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is event a global variable that is accessible everywhere inside the callback chain?

I was just playing around with event listeners with DOM and Javascript and did notice this:

function chained(msg) {     console.log(msg, event); }  function onClick() {     chained('the body was clicked'); }  document.body.addEventListener('click', onClick); 

Now the funny thing...this will output:

"the body was clicked, (MouseEvent)"

Then I ask, why? how does it passes the event object without sending it on the chained call?

function chained(msg) {     console.log(msg, namedEventObj); //throw error namedEventObj is not defined }  function onClick(namedEventObj) {     console.log(event); //outputs (MouseEvent);     console.log(nameEventObj); //outputs (MouseEvent);     chained('the body was clicked'); }  document.body.addEventListener('click', onClick); 

Even If I declare the event obj to be passed on the onClick function as namedEventObj it will available only to onClick but not to chained function...I got this and this makes sense for me...but definitely not the event variable to be available to the chained function.

Anyone know why does it behaves like this?

The only thing I can think of is that event is in fact window.event and it makes itself available when some event dispatches and Event...but that would mean that any element could get that event information if called at the same time as the event when it triggers?

I am using Chrome 11.0.x

like image 423
zanona Avatar asked Jun 21 '11 13:06

zanona


People also ask

Is an event listener a callback?

The event listener callbackThe event listener can be specified as either a callback function or an object whose handleEvent() method serves as the callback function.

Where are event listeners stored?

Its stored in the actual list (array) of Event listeners for body . Elements have a list of function references in them for their event listeners. These references are not in the DOM. When firing an event, the browser has to run thru all the appropriate elements looking for these references and running them in order.

Is window a global variable?

In HTML, the global scope is the window object. All global variables belong to the window object.

Can event listeners be used with any element?

Creating an Event Listener Using JavaScript. You can listen for events on any element in the DOM. JavaScript has an addEventListener() function that you can call on any element on a web page. The addEventListener() function is a method of the EventTarget interface.


1 Answers

One can access the current event through window.event. Just using event is implicitly accessing window.event.

like image 167
Nathan Romano Avatar answered Sep 20 '22 22:09

Nathan Romano