Professional Documents
Culture Documents
It’s worth noting that event-driven programming is often asynchronous, and it’s particularly
popular in graphical user interfaces (GUIs), real-time apps, and IoT use cases.
EDP typically goes hand-in-hand with event-driven architectures (EDA). While EDA
defines how multiple (and different) programs interact and communicate via events, EDP
provides the means to implement the specific logic and behaviors within a program in
response to events. That’s not to say that all components that comprise an EDA need to
follow the EDP paradigm; however, adopting event-driven programming where suitable
can lead to more efficient and responsive systems within the overarching EDA. I won’t go
into more details here, but please see the “Event-oriented architecture: e-commerce
example” section towards the end of this article to better understand how EDP works as
a part of a wider EDA.
JavaScript Events
The change in the state of an object is known as an Event. In html, there are various
events which represents that some activity is performed by the user or by the browser.
When javascript code is included in HTML, js react over these events and allow the
execution. This process of reacting over the events is called Event Handling. Thus, js
handles the HTML events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the
task to be performed on the event.
mouseover onmouseover When the cursor of the mouse comes over the
element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keyboard events:
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
change onchange When the user modifies or changes the value of a form
element
Window/Document events
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the browser
unloads it
resize onresize When the visitor resizes the window of the browser
Events
An event refers to a significant occurrence or change in state within a system or
application. In simpler words, an event records that something has happened. Here are
some common examples of events:
Collecting such telemetry events enables the manufacturing company to monitor its
machines in real time and detect issues in production lines as soon as they occur. This
way, the manufacturer can quickly react and follow the appropriate course of action (i.e.,
investigate the machine and perform maintenance, if needed).
A monitoring system designed to analyze and visualize real-time vibration data, history,
and trends.
An alerting system that sends automated alerts via email, SMS, or other means to
maintenance teams.
A database or data storage system that stores the vibration readings for historical
analysis, reporting, or compliance purposes.
All of the above (you can have multiple and different types of components/systems
consuming an event).
It’s also worth mentioning that, depending on the use case, an event producer can also
be a consumer. Think, for example, of chat apps. If you send a chat message (an
event), you are the producer. On the other hand, if you receive a chat message, you are
the event consumer.
handleButtonClick is the event handler — the actual code that gets executed in
response to the ‘click‘ event. Here’s a possible implementation:
function handleButtonClick(event) {
alert('Hello world!');
}
On button click, this trivial event handler will display an alert to the user saying ‘Hello
world!‘
Note that you will often see these two terms (event listener and event handler) being
used interchangeably. However, as we have just seen, there is a distinction between
them:
The event listener listens for events and specifies which function to call when an event
occurs.
The event handler is the actual callback function that gets executed in response to the
event.
More efficient troubleshooting. When debugging, it's essential to know if an issue lies
in the event listening mechanism (the event isn't being captured) or the event handler
(the response isn't as expected).
Flexibility and modularity. Multiple event listeners can trigger the same event handler,
and vice versa, a single event listener can trigger different event handlers based on
certain conditions. Grasping the distinction between handlers and listeners allows for
more flexible and modular coding practices.
Clarity in collaboration. It’s crucial to have clear, shared terminology at a team level.
Misunderstandings can arise if one person is discussing a handler while someone else
believes they’re talking about a listener.
Before moving on from event listeners and handlers, it’s important to say a few words
about the event loop. Numerous runtimes and frameworks (e.g., JavaScript/Node.js or
Python’s asyncio library) use an event loop as a sort of intermediary between event
listeners and event handlers. Here’s how it works:
1. Event listeners detect incoming events and place them in an event queue.
2. The event loop mechanism continually checks for queued events and calls the
corresponding event handler for each event.
One of the main benefits of the event loop is that it enables concurrent execution and
non-blocking I/O operations when you’re working with single-threaded programming
languages and runtimes.
Event examples:
Click Event
1. <html>
2. <head> Javascript Events </head>
3. <body>
4. <script language="Javascript" type="text/Javascript">
5. <!--
6. function mouseClick()
7. {
8. document.write("This is JavaTpoint");
9. }
10. //-->
11. </script>
12. <form>
13. <input type="button" onclick=" mouseClick()" value="Who's this?"/>
14. </form>
15. </body>
16. </html>
MouseOver Event
1. <html>
2. <head>
3. <h1> Javascript Events </h1>
4. </head>
5. <body>
6. <script language="Javascript" type="text/Javascript">
7. <!--
8. function mouseoverevent()
9. {
10. alert("This is JavaTpoint");
11. }
12. //-->
13. </script>
14. <p onmouseover="mouseoverevent()"> Keep cursor over me</p>
15. </body>
16. </html>
Focus Event
1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onfocus="focusevent()"/>
6. <script>
7. <!--
8. function focusevent()
9. {
10. document.getElementById("input1").style.background=" aqua";
11. }
12. //-->
13. </script>
14. </body>
15. </html>
Keydown Event
1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onkeydown="keydownevent()"/>
6. <script>
7. <!--
8. function keydownevent()
9. {
10. document.getElementById("input1");
11. alert("Pressed a key");
12. }
13. //-->
14. </script>
15. </body>
16. </html>
Load event
1. <html>
2. <head>Javascript Events</head>
3. </br>
4. <body onload="window.alert('Page successfully loaded');">
5. <script>
6. <!--
7. document.write("The page is loaded successfully");
8. //-->
9. </script>
10. </body>
11. </html>
Advantages and challenges of event-driven
programming
EDP brings significant advantages to developers and organizations. Here are the key
ones:
While EDP offers plenty of benefits, it also comes with challenges, such as:
Programming languages
You can implement event-driven programs in any programming language. However,
some languages and their ecosystems (e.g., C#, JavaScript, Python, Ruby) naturally
offer more streamlined tools, libraries, and frameworks to simplify the development of
event-driven applications.
Examples: Quix Streams, Kafka Streams, Amazon Kinesis Data Analytics, Google
Dataflow, Apache Beam, Apache Spark, Apache Flink.
Event buses
You can think of an event bus as a routing middleware that receives events and delivers
them to one or more destinations. Event buses are generally well-suited for routing
events from many sources (producers) to many targets (consumers). Unlike event
streaming platforms, event buses usually deliver events in a fire-and-forget way (data
isn’t stored for long periods of time). Another difference is that event buses allow for
better, more efficient event filtering and routing compared to event streaming platforms.
The tradeoff is that event buses are not generally geared toward the same levels of
scalability and huge data volumes as event streaming solutions.
If you’re curious to see how event queuing services compare to event streaming
platforms, check out the following:
Note that event streaming platforms like Apache Kafka also belong to the pub/sub
paradigm, but can support more advanced use cases out of the box. In contrast, pure
pub/sub messaging services mainly focus on one simple task: delivering messages
reliably from producers to consumers.
Event stores
An event store is a specialized database or storage system optimized for storing and
querying event-driven data. Unlike traditional databases that store the current state of
data entities, an event store captures the full series of state-changing events over time.
Each event in the store represents a state transition, carrying information about the
change, its cause, and a timestamp. This sequential log of events enables event
sourcing, a pattern where the application state is reconstructed by replaying the events.
Examples: DynamoDB, Google Datastore, Azure CosmosDB, EventStoreDB, Axon
Server.
We’ll use an online shop as an example. When customers (event producers) submit
orders, OrderPlaced events are generated. An event streaming platform then ingests
these events.
An event store, for long-term storage. This is useful for event sourcing, analytics (e.g.,
analyzing historical order data to understand buying patterns), and auditing.
A payment service, which consumes the events to process customer payments.
Event-oriented architecture in e-commerce
The payment service has an event listener (OrderListener), which listens for events
and triggers an event handler (PaymentHandler) to initiate the payment process. Once
a payment is processed, the service emits a PaymentProcessed event, which is sent
to the event streaming platform, and from there, forwarded to the customer, as payment
confirmation.
In this architecture, as events flow through the system, each service can work
asynchronously, improving scalability and resilience. If, for instance, the payment
service goes down, orders can still be placed. Once the payment service is back, it can
pick up from where it left off, ensuring no order is missed — the event streaming
platform can store OrderPlaced events as long as needed for the payment service to
consume them (plus, they are also stored in the event store).
Bear in mind that this is a simplified architecture — the point was to showcase how EDA
and EDP work together in an easy-to-understand way. In a real-life scenario, the
architecture would be more complex. We’d likely have:
Additional services that follow the EDP paradigm (e.g., fraud detection service, inventory
checker service, recommendation engine to send recommendations to shoppers).
More types of events (for instance, FraudCheckCompleted to signal the result of a
fraud detection process, or InventoryChecked events, which are fired after verifying
product availability). Additionally, all types of events could be pushed to the event store
for long-term storage.
Extra components, such as a stream processing solution (it would allow you, for
instance, to join OrderSubmitted and InventoryChecked events to ensure stock is
available before initiating the payment process).
Open source connectors, so you can easily ingest events from different sources and
stream them to various destination systems.
Online IDE and open source code samples.
Stream processing capabilities.
Multi-environment support, baked in CI/CD, and Git integration.
Built-in observability, e.g., dashboards to monitor metrics and logs, a graphical snapshot
of your app’s architecture.
JS Sample Programs
1.
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>
</body>
</html>
2.
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<p>In this case JavaScript changes the value of the src (source) attribute of an
image.</p>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the
light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the
light</button>
</body>
</html>