<?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 Yonatan Schreiber on Medium]]></title>
        <description><![CDATA[Stories by Yonatan Schreiber on Medium]]></description>
        <link>https://medium.com/@char_109?source=rss-16bb29067fe2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_9_VaZa6W7XE4tz_.jpg</url>
            <title>Stories by Yonatan Schreiber on Medium</title>
            <link>https://medium.com/@char_109?source=rss-16bb29067fe2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:46:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@char_109/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[JS event emitter, get and set, and combining them to create something really cool.]]></title>
            <link>https://medium.com/@char_109/js-event-emitter-get-and-set-and-combining-them-a54172f6daf8?source=rss-16bb29067fe2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a54172f6daf8</guid>
            <category><![CDATA[defineproperties]]></category>
            <category><![CDATA[eventemitter]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yonatan Schreiber]]></dc:creator>
            <pubDate>Sat, 16 Apr 2016 13:56:07 GMT</pubDate>
            <atom:updated>2016-04-18T16:17:03.429Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>How to write a simple event emitter, how to use object property’s getters and setters, and how to mix them together for something way cooler.</strong></h4><p>In this article we will learn how to build a really cool non-conventional interface for event emitter. It will look like this:</p><pre>function notifyCook(mainDish) {<br>  console.log(&#39;Hey cook, can you prepare &#39; + mainDish + &#39;?&#39;);<br>}<br>function notifyGuests() {<br>  console.log(&#39;Hey all, don&#39;t forget today&#39;s dinner!&#39;);<br>}</pre><pre>//subscribe to events (named &#39;dinner&#39;) with cb (notifyCook)<br>myEmitter.dinner = notifyCook; </pre><pre>//another subscription won&#39;t override the previous one<br>myEmitter.dinner = notifyGuests;</pre><pre>//emit &#39;pasta&#39; to all listeners<br>myEmitter.dinner(&#39;pasta&#39;);</pre><pre>//logs:<br>//&#39;Hey cook, can you prepare pasta?&#39;<br>//&#39;Hey all, don&#39;t forget today&#39;s dinner!&#39;</pre><p>In the process of making it, we will see how to write a simple event emitter. If you think that’s a piece of cake — you are right! Jump to the second part and read about ES5 <em>getters </em>and <em>setters, </em>using <em>Object.defineProperty </em>and other methods. If you already know that — cool, your’e a champ! Jump to the third part (full code at the end), and see a new and interesting way to combine them both, I promise it will be thought-provoking.</p><h3>Event emitter in Javascript</h3><p>Event emitter is sort of a pattern widely all over the JS , from jQuery to angular, flux or node. If you&#39;ve written JS you&#39;ve probably used it already. But how does it work? Native JS does not support events!</p><p>First, lets look at the interface for a regular emitter:</p><pre>myEmitter.on(&#39;dinner&#39;, (mainDish) =&gt; {<br>  console.log(&#39;dinner is served with: &#39; + mainDish );<br>});</pre><pre>myEmitter.emit(&#39;dinner&#39;, &#39;lasagna&#39;);</pre><pre>setTimeout( function(){<br>  myEmitter.emit(&#39;dinner&#39;, &#39;pasta&#39;);<br>}, 1000);</pre><p>In this example, you have an object that will be your instance of the emitter (<em>myEmitter</em>), then you subscribe to “dinner<em>” </em>with<em> on </em>method and provide a callback to handle it. Every time your emitter will <em>emit </em>this event, the callback function will get called.</p><p>In order to build an emitter like that, we just need to create an emitter object, that will have <strong><em>on</em></strong><em> </em>and <strong><em>emit</em></strong><em> </em>methods, and store all of the callbacks in a property named <em>_subscriptions.</em></p><p><em>_subscriptions</em> will be an object whose keys are the event names, and their values will be an array of all the registered callbacks for that event.</p><pre>const emitter = {<br>  _subscriptions:{<br>    //someEvent:[cb1, cb2]  //<br>  },<br>}</pre><p><strong><em>on</em></strong> method will add keys and values to <em>_subscriptions:</em></p><pre>on(name, func){<br>  //check for the existence of <br>  // this event in _subscriptions or init it<br>  this._subscriptions[name] = this._subscriptions[name] || [];<br>  //push the callback that array<br>  this._subscriptions[name].push(func);<br>},</pre><p>last, add <strong><em>emit</em></strong> that will call all callbacks when triggered:</p><pre>emit(name, …args){<br> if(!this._subscriptions[name]){return; }<br> this._subscriptions[name].forEach(f=&gt;f(…args))<br>}</pre><p><a href="https://gist.github.com/yonatanmn/49e5b4d912f6cb7be467de2ca7ec7444#file-simpleemitter-js">full code</a> for this simple event emitter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*Ko5wdMygUD1_gwcWT8W9cA.jpeg" /></figure><h3>Property definition</h3><p>Normally you would create objects and initiate their properties like so:</p><pre>let obj = {<br>  key1: &#39;john&#39;<br>};<br>obj.key2 = &#39;smith&#39;;</pre><p>‘key1’ and ‘key2’ are <em>writable</em> (you can override their value by another assignment), and <em>enumerable </em>(you’ll see all of the keys when calling <em>Object.keys(obj)</em> and you’ll iterate over the with <em>for..in</em> loop). Read more about it <a href="http://arqex.com/967/javascript-properties-enumerable-writable-configurable">here</a>.</p><p>They also have normal read and write:</p><pre>obj.key1 // ‘john’<br>obj.key1 = ‘adam’;<br>obj.key1 // &#39;adam&#39; </pre><p>The cool thing here is that you can change all that! that’s done with <em>Object.defineProperty\ies :</em></p><pre>Object.defineProperty(obj, &#39;key1&#39;, descriptor);<br>//OR<br>Object.defineProperties(obj, {<br>  &quot;key1&quot;: descriptor<br>},</pre><p><strong><em>descriptor</em></strong><em> </em>is another object, that will allow you to configure exactly how this property should behave. You can choose value, set it to be <em>non-writable</em>, or <em>non-enumerable</em>, and whether this configuration is later <em>configurable</em>. In this article I’ll focus at two other properties of the descriptor, read more about the descriptor (and about configurable, enumerable, value and writable) <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties">here</a>.</p><p>The descriptor has two more methods: <strong><em>get</em></strong> and <strong><em>set</em></strong>. Normally, when you call obj.prop, you expect to get the value of that prop, but you can alter that:</p><pre>var obj = {key1: &#39;john&#39;}<br>Object.defineProperty(obj, &#39;key2&#39;, {<br>  get: function(){<br>    return &quot;John is way too normal for me&quot;;<br>  }<br>});<br>// OR when you init obj:<br>var obj = {<br>  key1: &#39;john&#39;,<br>  get key2(){ ... }<br>}</pre><pre>obj.key2 = &quot;I&#39;m John too&quot;;<br>console.log(obj.key2) // logs: &quot;John is way too normal for me&quot;;</pre><p>We can also play with the assignment:</p><pre>var obj = {};<br>var name = ‘John’;<br>Object.defineProperty(obj, ‘key2’, {<br> set: function(val){<br>   name = val + val;<br> },<br> get: function(){return name}<br>});</pre><pre>console.log(obj.key2) // logs name: &quot;John&quot;;<br>obj.key2 = &quot;John&quot;; // changes name;<br>console.log(obj.key2) // logs: &quot;JohnJohn&quot;;</pre><p>Notice that <em>name</em> is not internal to obj.key2, you cannot have <em>value</em> of a property if you define setters and getters (nor <em>writable </em>definition). Also pay attention that <em>Object.defineProperty</em> sets <em>enumerable</em> and <em>configurable</em> to false unless otherwise specified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhUV-TzEQASVNdHev3ix0Q.jpeg" /></figure><h3>Cool event emitter</h3><h4>Mixing getters-setters with eventEmitter</h4><p>Lets use what we’ve learned about property descriptors in order to create a new interface for our event emitter. What I’d like to see, is something like this:</p><pre>//use assignment (set) as &#39;on&#39;<br>myEmitter.dinner = function(){<br>  console.log(&#39;dinner is served&#39; );<br>};<br>//second assignment<br>myEmitter.dinner = function(mainDish){console.log(mainDish)} </pre><pre>// getters will be &#39;emit&#39;<br>myEmitter.dinner(&#39;pasta&#39;); <br>// logs: <br>// &#39;dinner is served&#39; <br>// &#39;pasta&#39; </pre><p>To do this, let’s create a function named <strong><em>emitize</em></strong> that will generate those unique emitter-events. This function will also hold <strong><em>_subscriptions</em></strong> a <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Closures">closured</a> variable that will hold all of the subscribed callbacks.</p><pre>function emitize(obj, eventName) {<br>  let _subscriptions = new Set();  <br>  Object.defineProperty(obj, eventName, getterSetterDescriptor)<br>};<br>//usage: <br>let myEmitter = {};<br>emitize(myEmitter, &#39;dinner&#39;)</pre><p>Iv’e defined <em>_subscriptions</em><strong><em> </em></strong>with es6 — <strong><em>Set</em></strong>, since we it will freely spare any callback duplication, and will be easier to remove them later on (the alternative is using array: ‘<em>_subscriptions = []</em>’, ‘<em>_subscriptions.push()’</em> and `<em>_subscriptions = _subscriptions.filter(f =&gt; f !== func)</em>`, thx <a href="https://twitter.com/jacoborus">@jacoborus</a> for the tip).</p><p>Now, in <em>getterSetterDescriptor</em>, we’ll add <em>get</em> and <em>set</em> with logic from the simple <em>eventEmitter</em> above:</p><pre>function emitize(obj, eventName) { <br>  let _subscriptions = new Set();<br>  Object.defineProperty(obj, eventName, {<br>    get(){<br>      return function emit(...args){<br>        _subscriptions.forEach(f=&gt;f(...args));<br>      };<br>    }, <br>    set(cb) {<br>      _subscriptions.add(cb);<br>    },<br>  })<br>};</pre><p><strong><em>get</em></strong> returns a function, so it will be able to receive arguments. If we want to add <strong><em>off</em></strong> functionality to this, we can just use <em>Object.defineProperty</em> again, this time over the internal <em>emit</em> function! Here’s the full code (<a href="https://gist.github.com/yonatanmn/49e5b4d912f6cb7be467de2ca7ec7444">gist here</a>):</p><h3>Full code</h3><pre>function emitize(obj, eventName) {<br> let _subscriptions = new Set();<br> Object.defineProperty(obj, eventName, {<br>   set(func) {<br>     _subscriptions.add(func); <br>   }, <br>   get() { <br>     var emit = (…args)=&gt;{<br>       _subscriptions.forEach(f=&gt;f(…args)); <br>     };<br>   <br>     Object.defineProperty(emit, ‘off’, {<br>       set(func) { _subscriptions.delete(func); },<br>       get() { _subscriptions = new Set(); } <br>     });<br>   <br>     return emit;<br>   }<br> });<br>}</pre><pre>//usage:</pre><pre>var obj = {};<br>emitize(obj, &#39;x&#39;);</pre><pre>function log(v) {<br>  console.log(v);<br>}<br>function logPlus1(v) {<br>  console.log(v + 1);<br>}</pre><pre>obj.x = log; //subscribe to events (named &#39;x&#39;) with cb (log)</pre><pre>//another subscription won&#39;t override the previous one<br>obj.x = logPlus1;</pre><pre>obj.x(9); //emits &#39;9&#39; to all listeners;<br>//logs:<br>//&#39;9&#39;<br>//&#39;10&#39;</pre><pre>obj.x.off = logPlus1; //unsubscribe logPlus1<br>obj.x.off; //or unsubscribe from all callbacks</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*AniLXGeHohMhlkoAx45nTw.jpeg" /></figure><p>Hope you enjoyed this article, and maybe even learned something new. Is this interface for eventEmitter really usable or is it too non-regular and confusing? I don’t know, it’s up to you to decide, but when you learn a new tool—cool implementations starts to follow.</p><p>If you liked it — Share, subscribe and follow <a href="https://twitter.com/char_109">my twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a54172f6daf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>