<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Idan Biton on Medium]]></title>
        <description><![CDATA[Stories by Idan Biton on Medium]]></description>
        <link>https://medium.com/@idan_42038?source=rss-6db0a70caef4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*07gWfoIkkq51vK0n7-RK7g.png</url>
            <title>Stories by Idan Biton on Medium</title>
            <link>https://medium.com/@idan_42038?source=rss-6db0a70caef4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:07:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@idan_42038/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Event Driven Development on Chrome Extension]]></title>
            <link>https://medium.com/eleos-health/event-driven-development-on-chrome-extension-9fea92ca683?source=rss-6db0a70caef4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fea92ca683</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <dc:creator><![CDATA[Idan Biton]]></dc:creator>
            <pubDate>Sun, 16 Apr 2023 08:29:32 GMT</pubDate>
            <atom:updated>2023-04-16T12:42:35.850Z</atom:updated>
            <content:encoded><![CDATA[<h3>Event Driven Development on Browser Extension</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-r1blj0VZ8t-TSZE0PWMkQ.png" /></figure><p>Imagine this scenario: You are developing a Chrome extension whose main functionality is to listen to changes on the page triggered by the user. For every change, you have a specific action you want to trigger, such as rendering a UI component or triggering an API call.</p><p><strong>How do you best tackle this need?</strong></p><p>Initially, the naive solution would be to create classes and static functions within them that can be used anywhere in your code. Inside these functions, you can trigger or return whatever you need. Although this is an option, it can be cumbersome, especially when you have cross-class actions and data that you need to share. It can be challenging to maintain and debug in such cases.</p><p>A better, more flexible, and organized solution would be to create an event handling mechanism that supports triggering events based on the user’s behavior.</p><p>Chrome comes with <a href="https://developer.chrome.com/docs/extensions/reference/events/">built-in</a> event handlers for common events such as clicking on a button or navigating to a new URL. If you are developing a react application you can even use <a href="https://redux.js.org/">Redux</a> for that. However, sometimes you need to trigger events in more complex scenarios, such as relaying on 3rd party website and waiting for a UI element to be rendered on the site, or when the user logs in or out of the system.</p><p>Here at <a href="https://eleos.health/">Eleos</a>, this was precisely the problem we faced, so we had to come up with an in-house solution for it.</p><p>Please keep in mind that this article covers a specific solution to the above issue. There are many approaches to achieving what we want, and each has its pros and cons.</p><p><strong>Register / Emitter Solution<br></strong>Firstly, if you are not familiar with event-driven development, I highly recommend that you read about it before diving into the solution I suggest here. Having a solid understanding of what we are trying to achieve here is essential. The approach I would like to cover involves two components:</p><ol><li>An Event Emitter class to handle the subscription and emission of events.</li><li>A component or class that is registered for one or more events, and every time this event is fired, an action will be triggered.</li></ol><p><strong>So, let’s dive deeper to how all of this is going to work together.</strong><br>The best way to visualize this is with the following drawing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tT7JWK-Ni0vJtGmTN3T8g.png" /></figure><p>The components need to subscribe (register) for a specific event, and the Event Emitter is responsible for handling these subscriptions and sending (emitting) the events. But wait, what does it mean to emit an event? At the end of the process, there is an action that we want to trigger in response to an event. Now let’s peel back another layer and think about what parameters we need to subscribe to a specific event:</p><ul><li>The event name we want to subscribe to.</li><li>A component id, so we will know which component is registered to a specific event.</li><li>Callback — a function that will be triggered when the event is fired.</li></ul><p>Meaning, on every event we want to be registered on, the above three properties need to be provided.</p><p><strong>Do you have any idea on how can we store the events? </strong><br>We can create an object on the window.top object, where every key will be the name of the event. This way, we can easily track which components are registered for which events, and the value will be an array consisting of objects, as described above.</p><ul><li>Note: We can also put inside our object some other properties for debugging purposes (like URI, page context, etc…)</li></ul><p>Now, let’s dive into some code examples. Let’s say we have a component (it can be a plain JS object, a React component, a JS or TS file), and we want to trigger a particular action when a login event is emitted.</p><pre>import { eventEmitter } from &#39;./eventEmitter&#39;;<br>export default class Example {<br>  constructor() {<br>    ...<br>    this.registerEventListeners();<br>    ...<br>  }<br>  registerEventListeners() {<br>    eventEmitter.subscribe(&#39;login&#39;, &#39;class-id&#39;, () =&gt; {<br>      // do something here<br>    });<br>  }<br>}</pre><p>So, in the example above, we can see that it’s pretty straightforward. We import the eventEmitter object so we can use the subscribe method, subscribe to the &#39;login&#39; event under a specific ID, and bind a callback to execute when the event is emitted.</p><p>But wait, there&#39;s more to it. When are we going to emit the event? Remember, we can emit the event from anywhere in the application, and all the subscribers will get notified. All we need to do is:</p><pre>...<br>eventEmitter.emit(&#39;login&#39;);<br>...</pre><p>All we need to do is to emit the event, with the specific name we subscribed on.</p><p>Great! So now we know how to subscribe and emit events, but what will the event emitter look like? <br>Let’s have a look: Remember how we are going to handle our events object?</p><pre>export default class EventEmitter {<br>  ...<br>  subscribe(name, id, cb) {<br>    if (!window.top.events[name]) {<br>      // in case we still dont have the event key on our object<br>      window.top.events[name] = []; <br>    }<br>    // add new subscription <br>    window.top.events[name].push({id,func: cb});<br>  }<br>  ...<br>}<br></pre><p>Still, pretty straight forward: <br>we are getting the id, name, and callback, checking if there is any value on the events object under the event name, creating an array if it doesn’t exist, and just pushing the object.<br>Now, the last thing we have to cover here is how we are going to implement the event emit function:</p><pre>emit(name, ...args) {<br>  if (!window.top.events[name]) return; // prevents null cases<br>  // loop through all the subscriptions on a the event name<br>  window.top.events[name].forEach((s) =&gt; {<br>    console.log(`Emitting event for event id: ${id}`);<br>    try {<br>      // execute the callback<br>      s.func.call(...args);<br>    } catch (e) {<br>      console.log(`Event failed to emit func ${e}`);<br>    }<br>  });<br>},</pre><p><strong>Note:</strong> we are passing an optional argument, <em>args, </em>in case we need to pass additional args to be called.</p><p>To summarize, we have covered a basic solution for event-driven development in Chrome extensions. We have a class that is responsible for registering and emitting events, and we have other components that can be registered to a specific event. When the event is emitted, the emit function is called and responsible for executing the callback attached to the event.</p><p>Please note that this solution is basic and may not handle some issues that can arise, such as overflowing events. We can handle these issue by creating an event buffer that controls how many events are sent within a specific timeframe. We also need to add conditions to handle null cases or when an event name is empty. Therefore, this solution is a skeleton of how we can implement this and can be improved to better fit our needs.</p><p>I really hope you find this solution helpful. If you have any questions or comments, please feel free to leave them below!</p><p>Until next time :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fea92ca683" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eleos-health/event-driven-development-on-chrome-extension-9fea92ca683">Event Driven Development on Chrome Extension</a> was originally published in <a href="https://medium.com/eleos-health">Eleos Health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>