What is an event?

16 views
Skip to first unread message

sn...@olymega.org

unread,
Jun 16, 2018, 10:41:49 AM6/16/18
to v8-users
I am looking for what an event is in terms of its implementation.I know what an event is in the abstract sense:

For instance, everyone knows what a 'list' is - a term that applies equally to 'shopping list' as well as 'collection of data'. However, I'm more interested in event implementation, e.g. how a programming language implements lists as arrays and Objects. I would like to know how events exist concurrently as code in the browser (written in in C++) and as data. (picked by an event handler). 

Thank you! The official docs are sparse on how events are implemented. So far, I know that they are 'objects' though it's not clear whether these are objects v.v. C++ or JavaScript. 

J Decker

unread,
Jun 16, 2018, 2:44:24 PM6/16/18
to v8-users
any of the above.
Events are a map of some sort of identifier and a callback.
For my websocket interface, which is C/C++ the events are tracked in C/C++ structures. 
For a graph database I was tinkering with in ES6, the events are tracked in just javascript ojects.

A super simple way (and I'm sure there's lots of ways of doing this)

var myObjectWithEvents = { events : {},
   on( event, callbackOrData ) {
       if( typeof callbackOrData === "function" ) {
            this.events[event] = callbackOrData;   // register event handler
       } else {
            if( event in this.events ) {
                this.events[event]( callbackOrData );  // invoke event handler
            }
       }
    }
};

myObjectWithEvents.on( "click", (data)=>{ console.log( "got click event..." ) } );   /// register an event handler to 'click'
....
myObjectWithEvents.on( "click", { x:1, y : 250 } );   // trigger an event...


Instead of assigning directly, each event in 'events' could be an array ... []  and .push( callbackOrData ); would allow you to assign multiple handlers to each eent instead of a single... and then you'd just  do something like    this.events[event].forEach( cb=> cb( callbackOrData ) ) instead.

The above was something I got from Gun DB; if the argument passed to 'on' is a function, keep that function as a callback stored as the name of the event specified.  If it's not a function, call any previously registered event with the data passed to 'on', which then overloads 'on' as both the uhh addEventListener()  and the emit().


sn...@olymega.org

unread,
Jun 17, 2018, 12:41:04 AM6/17/18
to v8-users
Thank you for your reply. I guess I am wondering where and how JavaScript and C++ code/data interact. 

I assume that C++ and JavaScript compile/interpret into 'mutually intelligible' byte code. 

I also assume that Events are Data that are dispatched by the Browser upon, say, I/O. 

Then, JavaScript code, like yours above, can handle an Event once it has fired, caught and placed on queue by the Event Loop, which pushes it onto the Stack. 
Reply all
Reply to author
Forward
0 new messages