<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>subscribe &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/subscribe/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Wed, 24 Dec 2014 16:41:05 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://jessewarden.com/wp-content/uploads/2016/08/cropped-Lambda2-32x32.png</url>
	<title>subscribe &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Message Systems in Programming: Part 7 of 7 &#8211; Conclusions</title>
		<link>https://jessewarden.com/2014/12/message-systems-in-programming-part-7-of-7-conclusions.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Wed, 24 Dec 2014 16:01:59 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[callbacks]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[eventemitters]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[promises]]></category>
		<category><![CDATA[publish]]></category>
		<category><![CDATA[pubsub]]></category>
		<category><![CDATA[streams]]></category>
		<category><![CDATA[subscribe]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=4733</guid>

					<description><![CDATA[Conclusions As you can see, each messaging system has pro&#8217;s and con&#8217;s. Also, each can, and often is, used in tandem with each other. They aren&#8217;t always stand alone, and many are used in the same code base. As you better understand the basics of messaging systems, you can more easily make your Object Oriented [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a name="conclusions"></a></p>
<h2>Conclusions</h2>
<p>As you can see, each messaging system has pro&#8217;s and con&#8217;s. Also, each can, and often is, used in tandem with each other. They aren&#8217;t always stand alone, and many are used in the same code base. As you better understand the basics of messaging systems, you can more easily make your Object Oriented code bases easier to encapsulate. It also makes it easier when using Design Patterns to have disparate parts of the code talk to each other in a flexible way.</p>
<p><span id="more-4733"></span><a name="whywritethisandotherrandomnotes"></a></p>
<h2>Why Write This and Other Random Notes</h2>
<p>For context, the whole reason I wrote this article is I had no idea why Promises were so lauded by JavaScript developers. I also had no clue what Streams were and if they were valuable or not. Coming from Flash and Flex, Events worked just fine as a core messaging system for years. There were a few who used Signals, and a few pumped strangeness across the global, and not well known loaderInfo.sharedEvents.</p>
<p>Many articles online explained what Promises and Streams were, but none explained why they mattered, nor why I should use them over some other system. WHY AM I DOING THIS!? The Stream guys are the worst. They use computer science terminology that&#8217;s extremely obtuse &#038; unapproachable, and they assume these words plastered by themselves is enough to justify their usage. &#8220;The Ancients used Stargates, or course we&#8217;re supposed to use them as well&#8221;.</p>
<p>Before writing this, I didn&#8217;t realize CustomEvent&#8217;s only worked with DOM elements. Polymer&#8217;s done a good job at this via their fire method, no doubt, butâ€¦ wow. Talk about having it rough. Those poor JS devs.</p>
<p>I also didn&#8217;t realize JQuery, to solve the above, gave them callbacks for async programming, and basically introduced the concept of Promises to the JS world. I was in my spoiled world of events that worked in visual components or in data components. What I didn&#8217;t realize was that when it came to orchestration, the JQuery crowd actually had a much easier time of it. Once you have more than 2 async events, you start having to hunt through the code to mentally map what function fires what event and what function handles that. When you start chaining those thingsâ€¦ good luck. With Promises, it&#8217;s all centralized, making the code much easier to read. AS3 is basically like TypeScript or Dart; and thus we were all willing to have more verbose code because of strong typing&#8217;s value. Anything that can help make it less more verbose, like Promises, would of been a god send in some of the larger enterprise code bases I&#8217;ve been thrust into fixing.</p>
<p>Sadly, Flash Player garbage collector worked extremely differently post Flash Player 8, so things like local variables can&#8217;t just magically &#8220;exist&#8221; like they do in JavaScript. This was so deeply ingrained, it made it quite hard for me to &#8220;get&#8221; why Promises actually work, and how to clean them up.</p>
<p>I was also confused why <a href="https://docs.angularjs.org/api/ng/service/$q">Angular&#8217;s $q</a> differed so much from the official <a href="https://github.com/kriskowal/q">Q</a>. I then realized they wrote their own version of it. Some of the more important features, however, of long stack traces would of made many people&#8217;s lives easier. The biggest frustration I&#8217;ve had learning the ins and outs of Promises this year was completely useless stack traces. As as spoiled Flex developer, I&#8217;ve watched Chrome in the past 3 years insanely improve it&#8217;s runtime errors and stack traces. None of which seems to make working with nested Promises that much easier when the developers use anonymous functions everywhere. This has completely changed the way I code Promises in JavaScript if not using a Promise library (most of my work is Angular&#8217;s $q so when creating Promise chains, I avoid anon functions like t3h plague if I can, and try/catch throw like a mofo). </p>
<p>After doing a lot of orchestration in larger code bases from a data perspective, Promises really started to make sense once I started doing the same work in JavaScript. Remember, this was before Node, and all Factory / data orchestration had to be done on the client WITHOUT something like <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html">Cocoa&#8217;s CoreData</a>. Once you put Node into the picture, this gets a TON easier. No matter how complicated the Java/.NET developers make your life, you can get yourself the 1 API call you need, with no parsing, in about 2 hours. That. Is. Hot. Shit.</p>
<p>Now, I still don&#8217;t get Streams on the client beyond gaming, or an improved event system for component frameworks (like Polymer or Angular UI). I&#8217;m attempting to <a href="https://github.com/JesterXL/fun-with-dart-streams">recreate Final Fantasy 6&#8217;s battle system as a research exercise</a>. In doing so, I&#8217;ve played with various Stream facets in Dart as well as Frappe (which works more like Bacon/RX).</p>
<p>Although research is still on going, for client side, Streams are way easier to deal with than Events, GUI or not. It took me 3 months to get comfortable, but once I got it, there&#8217;s basically no going back to Events if it I can help it. I&#8217;m not sure how to resolve that for Polymer as I&#8217;m a huge fan of the project, want to use it, but I&#8217;ve already lived through the world of Events and am over it. One of these days I need to hack into it and see if there&#8217;s an easier way to convert &#8220;fire&#8221; and it&#8217;s ilk to Streams vs. just using the common adapters on top. Implementing pause and cancel is where the real work would be.</p>
<p>It&#8217;d be nice of application frameworks would implement these, such as <a href="http://angular-ui.github.io/bootstrap/">Angular UI</a>. A few hours playing with Polymer&#8217;s ObservableList and you&#8217;ll be hooked. Array&#8217;s are too low level for creating truly dynamic application UI controls.</p>
<p>That said, in the data layer, especially when Node comes into play to support your front end REST API, I don&#8217;t have many disparate async events. The value for Streams beyond the GUI layer doesn&#8217;t seem helpful, and smaller promise chains work fine.</p>
<p>In Node, however, the complete opposite. If I had Node back in my Flex consulting days, things would have been much simpler. Waiting weeks, sometimes never, getting the API&#8217;s to be simpler, moved a ton of technical debt on the client side to compensate for this, with large Facade layers over the data. Orchestrating many different API&#8217;s, often from different servers with different request and response formats is ripe for Streams to make them easier to work with. Even better is that Node is in a language I already know: JavaScript. I can use the same libraries in the same build stack on the same CI server.</p>
<p>And yet, even here I struggle to convince others. My guess is they just haven&#8217;t spent 6 months like I have playing with Streams and Promises simply to write a blog post.</p>
<p>I will say the need for a Stream spec is pretty clear. It makes all the Promise libraries immediately understandable in how they work. You have the exact opposite problem with Streams. Sadly, I don&#8217;t think Streams will catch on as hard as Promises do. Promises solve such a core problem in ajax and only have a small native footprint to code whereas Streams require a TON of things.</p>
<p>First off, most browsers, even nightlies, barely scratch the surface of what RX/Bacon/Dart have for functional array methods. We&#8217;ve seen how long it takes browser vendors to acknowledge their value and add them in natively hence why lodash or underscore still reign supreme in most peoples tool belts.</p>
<p>Second, they rely a common expectation of how Streams work and the consensus, especially on cold vs. hot, and Observables vs. Properties, just ain&#8217;t there either yet. Until that mess settles down, the libraries will be the go-to places to embrace Streams. Well, except in Dart where they are in there out of the box. It&#8217;s still unclear to me in Polymer where Events end and Streams begin. Need more time to play.</p>
<p>One small note, I used a variety of text editors to write this post over the past 6 months. After about 4 pages, even if the most recent version of <a href="https://wordpress.org/">WordPress</a> with the improved single page scrolling, it&#8217;s still brutal and version control is confusing. I tried <a href="http://25.io/mou/">Mou</a>, my current favorite Markdown editor, but after about 10 pages performance quickly went down. I gave a few random text editors for the Mac a try and finally settled on <a href="http://www.literatureandlatte.com/scrivener.php">Scrivener</a>. It&#8217;s not safe with my HTML tags as it keeps upper casing b and pre tags, and breaks hyperlinks with it&#8217;s weird double-quote choice, but I&#8217;m sure it&#8217;s a setting I don&#8217;t know yet. Either way, at nearly 20,000 words, ZERO performance problems. Faster to boot up and use compared to Word for Mac. Props to <a href="https://plus.google.com/+CliffHall/posts">Cliff Hall</a> for the recommendation.</p>
<p><a name="specialthanks"></a></p>
<h2>Special Thanks</h2>
<p>Thanks to <a href="http://joelhooks.com/">Joel Hooks</a>, <a href="https://twitter.com/trxcllnt">Paul Taylor</a>, <a href="https://plus.google.com/+danschultzonline/posts">Dan Schultz</a>, and the <a href="https://plus.google.com/communities/114566943291919232850">Dart community</a> for answering my questions.</p>
<p>Art:</p>
<ul>
<li><a href="http://clementsauve.deviantart.com/art/Ao2-40th-day-Antennas-158537814">Ao2 40th day: Antennas</a></li>
<li><a href="http://2501sodapop.deviantart.com/art/grad-lvl-31526040">grad lvl</a></li>
</ul>
<p><a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-6-of-7-streams.html" class="btn btn-primary">&lt;&lt; Part 6 &#8211; Streams</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Message Systems in Programming: Part 6 of 7 &#8211; Streams</title>
		<link>https://jessewarden.com/2014/12/message-systems-in-programming-part-6-of-7-streams.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Wed, 24 Dec 2014 16:01:03 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[callbacks]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[eventemitters]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[promises]]></category>
		<category><![CDATA[publish]]></category>
		<category><![CDATA[pubsub]]></category>
		<category><![CDATA[streams]]></category>
		<category><![CDATA[subscribe]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=4731</guid>

					<description><![CDATA[Streams Streams are merely Array&#8217;s that emit change events through a callback when items are added to it. That&#8217;s it. People try to make them sound magical, complicated, or like some core savior technique of programming life. They&#8217;re not. They&#8217;ve been around long before me in networking code. They&#8217;re how Github visualizes different branches. They&#8217;re [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a name="streams"></a></p>
<h2>Streams</h2>
<p>Streams are merely Array&#8217;s that emit change events through a callback when items are added to it.</p>
<p>That&#8217;s it.</p>
<p><span id="more-4731"></span>People try to make them sound magical, complicated, or like some core savior technique of programming life. They&#8217;re not. They&#8217;ve been around long before me in networking code. They&#8217;re how <a href="https://github.com/">Github</a> visualizes different branches. They&#8217;re just Arrays that emit change events to a callback you can filter before you get the event. You don&#8217;t even have to use events; you could just use any value you want. Most implementations also play nice with Promises.</p>
<p>Streams are like Events, except you can use Array methods on them BEFORE the event is given to the callback handler, and listeners can pause further events from being emitted. They take the asynchronous flattening abilities of Promises, the filtering abilities of functional Arrays (think all those Array methods on Underscore), and the 1 to many broadcast abilities of Events. They have a flattening power of their own once you start merging streams together. When used with Promises, you can work around the race conditions much like you do for Events.</p>
<p>As a side note, Node&#8217;s <a href="http://nodejs.org/api/stream.html">current version of Streams</a> at the time of this writing is actually based on EventEmitter.</p>
<p>For example, you&#8217;ll use a command to get the weather in JSON:</p>
<pre lang="dart">String url = 'http://api.openweathermap.org/data/2.5/weather?q=Richmond,VA&units=imperial';
EventStream links = new EventStream(HttpRequest.request(url, responseType: 'json').asStream());
links.listen((data)
{
	print(data.response);
});</pre>
<p>In <a href="https://www.dartlang.org/">Dart</a> using <a href="https://github.com/danschultz/frappe">Frappe</a>, you use listen to hear about when streams fire events. Here&#8217;s <a href="https://github.com/Reactive-Extensions/RxJS">RxJS</a> doing the same thing:</p>
<pre lang="javascript">function getWeather()
{
    return $.get('http://api.openweathermap.org/data/2.5/weather?q=Richmond,VA&units=imperial')
    .promise();
}
var currentWeather = distinct.flatMapLatest(getWeather);
currentWeather.subscribe(function(data)
{
   	console.log(data);
});</pre>
<p>And in <a href="https://github.com/baconjs/bacon.js/">Bacon.js</a>, another rad, and less intimidating, JavaScript Stream library:</p>
<pre lang="javascript">function getWeather()
{
    var promise = $.get('http://api.openweathermap.org/data/2.5/weather?q=Richmond,VA&units=imperial')
    .promise();
    return Bacon.fromPromise(promise);
}
getWeather().onValue(function(data)
{
	console.log(data);
});</pre>
<p>Like addEventListener, you pass in a callback to fire when they happen. Like events, listen will pass in the parameter the Stream emits. While events have the convention to pass events as the single and only parameter, many who are used to smaller promises, or putting streaming code on top of existing promise code, more primitive values along with multiple values may be common, and that&#8217;s ok. JavaScript will work.</p>
<p><A name="stronglytypedstreams"></a></p>
<h3>Strongly Typed Streams</h3>
<p>Dart however will give you compile warnings if you don&#8217;t match the types. If you don&#8217;t use strong-typing and expect a certain type, you&#8217;ll get a runtime exception.</p>
<p>For example, this is good:</p>
<pre lang="dart">StreamController<String> controller = new StreamController<String>();
EventStream<String> nameChanges = new EventStream<String>(controller.stream);
nameChanges.listen((String someName)
{
	print("someName: $someName");
});
controller.add("Jesse");</pre>
<p>This will give you a compiler warning:</p>
<pre lang="dart">StreamController<String> controller = new StreamController<String>();
EventStream<String> nameChanges = new EventStream<String>(controller.stream);
nameChanges.listen((int someName)
{
	print("someName: $someName");
});
controller.add("Jesse");</pre>
<p>And this will compile just fine, yet blow up at runtime:</p>
<pre lang="dart">StreamController<String> controller = new StreamController<String>();
EventStream<String> nameChanges = new EventStream<String>(controller.stream);
nameChanges.listen((someName)
{
	int oldAge = 70 + someName;
	print("oldAge: $oldAge");
});
controller.add("Jesse");
//	Exception: Uncaught Error: type 'String' is not a subtype of type 'num' of 'other'.
//    Stack Trace:
//    #0      int.+ (dart:core-patch/integers.dart:15)</pre>
<p>#inb4HaxeDoesntHaveThisProblem</p>
<p>The strong-typing helps both while coding, when you start merging/piping streams or using Composition. It also helps in helping the compiler create faster JavaScript at runtime. This helps when writing Dart for the client or for the server (just like JavaScript in the client and Node).</p>
<p><A name="streamsbeingdonevsinfinite"></a></p>
<h3>Streams Being &#8216;Done&#8217; vs. Infinite</h3>
<p>If you map your mind to Streams firing multiple times like an event, they are immediately familiar. Here&#8217;s Bacon creating an event stream (a Stream of Events, usually from something that spits out events from addEventListener type deal):</p>
<pre lang="javascript">$('#someButton').asEventStream('click').subscribe(function(mouseEvent)
{
	console.log("mouseEvent:", mouseEvent);
});</pre>
<p>&#8220;JQuery, find me this button hidden in the DOM soup, create a Stream from it&#8217;s click addEventListener, and let my anonymous function know about events as they are added in the Stream, kthxbai!&#8221;</p>
<p>Since Events work very similarly to Streams, most Streaming libraries have these kinds of converters to quickly make them work like Streams, yet retain the original Event interface. Lowers the barrier of entry. </p>
<p><A name="filtering"></a><H3>Filtering</h3>
<p>As previously mentioned unlike Events, you can filter them BEFORE you&#8217;re subscribe/listen function is fired. For example, when designing a game, I only want to know about events where a particular character is ready so I can redraw the UI:</p>
<pre lang="dart">initiativeStream.where((InitiativeEvent event)
{
	return event.type == InitiativeEvent.CHARACTER_READY;
})
.listen((event)
{
	print("character ready: ${event.character}");
});</pre>
<p>You&#8217;ll notice I&#8217;m treating the initiativeStream here as an Array, using a where function. If you&#8217;re not familiar with uber functional Array stuff, check out <a href="http://underscorejs.org/#where">Underscore&#8217;s definition of where</a> or try your hand at the <a href="http://reactive-extensions.github.io/learnrx/">low-level implementations tutorial</a> to understand why you even need or would want this stuff.</p>
<p>What if I didn&#8217;t have filtering abilities? You&#8217;d write crap like this:</p>
<pre lang="dart">initiativeStream.
.listen((event)
{
	if(event.type == InitiativeEvent.CHARACTER_READY)
	{
		print("character ready: ${event.character}");
	}
});</pre>
<p>Bottom line, every time an initiative event is fired, only let me know about the ready events. Cool. However, anyone who has played RPG games know&#8217;s there is one issue with the above; I&#8217;ll hear about the Monster events as well. Again, without functional Array methods:</p>
<pre lang="dart">initiativeStream.
.listen((event)
{
	if(event.character is Player)
	{
		if(event.type == InitiativeEvent.CHARACTER_READY)
		{
			print("character ready: ${event.character}");
		}
	}
});</pre>
<p>Machete don&#8217;t write nested ifs.</p>
<p>With functional Arrays, you can filter on filters. We&#8217;ll ensure it&#8217;s the correct event type, only from Players, and convert it so we get the player out since that&#8217;s all we care about:</p>
<pre lang="dart">initiativeStream.where((InitiativeEvent event)
{
	return event.type == InitiativeEvent.CHARACTER_READY;
})
.where((InitiativeEvent event)
{
	return event.character is Player;
})
.map((InitiativeEvent event)
{
	return event.character;
})
.listen((Player player)
{
	print("player is ready: ${character}");
});</pre>
<p>Good stuff. Remember, though, like events, that listen callback will get called multiple times if more things come into the stream. The docs for the various libraries and runtimes are confusing in that many methods will go &#8220;when the stream is done&#8221;. Done is a strange word because if you never un-listen, is it REALLY done? The whole chain above will get executed if 5 seconds later when another IntiativeEvent is pumped through the system. In implementations like Dart&#8217;s, they actually can emit a &#8216;done&#8217; type of event if you wish to know. However, for UI Streams like the Bacon one I gave above, it&#8217;s never really done because the user could click anytime they want.</p>
<p><A name="mergingandpipingstreams"></a></p>
<h3>Merging and Piping Streams</h3>
<p>Many systems use Streams to link a series of inputs and outputs together with very little code. The most common are string operations on the command line in many Unix systems.</p>
<pre lang="unix">$ ps aux | grep conky | grep -v grep | awk '{print $2}' | xargs kill</pre>
<p>To read that in Jesse Engrish, &#8220;List my running processes, throw that list to a search program called grep, and look for &#8216;conky&#8217; within it, exclude all the lines that don&#8217;t match, use a program called awk to snag out the process ID (called a PID) I need from the string, and throw that PID at xargs kill which will stop the process from running. Notice in this case the pipe is literally a pipe vs. a &#8220;Stream.pipe()&#8221; function. You can imagine what happens if someone starts changing &#8216;conky&#8217; and keeps re-running ps auxâ€¦ continuously streaming pipes in hot action, sucka!</p>
<p>It should be noted that Node <a href="http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options">already has a way to pipe streams together</a> which is more performant and shorter to write:</p>
<pre lang="javascript">var errorsFromClient = getErrorPostStream();
var errorLogFile = fs.createWriteStream('error.log');
errorsFromClient.pipe(errorLogFile);</pre>
<p>You&#8217;ll often &#8220;pipe&#8221; the data from one command to the next, whether manually doing it like I showed, or using the platform/libraries built in pipe command.</p>
<p>Streams can also indicate a &#8220;series of events&#8221;. As previously mentioned, Node.js uses streams much in this fashion using EventEmitters. They&#8217;re basically Events that have start, progress, and stopping points and are called Streams (api in flux at time of this writing).</p>
<p>Finally, Streams can be merged. One use case is when you&#8217;re building an orchestration on the Node server to have 4 API calls be 1 to make the client side code easier to write and not have to worry about authentication &#038; parsing details. Another use case is flattening all the Events on a client that cause the same thing to happen.</p>
<p>For example, you know how when building a login form, either clicking the &#8220;Login&#8221; button will submit the form as well as hitting enter while within the password field? You can merge Streams to make that easier to read. Here&#8217;s a Bacon example:</p>
<pre lang="javascript">var loginButton = $("#loginButton").asEventStream("click");
var loginField = $("#passwordField").asEventStream("click");
var loginStream = loginButton.merge(loginField);
loginStream.onValue(function()
{
	$.post('server.com/login');
});</pre>
<p>The same technique can be used server-side or client side to flatten orchestrations when making many REST API calls. This example first loads the client&#8217;s location using a geoIP service (uses the server vs. navigator.geolocation) to identify the user&#8217;s latitude and longitude, ensures it&#8217;s not called more than every half a second, parses the result into a Point object, loads the weather passing in the latitude and longitude, and ensures the result isn&#8217;t the same as last time, else it ignores it:</p>
<pre lang="dart" line="1">GetLocation locationService = new GetLocation();
EventStream getWeatherFromGeoIP = new EventStream(locationService.asStream())
.debounce(new Duration(milliseconds: 500))
.map((HttpRequest request)
{
	return new Point(request.response.lat, request.response.lon);
})
.asyncMap((Point point)
{
	return getWeather(point.x, point.y);
})
.distinct();
getWeatherFromGeoIP.listen((num weather)
{
	print("It is $weather degrees.");
});

new Timer(new Duration(minutes: 1), ()
{
	locationService.getLocation();
});</pre>
<p>If you didn&#8217;t catch it, check out line #10 (getWeather method) where the Stream supports asynchronous filters as well, specifically Promises. This is also an option where you can use Composition vs. Merging of Streams.</p>
<p>Here&#8217;s another example with a less linear approach where you can see different streams emitting events at different times, in this case, Monsters and Players attacking each other. One is controlled by AI, the other controlled by the user:</p>
<pre lang="dart">EventStream<AttackResult> monsterAttacks = new EventStream(new StreamController<AttackResult>().stream);
EventStream<AttackResult> playerAttacks = new EventStream(new StreamController<AttackResult>().stream);
EventStream<AttackResult> attacks = monsterAttacks.merge(playerAttacks);
attacks.listen((AttackResult result)
{
	textDropper.addTextDrop(result.attackTarget, result.hitValue);
});</pre>
<p>In the case of chat applications which will do a request/response in the background, but a real-time socket when you have the application active, like on your phone with <a href="https://www.hipchat.com/">HipChat</a>. Two different application modes, your data comes out the same:</p>
<pre lang="dart">EventStream<ChatMessage> ajaxStream = new EventStream(new StreamController<ChatMessage>().stream);
EventStream<ChatMessage> socketStream = new EventStream(new StreamController<ChatMessage>().stream);
EventStream<ChatMessage> messages = ChatMessage.merge(socketStream);
messages.listen((ChatMessage message)
{
	querySelector("#chatField").text = message.text;
});</pre>
<p><A name="noteonobservables"></a></p>
<h3>Note On Observables</h3>
<p>While not always mentioned in some Stream API&#8217;s, an Observable is often included when describing Stream API&#8217;s. All they&#8217;re referring to is the Observer pattern applied over an Array, like a Collection. When you do an arrayInstance.push(), there are no change events. No one else knows that the Array changed unless you use a CustomEvent or pub sub to inform others that it changed. Thus, many use the Observer pattern to wrap Array&#8217;s to create Collections; similar API, except you know what changed, where, and how. Backbone&#8217;s <a href="http://backbonejs.org/">Model and Collection classes</a> are perfect examples of this.</p>
<p>Streams, however, represent the data coming into their Array IN ORDER, even when merged streams. This is why all the cray cray Functional Array stuff works on top, no matter how many Streams you use. Now, your listen function may fire only 1 time because your Array/Stream only has 1 data item. As that data &#8220;changes&#8221; however, you&#8217;ll get more events. Hence why they call it an Observable; somewhere deep in the API is the Observer pattern watching a piece of data, usually passed by ref if possible to emulate Promise state encapsulation.</p>
<p>You&#8217;ll also sometimes see <a href="http://www.dartdocs.org/documentation/frappe/0.3.0+1/index.html">Properties</a>. These are sometimes like Observables depending on the library. Other times they&#8217;re like Promises that cache data.</p>
<p>Be aware of the context of Observable. This is one of the reasons Streams are so hard to grok because people often cite Observable in many different ways without defining what the hell it actually is. For example, the RX family calls Streams:</p>
<blockquote><p>RxJS = Observables + Operators + Schedulers.</p></blockquote>
<p>Except it&#8217;s not. That quote form the docs is actually talking about RX, not Streams. You could be easily fooled (I was) to think using a Stream library called RX would be defined as Observers, Operators, and Schedulers.</p>
<p>Streams ARE an Observable. Like the Observer pattern: &#8220;This thing changed, let the world know.&#8221; When you change a Stream, it lets the world know. You use functional Array methods to &#8220;operate&#8221; on that data. Operators == Functional Array Methods. And putting Schedulers there makes it sound like Streams are one third made up of these scheduler things. Except their not. It&#8217;s 1 plugin out of the 11 RX hasâ€¦ and that&#8217;s only for some advanced unit testing/functional testing mojo. Most of us ain&#8217;t going to use that.</p>
<p>If you think of a Stream as an Array that emits events when it changes, and thus is an Observer, you&#8217;ll get it. The 2 diverging extremes are &#8220;the Observable&#8217;s current value&#8221;, I.e. The latest value in the Stream. The other end of the spectrum is what I call them as; the Stream is just an Array of values, and you get them in order; so the Array&#8217;s an Observable. They&#8217;re both not technically correct because some Streaming libraries give you insane ballz control over Observables. Some like Frappe even go the Property route.</p>
<p>This is why specs exist after the innovation love has died down and developers have self-loathing when their toys start to get annoying.</p>
<p><A name="coldvshot"></a></p>
<h3>Cold vs. Hot</h3>
<p>When they start speaking really advanced about &#8220;cold vs. Hot&#8221;, don&#8217;t sweat it. All this means is something is Cold when it doesn&#8217;t dispatch events until someone listens. In a cold stream, if I click the mouse 50 times on a Hot button Stream, none of those Events are actually dispatched on the Stream until someone calls listen/subscribe. If it was a hot stream, she&#8217;d act like Events; the Stream would emit the events even if no one is listening.</p>
<p>Another example is reading text from a file. You won&#8217;t start receiving events for it until someone says, &#8220;Yo, read the this text file, and lemme know each line of text read as an event&#8221;. On demand type stuff like ajax calls, reading serialized data from window.localeStorage, querying a Model/Collection for the first time, etc.</p>
<p>Hot is the opposite, and works like Events; they&#8217;re fired whether anyone&#8217;s listening or not. This is for things that are happening whether you&#8217;re there or not. If you&#8217;re listener is late to the party, he&#8217;ll start getting new events from that point forward. If I click the mouse 50 times on a button Stream, and you only add a listen/subscribe callback after 25th has fired, you&#8217;ll only get 25 Events. Same as if you did 25 mouse clicks, then domElement.addEventListener(&#8220;click&#8221;, mouseCallback), then clicked 25 more times.</p>
<p>Dart streams are hot by default, whereas RX ones are cold unless you explicitly make it hot.</p>
<p><A name="streampros"></a></p>
<h3>Stream Pros</h3>
<p>The core goal with Streams is to reduce the amount of code you have to write, centralize the event handling, and filter the events all with Promise support. They do this by embracing functional Array filter methods, improving upon the Events API, support of Promises, with the ability to merge &#038; pipe streams together.</p>
<p>Promises deal with 1 event, not many. Although you can chain and/or bubble the event forward, it&#8217;s still 1 specific event that starts each part of the chain. Streams deal with many events with many listeners.</p>
<p>Promises usually are a 1 time affair. With their caching, while you can restart the sequence with many Promises in a chain and it&#8217;s a lot faster, it&#8217;s still the same piece of data. Streams on the other hand represent new data each time an event occurs by default unless combined with Promises or Observables/Properties. For cold observables, this helps solve the Event race condition problem by using the fact Streams will not usually post events until someone has subscribed/listened. In the case of many, you can utilize Promises to help.</p>
<p>Most Event mechanisms are synchronous whereas Streams can support asynchronous operations as well, yet like Promises, be written in a synchronous way. While not 100% solving race conditions, it helps. Some API&#8217;s such as Dart&#8217;s provide options allowing the Stream to be synchronous or asynchronous. Event emitters can&#8217;t be paused by default, where in some Stream implementations, its assumed those who are listening to the streams can pause them. This means any consumer, anywhere, can pause the stream without having knowledge of what Stream their pausing, whether that Stream is merged or via Composition. Since you can get multiple instances, you can have multiple people with varying levels of control. With great power comes great responsibility. Those who use Streams are now responsible for managing this subscription. This is an additional instance that you must store and later destroy. Here&#8217;s an RX example:</p>
<pre lang="javascript">var stream = getAStream();
var subscription = stream
  .subscribe(
    function (hotness) {
      console.log('Droppin it: ' + hotness);
    });
subscription.dispose();</pre>
<p>Events make this simpler by just forcing everyone to get the emitter instance, and just manager the listeners directly from the emitter. Except in larger code bases, finding this instance isn&#8217;t so simple. Some frameworks in more dynamic languages will offload the listeners secretly through the Decorator pattern onto those who call addEventListener so that garbage collection can more easily deal with the references.</p>
<p>For larger applications, flattening the complexity with Streams is very similar to flattening a complex architecture through Composition and Facades. The difference with Streams is a common API to do so for both consumption of Events as well as the abilities to wire Streams together. In heavy GUI applications in Flash/Flex, we&#8217;d do this with Events, or some other messaging system like <a href="https://github.com/robertpenner/as3-signals">Signals</a>.</p>
<p>They also scale better than Events in larger systems. As Stream / pub sub / Event systems grow, you start to run into the cognitive load challenge of keep track of all the different Event types and who dispatches them in your head including the data and types of data they contain. The difference with Streams is you have the ability to query both the data/Events you&#8217;re getting and operate on that data, all from a higher level structure. Using CSS classes and a DOM query syntax allows a more flexible UI. You can change &#038; refactor things under the surface API, and the surface API still works. Streams are the same way. No matter what you modify, move around underneath, you can still have flexible queries up top to ensure your data is in the format you need when it arrives. For game developers this may seem like something horrible; deeply nested, disparate structures IN SUPPORT OF allowing disparate parts to flexibly talk to each other.</p>
<p>For applications developers on a deadline with ever changing API&#8217;s across different domains, however, different story. You can quickly see how &#8220;querying&#8221; your data and composing it into something more useful from smaller parts, all in synchronous looking code that has a small line count, sounds hot.</p>
<p>To be clear; this isn&#8217;t a panacea; a large code base still has a heavy cognitive load. Streams just help. Helping is good.</p>
<p>For unit testing purposes, it&#8217;s slightly easier in some cold Streams to write unit tests specifically because many Streams will not dispatch events until the 1st listener is subscribed. Some of this behavior is predictable in some API&#8217;s, thus you can write better tests to ensure the listener actually received and reacted on the API regardless of what transformations it and the data composing went through. This all continues to work regardless of how many Streams you merge.</p>
<p><A name="streamcons"></a></p>
<h3>Stream Cons</h3>
<p>There is no spec right now. As such, they are quite confusing to learn. This also inadvertently makes them quite intimidating. Unless you have a game development, animation, or networking hardware background, visualizing how streams scale in larger systems can be quite hard. Bottom line, the lack of a spec means a lack of consensus on how these things are implemented. That&#8217;s really the only valid con for Streams, right now. Everything below is just nitpicking. </p>
<p>Streams also assume you already have good experience with Functional Array programming, and can answer why you&#8217;d use a map, where, and zip on the same Arrayâ€¦ yet applied to Events. Wait, what? If you don&#8217;t, it can be hard to extricate what is part of a Stream, and what&#8217;s part of the library. You have to &#8220;get&#8221; why <a href="https://lodash.com/">lodash</a>/underscore are awesome libraries first before you can see how they can &#8220;improve&#8221; events.</p>
<p>Many also assume you already are comfortable with Promises. Many developers are comfortable with Promises, but still create nested Promise chains vs. flattening them. Most Streaming libraries embrace Promises to make dealing with asynchronous code in a multitude of events easier. This can be a real mind-bender. It takes time to get used to coding this way. If your teammates don&#8217;t, they&#8217;ll get mad when they need you debug the code if they&#8217;re not up to speed yet.</p>
<p>Managing, or rather, choosing NOT to manage Stream subscriptions can get you into trouble memory wise. Most Promises you see on the web don&#8217;t really show how to clean them up. Most Stream examples are the same way. Just be sure you realize their writing pseudo code to get the point across and assume you will do your due diligence by disposing of your subscriptions.</p>
<p>Lastly is the merge/pipe mania. Many will use Stream features simply because they a Stream features. New, fresh, shiny, hot. Once they get bored, they&#8217;re just another way of doing events or async Promises. Be wary of people who want to merge/pipe all the things. If they go all Katamari Damacy with Streams attempting to eat and consume MVC, you know they&#8217;ve jumped the shark. That said, I encourage you to do this in your spare time off of project/client work. The various libraries approach things differently so it&#8217;s neat to learn those differences.</p>
<p><a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-5-of-7-promise-and-deferred.html" class="btn btn-primary">&lt;&lt; Part 5 &#8211; Promise Deferred</a> | <a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-7-of-7-conclusions.html" class="btn btn-primary">Part 7 &#8211; Conclusions &gt;&gt;</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Message Systems in Programming: Part 5 of 7 &#8211; Promise and Deferred</title>
		<link>https://jessewarden.com/2014/12/message-systems-in-programming-part-5-of-7-promise-and-deferred.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Wed, 24 Dec 2014 15:58:10 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[callbacks]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[eventemitters]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[promises]]></category>
		<category><![CDATA[publish]]></category>
		<category><![CDATA[pubsub]]></category>
		<category><![CDATA[streams]]></category>
		<category><![CDATA[subscribe]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=4729</guid>

					<description><![CDATA[Promise and Deferred (or Futures and Completers) We&#8217;ve glossed over asynchronous coding up to this point. Many from languages which have reasonable event API&#8217;s (ActionScript) to extremely nice ones (C#), it may not at first look like a problem, or even appear to be an edge case. Coming from ActionScript, it took me years to [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a name="promises"></a></p>
<h2>Promise and Deferred (or Futures and Completers)</h2>
<p>We&#8217;ve glossed over asynchronous coding up to this point. Many from languages which have reasonable event API&#8217;s (ActionScript) to extremely nice ones (C#), it may not at first look like a problem, or even appear to be an edge case. Coming from ActionScript, it took me years to get comfortable, and understand why, Promises were helpful. Also, many in those languages either create, or have facilities that help create, orchestration code to help mitigate common asynchronous coding issues.</p>
<p><span id="more-4729"></span>But first, why asynchronous code?Â Synchronous code in GUI&#8217;s is challenging for 2 reasons.</p>
<p>The first is most UI runtimes have the code execution and drawing in the same thread. The <a href="http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/">Elastic Racetrack</a> metaphor is often used to explain how this works. This means we have an our code doing calculations and handling user events (like clicks) done at the same time as the code that draws and redraws things to the screen. At first this seems reasonable given how fast computers are. However, as code complexity grows inline with sophisticated UI such as dynamic graphs, hardware accelerated animation, and complicated redrawing of multiple DOM elements for text and graphics in the browser&#8230; It&#8217;s a lot to do in a few milliseconds so the user doesn&#8217;t notice. That, and this all assumes the code has no orchestration to optimize this redraw part of the track, and the data processing part of the track such as <a href="http://jessewarden.com/2008/03/how-to-fix-the-flash-cs3-components.html">invalidation strategies</a>, also known as deferred rendering.</p>
<p>Second is network or I/O (input output) calls. For example, I want to show some text on this page; I know you&#8217;re German speaking based on the browser string, so I make a network request to my CMS (content management system) to get the German content. This may take a second or many seconds. In the synchronous or &#8220;blocking&#8221; world, the code would stop executing at that point and wait for that request to the server to spit back the text we need. The user&#8217;s mouse would work, but no clicks, drags, touches, double-clicks, rollovers, touch indicators, keyboard usage would function, nor would the user be able to see the UI visually update; the app looks like it&#8217;s broken. Even if it had a loading icon, it&#8217;d be paused. The UI is &#8220;locked&#8221; or &#8220;blocked&#8221;.</p>
<p>Cool, so things that require us to go outside of JavaScript for data like the server or the local disk/database, we&#8217;ll just make those asynchronous, which the Browser developers have done for us. The same holds true for server development platforms like Node and gaming ones like Corona and <a href="http://unity3d.com/">Unity</a>. Other blocking languages like <a href="https://golang.org/">Google&#8217;s Go</a> don&#8217;t have this issue/feature.</p>
<p>This, however, creates 2 new problems specifically how to write code that &#8220;waits&#8221; for things and how to chain these scenarios without making the code unreadable or hard to follow.</p>
<p>Callbacks are the first way. We&#8217;ve seen for simple code, they are the fastest, easiest, and most flexible way to do that. &#8220;Whenever you&#8217;re done, homey, call me&#8221;. Below is how JQuery does asynchronous loading of data from t3h interwebz:</p>
<pre lang="javascript">$.ajax({
  url: "http://jessewarden.com",
  success: function(data)
  {
  	console.log("loaded data:", data);
  }
});</pre>
<p>&#8220;Load data from here, and call this function when it worked, passing me the data as the 1st parameter, kthxbai.&#8221;</p>
<p>Events were another attempt to do that for multiple people who wish to know about some async event. You can utilize the same API, and your code looks the same, and the key here is that it works the exact same whether synchronous or asynchronous. The pseudo code below shows synchronous click code with asynchronous image loading code. Notice how the API looks and works the same, yet the firstÂ callback function fires immediately when you click in the same call stack, whereas the 2nd fires after some random amount of time, never in the same execution stack.</p>
<pre lang="javascript">function onClick(event)
{
   console.log("clicked");
}
button.addEventListener("click", onClick);

function onImageLoaded(event)
{
   console.log("image loaded");
}
image.addEventListener("onload", onImageLoaded);</pre>
<p>That&#8217;s all well and good until you start utilize class composition; meaning you utilize many objects that have events or callbacks in a parent class. One convention is to register all the event listeners up top, and then define the event handlers below, in the order they were added. If the event handlers utilize functions, well, you just either put them nearby and make finding the functions in order no longer work, or put them below the callbacks and force those reading/debugging to jump around your class.</p>
<p>For the sake of the reader, I&#8217;ll keep the below brief, but tripling the lines of code below it is something I commonly see:</p>
<pre lang="javascript">define(["jquery",
		"Underscore",
		"com.company.project.views.InventoryView",
		"com.company.project.views.ScheduleView",
		"com.company.project.views.ProfilePopUp",
		"com.company.project.events.EventBus",
		"com.company.project.utils.InventoryUtils"], 
		function($,
					_,
					InventoryView, 
					ScheduleView, 
					ProfilePopUp,
					EventBus,
					InventoryUtils)
{
	var SomeClass = function()
	{
		init: function()
		{
			// TODO: use _.bindAll
			_.bind(this.onClick, this);
			_.bind(this.onInventory, this);
			_.bind(this.onScheduleTask, this);
			_.bind(this.onToggleProfile, this);
			_.bind(this.onToggleEditProfile, this);

			$("#SubmitButton").click(this.onClick);
			$("#InventoryButton").click(this.onInventory);
			$("#ScheduleTask").click(this.onScheduleTask);
			$("#ToggleProfile").click(this.onToggleProfile);
			$("#ModalProfileEditForm").click(this.onToggleEditProfile);
		},

		onClick: function()
		{

		},

		onInventory: function()
		{

		},

		onScheduleTask: function()
		{

		},

		onToggleProfile: function()
		{


		},

		onToggleEditProfile: function()
		{

		},

		someHelperMethodReferencedRandomlyAbove: function()
		{

		}
	};
	return SomeClass;

});</pre>
<p>It looks nice at first, but then becomes a long class you have to constantly scroll up and down through. It gets worse as those event handlers and methods either grow in size, number, or have comments attached to them. You&#8217;ll notice the above is using UI events; this can be deceiving if some of those callbacks are actually listening to global pub sub messages. It gets confusion which functions are responding to global events and which are responding to local UI ones. Your unit tests also start to get pretty long as well. Languages which handle scope like <a href="http://coffeescript.org/">CoffeeScript</a> and <a href="http://www.typescriptlang.org/">TypeScript</a> can help a little, but you still end up with the same problem: lot&#8217;s of code that&#8217;s hard to pin down to localized functionality; i.e. &#8220;all the stuff this class does about this one thing is right here&#8221; vs. spread out all over the place.</p>
<p>Now, remember, there are those of us from other languages/platforms where this was the norm and considered ok (even if you didn&#8217;t have a deadline). Worse, anonymous functions in some languages needed to be scoped to SOMETHING else the garbage collector would eat them leading to less terse code capabilities without a language change (i.e. Lambdaâ€<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2122.png" alt="™" class="wp-smiley" style="height: 1em; max-height: 1em;" />s in t3h newer Java). JavaScript and Lua&#8217;s friendless to lamda/anonymous functions in terms of the Garbage Collector not eating them in Mark and Sweep phases means they are a common way to reduce code length in larger code bases at a tiny cost to function creation time (anonymous functions vs. class member / Object.prototype ones).</p>
<p>Where async code really starts to break down is with data orchestration and animation: 2 common asynchronous operations central in UI development. Additionally, we have no idea if any of those events already happened before the class executed. The UI events that are user gestures (the user clicked on something), we don&#8217;t care, but the model or other UI asset changes, we do. This is why you&#8217;ll often see those event handlers called at the bottom of the init to &#8220;set the class up in case she&#8217;s late to the data party&#8221;.</p>
<p>Jake Archibald has a great, and often used example, that wonderfully illustrates how the above provides a false sense of security, specifically around loading of an image. I&#8217;ll copy that example here verbatim:</p>
<pre lang="javascript">var img1 = document.querySelector('.img-1');

function loaded() {
  // woo yey image loaded
}

if (img1.complete) {
  loaded();
}
else {
  img1.addEventListener('load', loaded);
}

img1.addEventListener('error', function() {
  // argh everything's broken
});</pre>
<p>2 important points in this example.</p>
<p>First, we burden the consumer, the developer using the class that emits events, to check if it already fired, and if so, manually fire her event assuming the event handler accepts a function call without an event parameter; JavaScript does, CoffeeScript(?), TypeScript, and Dart you have to specifically mark those functions to have the events as optional parameters.</p>
<p>Second, my SomeClass example above doesn&#8217;t have any error handling at all. In most apps, at best, they log errors with little to no user experience thought given around those scenarios. That said, very rarely do any of them react to errors that happened before their instantiated for the user (ie a graph is shown, but the data that was supposed to be loaded before it was shown failed to load). No one wants to spend time creating user experiences around a broken server, but it&#8217;s important. Pitching clients to spend a lot of their application development budget on designing user experiences around things breaking seems counterintuitive to quality software craftsmanship. Thus, this is often left to developers who have little time for such concerns, hence why error handling is often such a horrible experience in many applications. It&#8217;s not their responsibility, its the Designer(s). Catch 22, sucka!</p>
<p>When you take into account both events already happening before you&#8217;ve arrived on the scene as well as errors, you can see how the code above gets much more verbose, and complicated to follow.</p>
<p>One common work around at least in MVC applications, is to allow View classes to be extremely friendly to null values in the Models. That way, if the data isn&#8217;t loaded let, they can show either a loading or something to the user while it loads or fails, otherwise they can immediately draw the model when they&#8217;re shown. The thinking goes &#8220;someone else will handle orchestrating everything in the correct order later&#8221; and even &#8220;somehow allow this to be easily refactored&#8221;. This can work if your Models aren&#8217;t that complicated, but still makes the code quite verbose.</p>
<p>The second place the SomeClass example starts to break down is when you have multiple asynchronous events that depend on each other.</p>
<pre lang="javascript">var userView = {
	userModel: null,
	imageTag: null,
	showAvatar: function()
	{
		var imageURL = userModel.avatarURL;
		imageLoader.get(imageURL, function(bitmapData)
		{
			imageTag.showBitmapData(bitmapData);
		});
	}
};</pre>
<p>You&#8217;ll notice in the above simple JavaScript View, if both the model data for the user is not yet loaded from the server AND the HTML and CSS needed to display the image which also needs to be loaded, the View won&#8217;t work. 2 options here: either check for null and do nothing assuming &#8220;you didn&#8217;t load the data for me idiot, I&#8217;m not showing anything, but will be nice to you and not throw errors&#8221; or put the burden on the developer using the View to get both of those things ready ahead of time.</p>
<p>Many MVC and web application tutorials out there assume you have good REST services that give you only the data you need, and you only need to make 1 call for the entire app or per section the user see&#8217;s with a good set of data caching code behind it. Backbone is notoriously seductive in this respect regarding who it&#8217;s Models are built around this with no guidance given to those who aren&#8217;t actually hitting REST services.</p>
<p>If you&#8217;re a JavaScript client developer, and you have a bad ass Node developer who has your back and y&#8217;all can communicate often as requirements changeâ€¦ you have it quite well, my friend.</p>
<p>This is simply not how enterprise applications work in the real world, although I&#8217;m seeing this change once .NET/Java business tier developers realize their jobs aren&#8217;t in jeopardy because of Node. You&#8217;re often building atop of .NET or Java backends that are several years old, many of which were in support of page based web sites or desktop applications long before you got involved. Getting the back-end team to refactor this for the best user experience takes an act of God, especially if you&#8217;re one of hundreds of applications that consume their services.</p>
<p>Unless you got Node into the mix, you&#8217;ll be making many calls, often multiple times, before a particular View/Screen can be shown to the userâ€¦ in addition to your other data orchestration duties. Sometimes you&#8217;re lucky if you abstract these multiple calls away into a single class that dispatches 1 event. If you&#8217;re not, you usually have the two common problems: multiple classes that only have pieces of the data you need that continually needs refreshing or lots of data on the client you have to parse, such as the case in dashboards and graphing applications. This isn&#8217;t just ajax calls we&#8217;re talking about either; this could be JavaScript code running on the client that that needs to run long running parsing code that may or may not include an ajax call, image and other media assets, and various multiple authentication calls from a variety of servers.</p>
<p>For example, many financial applications often pull data from a variety of back-end data sources to show on 1 screen. Whether these are different sub-domains, or a single REST/SOAP/RPC server, they could still all work slightly differently and take varying amount of times to respond. Sometimes you have to call them in a certain order since each successive call gives you a token/id/session cookie needed for the following call for the actual data, some of which you can&#8217;t cache because the nonce tokens (prove you&#8217;re a user who&#8217;s logged in) can expire quickly for financial data.</p>
<p>Let&#8217;s show an example where you first need to get some user info that needs to be obtained to snag the user&#8217;s current token (which changes often) so you can then get info on a particular financial transaction (something the user bought) which is then used to charting data related to it&#8217;s id + type (which the server has conveniently stashed a bunch of huge JSON files on a <a href="https://www.heroku.com/">Heroku</a> friendly CDN somewhere so you can parse on the client to show charts). </p>
<p>However, that last call has a TON of data, so you&#8217;re using a polyfill (a library that allows you to use future HTML5 functionality, today) that supports WebWorkers (threads in JavaScript) so you can parse the data safely and attempt save to LocalStorage to avoid the slow latter part of the process again if the user views a particular transaction again later. I&#8217;ve also had cases where the type dictates which type of data we have, thus requiring another parsing call and a basic fork in the path of how you parse the code. I&#8217;ve also left out the fun parts of debugging unknowingly neutered ArrayBuffers&#8230; but lets keep it simple (lulz).</p>
<p>Quite a mouthful yet common in the screwed up world of Enterprise Software.</p>
<pre lang="javascript">var currentClientToken = null;
var clientID = null;
var transactionID = null;
var graphWorker = null;
var done = false;

function getCompleted()
{
	return this.done;
}

function getClientToken(clientID, transactionID)
{
	this.done = false;
	this.clientID = clientID;
	this.transactionID = transactionID;
   $.get("/getClientInfo", clientID, this.onGetClientTokenSuccess, this.onGetClientTokenError);
}

function triggerGenericError(error)
{
	EventBus.trigger("GetChartingInfo:error", error);
}

function onGetClientTokenError(error)
{
	this.done = true;
	this.triggerGenericError(error);
}

function onGetClientTokenSuccess(data)
{
	try
	{
		var clientVO = ClientFactory.get(data);
		this.currentClientToken = clientVO.token;
		$.get("/getTransactionInfo", 
			{token: this.currentClientToken, transactionID: this.transactionID}, 
			this.onGetTransactionInfoSuccess, this.onGetTransactionInfoError);
	}
	catch(err)
	{
		this.triggerGenericError(err);
	}
}

function onGetTransactionInfoError(error)
{
	this.triggerGenericError(error);
}

function onGetTransactionInfoSuccess(info)
{
	try
	{
		var transactionVO = TransactionFactory.get(info);
		var currentTransactionURL = "https://sub.company.com/project/graphingcdn/" + transactionVO.id + "/?clientID=" + this.currentClientToken;
		$.get(currentTransactionURL, this.onGraphDataSuccess, this.onGraphDataError);
	}
	catch(err)
	{
		this.triggerGenericError(err);
	}
}

function onGraphDataError(error)
{
	this.triggerGenericError(error);
}

function getGraphWorker()
{
	if(this.graphWorker == null)
	{
		this.graphWorker = new Worker("GraphFactory.js");
		this.graphWorker.onmessage = function(event)
		{
			this.onGraphDataParsed(event.data);
		};
	}
	return this.graphWorker;
}

function onGraphDataSuccess(graphData)
{
	getGraphWorker().postMessage(graphData);
}

function onGraphDataParsed(graphVO)
{
	if(graphVO != null)
	{
		this.done = true;
		EventBus.trigger("GetChartingInfo:success", graphVO);
	}
	else
	{
		// parsing failed
		EventBus.trigger("GetChartingInfo:error", error);
	}
}</pre>
<p>&#8230; to recap our problems, we now have:</p>
<ol>
<li>lots of code</li>
<li>you have to scroll to find where an event is handled</li>
<li>finding event handlers for events registered within event handlers makes it even harder to follow</li>
<li>using if statements to handle potential race conditions</li>
<li>burden to ensure sequence can only start once with ability to stop it at any point</li>
<li>forced to remove event listeners to help garbage collection</li>
<li>code not fully shielded from uncaught exceptions</li>
<li>burden of error handling can make API unwieldy</li>
</ol>
<p>WAT DO!?</p>
<p>Science has shown that less code equals better software. Through 1 study at least.</p>
<p>Enter the <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">Promise</a> (known as <a href="https://www.dartlang.org/docs/tutorials/futures/">Futures</a> in Dart). They are a way to make asynchronous code look and feel like synchronous code.</p>
<p>Our &#8220;use&#8221; of the above is turned into 8 lines of code (6 if you cuddle, but Machete don&#8217;t cuddle):</p>
<pre lang="javascript">getGraphData().then(function()
{
	EventBus.trigger("GetChartingInfo:success", graphVO);
},
function(error)
{
	EventBus.trigger("GetChartingInfo:error", error);
});</pre>
<p>Now, using Underscore and some refactoring using your module system of choice, you could refactor the above to be similar without Promises:</p>
<pre lang="javascript">EventBus.on("GetChartingInfo:success", function(graphVO)
{
	drawIt(graphVO);
});
EventBus.on("GetChartingInfo:error", function(error))
{
	console.error("GetChartingInfo:error:", error);
});
getGraphData();</pre>
<p>9 (7c) lines vs. 8 (6c); not bad. However, not apples to apples either. They do completely different things and the Event way doesn&#8217;t guarantee the same order in the same stack like Promises do. Subtle, but painful for n00bs to debug when they don&#8217;t know what&#8217;s going on. Heck, it&#8217;s painful for me!</p>
<p>The promise way only has 1 callback. The Events have multiple potential ones.</p>
<p>The events must be registered as listeners first before the call to getGraphData happens. If the events are not registered before getGraphData is called, you do not get the data. While getGraphData may internally cache the data, you must call it again after your listeners are registered to get this data. For smaller applications, this is easy; for larger ones, this is more challenging. It also puts a burden on those types of classes to make a caching decision sooner to make an easier API to consume.</p>
<p>The Promise does not care if you call it before the value(s) internally have been fetched from the server yet or not; you can call it anytime and get the same result. There is never a race condition problem using Promises as opposed to Events.</p>
<p>Also, by default, most Promises assume you&#8217;re caching in RAM by default based on the last return value if you follow the Promise/A spec.</p>
<p>API wise, it should be noted that the Event by default allows multiple responders to hear about a success or failure, whereas the Promise is only executed with 1 callback. This is neither good nor bad, just something be aware of when comparing the callback nature of Promises compared to Events.</p>
<p>A minor point, but the events now have a message chosen. You now need a way to track that message. If you just use a magic string, fine, but for large applications you tend to use some form of enumeration or constant class to help both management, strong-typing &#038; code hinting for IDE&#8217;s that support it, and to ease the developer&#8217;s need to View all possible messages in a central place without a grep. Now a decision must be made; where do these enumerations go? In the class dispatching as statics/constants? Is it 1 class that supplies all global pub sub events for the entire application? Each has their pro&#8217;s and con&#8217;s, but both include more code, cognitive overhead, and crap for you to deal with.</p>
<p>Lastly, most Promises &#038; promise libraries will execute on the next tick whereas most event, pub sub, and streaming libraries do not. Yes, you can add a setTimeout(func, 0), but that&#8217;s a hack on top of an API most assume works, and codes their API as, synchronously. There are a variety of use cases that aren&#8217;t described very well so I&#8217;ll cover that below regarding expecting order of execution to work, whether in synch or async code. This is why many pub sub libraries have extra error handling on removing listeners because if it&#8217;s in the middle of a dispatch, you can accidentally <a href="https://web.archive.org/web/20030203013431/http://chattyfig.figleaf.com/flashcoders-wiki/index.php?betabugs">prevent others from getting the message</a>.</p>
<p>Now, Jake&#8217;s article covers all you need to know about how Promises work, and Q&#8217;s documentation is pretty legit as well to help you create Promises as well as work with libraries that aren&#8217;t Promises out of the box.</p>
<p><A name="doneyet"></a></p>
<h3>Done Yet?</h3>
<p>Promises, whether ES6 or Q, store the state of whether the Promise is done or not internally. You don&#8217;t have write code to do that; it&#8217;s part of them implementing the state machine part of the Promises/A spec. The Event option, however, has to allow the &#8220;done&#8221; boolean to be managed amongst the many callbacks.</p>
<p>This internal state management has a positive effect on sub-sequent calls with the same data, specifically getClientToken, getTransactionInfo, loading of the transaction JSON data, and receiving the parsed data from the WebWorker. For Promises, they&#8217;ll simple cache the data and re-deliver it usually immediately in the next tick (next time the stack is unwound then wound).</p>
<p>In the Event abstraction, you&#8217;ll have to do that yourself. In both cases, you&#8217;ll have to utilize whatever local storage option you wish to use (cookies, local storage, app cache, etc), but this functionality of locked data is built into Promises; you don&#8217;t have to code it, it&#8217;s built in + expected behavior. This includes multiple calls that could utilize multiple Promises internally. In our case, that&#8217;s about 4 Promises that each has the built-in ability to store data if it hasn&#8217;t changed.</p>
<p>You can also refactor asynchronous code that is not a Promise to be a Promise. That is one way developers have attempted to solve the above problems.</p>
<p><A name="solvinglotsofcode"></a></p>
<h3>Solving Lots of Code</h3>
<p>Promises are made part of async API&#8217;s. As such, instead of first registering for an event before calling something that will trigger it, you instead just call the method and the Promise is the returned value. That&#8217;s 2 lines of code to 1. Like callbacks.</p>
<p>This has larger ramifications, though, down the line when you&#8217;re async call is part of a series of async call allowing them to be chained as well as put into groups where they all must complete before another operation can succeed. This further cuts down on needing to define event handlers.</p>
<p><A name="scrolltofindcode"></a></p>
<h3>Scroll to Find Code</h3>
<p>No more scrolling, it&#8217;s defined inline. The call and the responses are all next to each other.</p>
<p><A name="nestedeventhandlerregistration"></a></p>
<h3>Nested Event Handler Registration</h3>
<p>This problem isn&#8217;t solved immediately with Promises. You can get into situations where people do not return Promises from async code, and they end up doing work in the success handlers. Through refactoring you can flatten these deeply nested chains. <a href="https://plus.google.com/+ThomasBurleson/posts">Thomas Burleson</a> has <a href="https://github.com/ThomasBurleson/angularjs-FlightDashboard">a great example</a> where he shows both.</p>
<p><A name="handlingraceconditions"></a></p>
<h3>Handling Race Conditions</h3>
<p>Part of the spec for Promises is to solve this issue. Promises will automatically call their success or error method if the event has already occurred. This, again, reduces the amount of code you need to write when consuming async services. Additionally, it adds flexibility to call them in any order, at any time you need to; no need for orchestration/setup code to ensure everything is &#8220;ready for the data events that will fire and YOU NEED TO BE THERE FOR&#8221;. You instead react. This is part of where the &#8220;reactive&#8221; part comes in Functional Reactive Programming.</p>
<p>Finally, Promises have an internal state machine convention that they only ever complete once; so you don&#8217;t have to worry about your error or success methods firing more than once. They are not like events in this aspect which are known to fire many times.</p>
<p>This is one of the main problems that Events and Pub Sub run into when the application starts to grow in size and developers. </p>
<p><A name="abortingsequence"></a></p>
<h3>Aborting Sequence</h3>
<p>Promises do not solve the abort sequence; i.e. you cannot easily start a long async Promise or chain of Promises once they&#8217;ve started. De-reffing the parent in hopes the child will get garbage collected isn&#8217;t sure fire, and adding API&#8217;s to a Promise based class is a more prudent option, although, more work in the case of many Promises through Composition.</p>
<p>More advanced Promise API&#8217;s such as Dart&#8217;s <a href="https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-async.StreamController">StreamController</a> and RX.js&#8217; <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/libraries/rx.backpressure.md">Backpressure</a> have the API&#8217;s you need to wrap Promises with the ability to stop async sequences, or even pause the events being emitted from the emitter. However, both incur a completely different paradigm of programming so it&#8217;s not as simple as &#8220;oh, I&#8217;ll just use this awesome library/x-compiler&#8230;&#8221;. We&#8217;ll get into that in the Streams section.</p>
<p><A name="nomorecleanupcode"></a></p>
<h3>No More Cleanup Code</h3>
<p>Promises, if they&#8217;re values are non-global and the chains are local to the function block, will get eaten by garbage collection if you de-reference them.</p>
<p>From a memory standpoint, this can be a blessing or a curse. Promises are ensured to only execute one time, and cache the value each additional call assuming the inputs don&#8217;t change, all while retaining the same code execution order. However, they basically act like a getter; they cache the data they are referencing as a form of <a href="http://stackoverflow.com/questions/10314056/usage-of-observable-pattern-in-javascript">Observers</a>, albeit with 1 listener to start. Note, the Observer pattern is different than what stream API&#8217;s refer to regarding <a href="http://reactive-extensions.github.io/RxJS/">Observables</a>. People will use the word &#8220;observable&#8221; to either refer to something that emits change events like the Observer design pattern, or a watchable property/stream in something like RX.js/<a href="http://baconjs.github.io/">Bacon.js</a>. For large data sets, images, etc. you may not wish to leave this stuff laying around in RAM.</p>
<p>Check out this post (plus the comments full of lulz) from <a href="http://sealedabstract.com/code/broken-promises/">Drew Crawford</a> talking about how brazenly just caching all data in Promises isn&#8217;t always a good idea.</p>
<p><A name="shieldedfromexceptions"></a></p>
<h3>Shielded From Exceptions</h3>
<p>In the native implementations, Promises are built around the concept of success and failure. This includes built-in support for if an exception is thrown in a constructor it calls the error callback. Additionally, you can interpret successful responses from the server as a mistake and cause an error condition safely.</p>
<p>That said, the burden of good error handling is still on the developer in case an error does bubble up through a deep Promise chain, you want a good idea of where it came from. The same goes for good synchronous error handling through tried and true try/catch blocks within more complex Promise operations. Looking through the stack trace to work your way back down is still required in some cases which, again, can be mitigated with an effective logging solution. Theoretically <a href="http://swannodette.github.io/2013/08/31/asynchronous-error-handling/">yield</a> used within a <a href="http://wiki.ecmascript.org/doku.php?id=harmony:generators">Generator</a> function could help mitigate some of the error hunting as well.</p>
<p>Also, take note some Promise libraries take the positive initiative to allow you to get stack traces that areâ€¦ you knowâ€¦ actually useful in debugging such as Q (check out <a href="https://github.com/kriskowal/q">longStackSupport = true</a>) and Bluebird&#8217;s <a href="https://github.com/petkaantonov/bluebird/blob/master/API.md#promiselongstacktraces---void">longStackTraces</a>. these types of debugging features are NOT in Angular&#8217;s version of <a href="https://docs.angularjs.org/api/ng/service/$q">$q</a>, and it&#8217;s Promise API. Do the hard work of being proactive yourself with good try/catch error messages and logging.</p>
<p>Also note, many Promise libraries will allow you to apply multiple catches to differentiate between the various types of async errors which is a wonderful practice you should endeavor to do.</p>
<p><A name="nexttick"></a></p>
<h3>Next Tick</h3>
<p>Some Promise libraries will make a big deal about &#8220;nextTick&#8221;. The reason is most people when writing synchronous code expect the same order of execution no matter how many times the code is run. While Promises aren&#8217;t technically synchronous code, you write it as such. </p>
<p>For example, we all expect the function below to print out 1, 2, 3 no matter how many times it&#8217;s called:</p>
<pre lang="javascript">function dreamMachine()
{
	console.log("1");
	console.log("2");
	console.log("3");
}</pre>
<p>We also expect the function below to print out 1, 3, 2 no matter how many times it&#8217;s called:</p>
<pre lang="javascript">function dreamMachine()
{
	console.log("1");
	Q.fcall(somePromise).then(function()
	{
		console.log("2");
	});
	console.log("3");
}</pre>
<p>This is one feature Promises have above simple Pub Sub because your callbacks are fired in the same order regardless of how long the response takes, and if the data is cached or not.</p>
<p>Those who get mad about it are the ones who want faster code, typically server-side Node developers. The nextTick is often at a minimum a setTimeout(runTheThenFunction(), 0). This&#8217;ll significantly warp benchmarks that make the code look slow whereas in reality the code isn&#8217;t actually using CPU.</p>
<p>However, it IS a problem in that the code still takes more time and can significantly increase unit test suite test runner time. There are various Promise/A+ spec compliant libraries that will give you a flag to turn this off. This is for developers who know exactly why you&#8217;ll get 1, 2, 3 in some situations above. If you don&#8217;t know why that can happen, leave the setting off, heh!</p>
<p>Be aware, Node.js has <a href="http://nodejs.org/api/process.html#process_process_nexttick_callback">a more efficient nextTick</a> with configuration options.</p>
<p>Another use case is asynchronous initialization. Some objects/classes have significant amounts of asynchronous setup they have to do. You want an opportunity to be aware of some of these operations, say the loading of images in gaming Sprites, or using a server-side logging that has JSON file based configuration values is must load and parse before being used. Incidentally, this makes writing invalidation routines on top of existing GUI code a big easier.</p>
<p>Finally, in the case of networking operations, you don&#8217;t always want to impose knowledge of order of operations on the user. Instead, let them set and call things in any order, and let the class figure out the true order on the nextTick/frame.</p>
<p>For example, imagine if JQuery&#8217;s ajax didn&#8217;t have object initialization as it&#8217;s API. Instead of:</p>
<pre lang="javascript">$.ajax({
  url: "http://jessewarden.com",
  success: function(data)
  {
  	console.log("loaded data:", data);
  }
});</pre>
<p>It&#8217;d be:</p>
<pre lang="javascript">var operation = $.ajax();
operation.url = "http://jessewarden.com";
operation.dataType = "html";
operation.type = "GET";
operation.success = function(data)
{
	console.log("loaded data:", data);
};
operation.load();</pre>
<p>You not only have to learn an API, but the order in which the methods are called just to make a simple GET call? What if even more code later continues to modify, or even overwrite the operation&#8217;s parameters?</p>
<p>Using nextTick, calling order doesn&#8217;t matter. Internally, the actual XHR call won&#8217;t be made until the next frame anyway, so the ajax operation can handle setting everything up in the order it needs. This follows OOP encapsulation principles, and makes life easy on the developer.</p>
<p><A name="promisepros"></a><H3>Promise Pros</h3>
<p>Promises significantly reduce the amount of code you have to write for asynchronous operations where you&#8217;d traditionally use callbacks or events.</p>
<p>They also localize it vs. spreading it out like events and callbacks are want to do. Just be sure you practice flattening some Promise chains so you don&#8217;t end up with the opposite problem of Promise chain hell vs. callback hell.</p>
<p>They also make chaining multiple asynchronous operations together much easier to read and debug.</p>
<p>They help reduce race conditions when the Promise already has a cached value, and merely calls the callback immediately. For low memory items, this also has the side benefit of caching data in memory for expedited calls later on, especially for those classes/Views initialized later in the application lifecycle. They also make writing asynchronous libraries easier on the consumers because they can call their setup calls in any order knowing the actual resolving of them will occur on the next frame.</p>
<p>Finally, you can write your code and not have to care something is synchronous or asynchronous; it looks and is written in a synchronous way.</p>
<p><A name="promisecons"></a><H3>Promise Cons</h3>
<p>For those who are new to Promises, as I mentioned, they end up creating callback hell using Promises. Rather than creating their own operations that return Promises, they instead merely use Promises and continue to nest them. Again, check out Thomas Burlesson&#8217;s <a href="https://gist.github.com/ThomasBurleson/7576083">great example</a> where he shows how you flatten deeply nested Promise chains. Once you practice, you can quickly flatten these trees as you create them. Eventually you&#8217;ll start writing methods that return Promises by default making your life easier. Like once you memorize a for loop&#8217;s syntax, you never think about it again.</p>
<p>For low memory situations on mobile, you could get in trouble when caching the data in Promises. While you&#8217;re supposed to follow the Promise/A spec and ensure Promise&#8217;s fullfilled state stays true and never changes the data, care must be taken to ensure you aren&#8217;t keeping these around unnecessarily, especially on mobile devices. This isn&#8217;t necessarely indicative of Promises, rather caching in general, which is a commonly hard programming problem. They are just brought up since most Promises handling async operations are often around data, your want to cache it.</p>
<p>Caching isn&#8217;t straightforward either. Some libraries help in this regard, but basic programming for by value vs. by reference apply. When getting values you&#8217;re basically assuming the developer doesn&#8217;t change them if they&#8217;re by ref. Cloning has performance impacts as well for deeply nested objects. Following the Promise/A spec with regards to not changing the value is often based on convention and isn&#8217;t always easily enforced. Don&#8217;t get me started on the insanity of sharing <a href="v">ArrayBuffers</a> across <a href="http://www.html5rocks.com/en/tutorials/workers/basics/">WebWorkers</a>; shiz is magic death.</p>
<p><a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-4-of-7-publish-subscribe.html" class="btn btn-primary">&lt;&lt; Part 4 &#8211; Publish Subscribe</a> | <a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-6-of-7-streams.html" class="btn btn-primary">Part 6 &#8211; Streams &gt;&gt;</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Message Systems in Programming: Part 4 of 7 &#8211; Publish Subscribe</title>
		<link>https://jessewarden.com/2014/12/message-systems-in-programming-part-4-of-7-publish-subscribe.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Wed, 24 Dec 2014 15:55:56 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[callbacks]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[eventemitters]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[promises]]></category>
		<category><![CDATA[publish]]></category>
		<category><![CDATA[pubsub]]></category>
		<category><![CDATA[streams]]></category>
		<category><![CDATA[subscribe]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=4724</guid>

					<description><![CDATA[Publish Subscribe Callbacks help objects/classes talk to each other in a less coupled way. Events for many to listen and react. However, for objects that deal with data or business logic, you need a way for them to globally communicate through some sort of event or message bus. Various libraries have sprung up in languages [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a name="pubsub"></a></p>
<h2>Publish Subscribe</h2>
<p>Callbacks help objects/classes talk to each other in a less coupled way. Events for many to listen and react. However, for objects that deal with data or business logic, you need a way for them to globally communicate through some sort of event or message bus. Various libraries have sprung up in languages that do not have this natively available, or if the native API doesn&#8217;t fit the developer(s) need.</p>
<p><span id="more-4724"></span>Enter publish subscribe.</p>
<p>Now, pub sub is actually a pretty high level term that pretty much encompasses this entire article.</p>
<p>Callbacks and Promises have a subscribe method, and they publish a method when they execute a callback. However, we&#8217;re referring to the ability to publish to multiple subscribers.</p>
<p>Events have a subscribe method via addEventListener, and a publish method via dispatchEvent. However, at least in the case of JavaScript, we&#8217;re referring to the same abilities WITHOUT the need for anything graphical involved.</p>
<p>A pub sub system COULD be made from a Stream, but I wanted to cover the implementations I&#8217;ve seen so you get an understanding why they not callbacks, events, promises, nor streams.</p>
<p>Pub sub IS the ability to:</p>
<ul>
<li>be 1 instance that can broadcast to many listeners</li>
<li>have no need for anything GUI related</li>
<li>just be a class/object instance</li>
</ul>
<p><A name="pubsubexamples"></a></p>
<h3>Pub Sub Examples</h3>
<p>Backbone&#8217;s <a href="http://backbonejs.org/#Events">Events</a> class is the first example most in the JavaScript community refer to. You can either create an instance and pass this instance around via <a href="http://requirejs.org/">Require.js</a> as a global telephone. Some get lazy (or are in a hurry or don&#8217;t know any better) and shove on window, or forget they can just use the Backbone object. Either way, here&#8217;s a manually created global one below:</p>
<pre lang="javascript">var EventBus = {};
_.extend(EventBus, Backbone.Events);
window.EventBus = EventBus;</pre>
<p>Now, any object or class, anywhere in the world, GUI or data, can go:</p>
<pre lang="javascript">EventBus.trigger("onSomeEvent", 1, 2, {firstName: "Action", lastName: "Jackson"});</pre>
<p>&#8230; and anyone and their mom can listen for it, anywhere via:</p>
<pre lang="javascript">EventBus.on("onSomeEvent", function(event)
{
	console.log("Who's the MAN?!: " + event.firstName + " " + event.lastName);
});</pre>
<p>Instead of caring about the context (or where and how) a message is sent, you just&#8230; get the message.</p>
<p>The same concept applies to Runtime in Corona SDK:</p>
<pre lang="lua">Runtime:dispatchEvent({name="boxDragged", x=event.x, y=event.y, phase=phase})</pre>
<p>And the View/Controller class that will visually update the object. She listens</p>
<pre lang="lua">function controller:init(view)
	self.view = view
	Runtime:addEventListener("boxDragged", self)
	self.originalX = self.view.x
	self.originalY = self.view.y
end

function controller:boxDragged(event)
	self.view.x = event.x + 20
	self.view.y = event.y + 20
	local phase = event.phase
	if phase == "ended" or phase == "cancelled" then
		self.view.x = self.originalX
		self.view.y = self.originalY
	end
end</pre>
<p>Notice Backbone&#8217;s is a custom implementation whereas Corona&#8217;s is a native implementation, built into the platform.</p>
<p>Angular&#8217;s uses a hybrid approach of event using their <a href="http://www.martinfowler.com/articles/injection.html">Dependency Injection</a> system where anyone can reference the top node to hear all events bubbled (emitted) up:</p>
<pre lang="javascript">// listen for it
angular.module("com.company.project.inventory", 
[
	"com.company.project.utils"
])
// shows and hides children UI panels
.controller("UIPanelsController", function($rootScope)
{
	$scope.inventoryShowing = false;

	$scope.onToggleInventory = function()
	{
		$scope.inventoryShowing != $scope.inventoryShowing;

		// <div ng-show="inventoryShowing"></div>
	};
	$rootScope.on("toggleInventory", $scope.onToggleInventory);
});

// use it
angular.module("com.company.project.gameControls", 
[
	"com.company.project.utils"
])
.controller("GameControlsController", function($scope)
{ 
	// angular template be all like 
	// &lt;button ng-click='onToggleInventory()'&gt;Show Inventory&lt;/button&gt;
	$scope.onToggleInventory = function()
	{
		$scope.$emit("toggleInventory");
	};
});</pre>
<p>You send whatever you want. You can send wherever you want; doesn&#8217;t matter if within a button click handler, a deeply nested list, or somewhere in the bowels of your ajax code parsing whack JSON from a middle tier.</p>
<p>This simplicity and flexibility made Underscore and others of its ilk a lot more popular than the verbose Event system. Easier to learn, easier to integrate anywhere, and easier to read. You can still use events for UI related concerns to keep the bubbling and cancelable functionality, but for everything else in Application (what your app does) and Business logic (what back-end your app talks to and how), you can simply use a pub sub library. This is why they&#8217;re popular amongst MVC frameworks.</p>
<p>While Underscore doesn&#8217;t cover all the cool pub sub libraries out there, it&#8217;s the most approachable and gives you enough to be uber effective in understanding one basic approach to pub sub.</p>
<p><A name="pubsubpros"></a></p>
<h3>Pub Sub Pros</h3>
<p>At their core, any &#8220;thing&#8221; in pub sub can publish a message. Any &#8220;thing&#8221; can subscribe to that message. A message can be whatever you want. They&#8217;re flexible, easy to grasp, and reasonably easy to debug if their dispatch function isn&#8217;t overly verbose.</p>
<p>Callbacks only support 1, but pub sub supports many. Pub sub have a more obvious API to subscribe and unsubscribe to messages and to particular messages than callbacks. They don&#8217;t expose nested UI parameters in their function signatures like Events do for addEventListener, nor do they care about where they&#8217;re dispatched from; if someone is listening for their message, they&#8217;ll get it. There is no native functionality to worry about canceling, so that too isn&#8217;t thrown in the API of messages where only 1% would actually have their preventDefault called.</p>
<p><A name="pubsubcons"></a></p>
<h3>Pub Sub Cons</h3>
<p>What pub sub lacks that events has, this makes it basically assumed you&#8217;ll never use it for UI. Instead, you&#8217;ll use it in some form of MVC; whether intentional or not, to communicate UI concerns to higher level classes that DO things when someone clicks a UI element or some class needs to broadcast it has new data if any of those UI controls want to show it.</p>
<p>If for whatever reason you want to stop others from getting events, you can&#8217;t unless for some weird reason the API supports removing all currently subscribed listeners from the stack of a subscriber&#8217;s current callback execution (which isn&#8217;t elementary to support, mind you; many an experienced programmer has created messaging bugs forgetting this common use case). Most Stream API&#8217;s have this functionality, either by pausing the broadcaster from the listener at a bare minimum.</p>
<p>You can also get into race conditions where a subscriber subscribes too late and misses one or many messages. This leads to a lot of weird &#8220;orchestration&#8221; code to ensure all views and controllers are registered for services start loading data that the UI wouldn&#8217;t be ready to &#8220;handle&#8221;. There is no &#8220;did I miss any?&#8221; functionality unless the API has clever ways to do so. Promises and Stream fix this problem.</p>
<p>More importantly, though, you start to get into &#8220;message hell&#8221; as your application grows. Unlike callbacks which can be solved by flattened Promises, pub sub messaging systems are a global message hell. Everyone sharing the same telephone, like an 80&#8217;s sitcom. They can be way worse when under a deadline with lots of code. You&#8217;re constantly following the path of a message through various unrelated classes just to update a piece of data or scope. What set out to be a nice way to enforce encapsulation ends up being an unassuming tool that creates confusion and an unwieldy code base to debug. The key is to isolate concerns and treat pub sub as a &#8220;global&#8221; or &#8220;Singleton&#8221;. Once it&#8217;s viewed in that light, it makes it easier to only use when necessary. </p>
<p>Pub sub aren&#8217;t in those ECMA specs, nor natively implemented as new features in the browsers, nor as API&#8217;s in the new languages because of the issues mentioned above.</p>
<p>Everyone uses Pub Sub anyway because it&#8217;s extremely useful whether in games or applications.</p>
<p><a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-3-of-7-events.html" class="btn btn-primary">&lt;&lt; Part 3 &#8211; Events</a> | <a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-5-of-7-promise-and-deferred.html" class="btn btn-primary">Part 5 &#8211; Promise and Deferred &gt;&gt;</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Message Systems in Programming: Part 3 of 7 &#8211; Events</title>
		<link>https://jessewarden.com/2014/12/message-systems-in-programming-part-3-of-7-events.html</link>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Wed, 24 Dec 2014 15:54:33 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[callbacks]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[eventemitters]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[promises]]></category>
		<category><![CDATA[publish]]></category>
		<category><![CDATA[pubsub]]></category>
		<category><![CDATA[streams]]></category>
		<category><![CDATA[subscribe]]></category>
		<category><![CDATA[tutorial]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=4722</guid>

					<description><![CDATA[Events Events in JavaScript (and EventEmitters in Node.js) allow 1 to many; meaning 1 dude or many people can listen for the same event without the developer having to add more code to the sender. Events also solve with finality the parameter order problem. There is only ever 1 parameter: The Event. Callbacks, Promises, and [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a name="events"></a></p>
<h2>Events</h2>
<p>Events in JavaScript (and EventEmitters in Node.js) allow 1 to many; meaning 1 dude or many people can listen for the same event without the developer having to add more code to the sender.</p>
<p>Events also solve with finality the parameter order problem. There is only ever 1 parameter: The Event. Callbacks, Promises, and Streams can have none, or many. In dynamic languages, you have no compiler help with this. Since most Events are an object of some type, you can add as many slots as you want without changing the interface between sender and receiver. This slightly improves the ability to refactor. In strongly typed languages, the surface API doesn&#8217;t change, only the internal consumption which is often opt-in, thus helping keep OOP things OOP. w00t to the w00t. Moot point is moot.</p>
<p><span id="more-4722"></span>The most common example you see is listening for a mouse click on a button in JavaScript web development, shown in <a href="http://www.typescriptlang.org/Playground">TypeScript</a>:</p>
<pre lang="typescript">function clickHandler(mouseEvent:MouseEvent)
{
	console.log("a mouse click:", mouseEvent);
}

myButtonOrDiv.addEventListener(MouseEvent.CLICK, clickHandler);
// or if strong-typing ain't yo thang,
// da first parameter is always a String, cha-ching!
myButtonOrDiv.addEventListener("click", clickHandler);</pre>
<p>You setup your handler, which is a function, that runs when the event fires. In this case, when the user clicks the mouse. Sometimes it&#8217;s called an &#8220;event handler&#8221;, other times an &#8220;event callback&#8221;. Same thing.</p>
<p>Either way, looks like a callback, right? While they are like callbacks, all event handlers, or handlers for short, take an event as the first and only parameter. Every event that fires, whether built in ones like MouseEvents, or custom ones you make and fire yourself, has the same API.</p>
<p>If you want to stop listening for mouse events, you simply remove your listener:</p>
<pre lang="typescript">myButtonOrDiv.removeEventListener(MouseEvent.CLICK, clickHandler);
// or without strong-typing
myButtonOrDiv.addEventListener("click", clickHandler);</pre>
<p>If you want have many listeners, simply add it.</p>
<pre lang="javascript">function clickHandler1(mouseEvent)
{
	console.log("a mouse click in handler 1:", mouseEvent);
}

function clickHandler2(mouseEvent)
{
	console.log("a mouse click in handler 2:", mouseEvent);
}

myButtonOrDiv.addEventListener("click", clickHandler1);
myButtonOrDiv.addEventListener("click", clickHandler2);</pre>
<p>Notice how clickHandler2 is a completely different function. If you were to use the same function, it would NOT register an additional event.</p>
<pre lang="javascript">function clickHandler1(mouseEvent)
{
	console.log("a mouse click in handler 1:", mouseEvent);
}

function clickHandler2(mouseEvent)
{
	console.log("a mouse click in handler 2:", mouseEvent);
}

myButtonOrDiv.addEventListener("click", clickHandler1);
myButtonOrDiv.addEventListener("click", clickHandler1);
// click on button, results in:
// a mouse click in handler 1: MouseEvent {dataTransfer: null, toElement: div#clickit, fromElement: null, y: 14, x: 45â€¦} 
</pre>
<p>Note there are SOME Publish Subscribe libraries and API&#8217;s out there that support such functionality; i.e. multiple addListener calls to the same function pointer result in multiple event registrations, and thus you&#8217;ll need to do as many to un-register them. However, those kind of API&#8217;s put a burden on the developer to remember how many they registered, or an obtuse API to query for this number, so it&#8217;s assumed the function/object/table pointer are sufficient for a single registration since you only expect that callback to be called once per event. If another dude needs to know about it, he&#8217;ll actually be a &#8220;true other dude&#8221; vs. an additional pointer pointing to the same function.</p>
<p><A name="customevents"></a></p>
<h3>Custom Events</h3>
<p>The power of events in client side JavaScript is your ability to create your own and tap into the API. While many other frameworks have illustrated this concept like <a href="http://backbonejs.org/">Backbone&#8217;s</a> <a href="http://marionettejs.com/">Marionette</a> and Angular&#8217;s <a href="https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$broadcast">$broadcast<a/> and <a href="https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$emit">$emit</a>, <a href="https://www.polymer-project.org/">Polymer</a> is one of the first to embrace the native JavaScript API for the actual <a href="http://davidwalsh.name/customevent">CustomEvent</a> part via <a href="http://www.polymer-project.org/docs/polymer/polymer.html#fire">fire</a> and asyncFire, not to be confused with <a href="https://www.youtube.com/watch?v=r32LcBqiv7I">zee German&#8217;s FIIIRRREEEE!!1oneone</a></p>
<p>The idea of dispatching custom events for many potential listeners to subscribe to is common place and accepted even if the mechanisms for doing so vary between languages and platforms.</p>
<p>Say you&#8217;re building a component for form input and you want to dispatch event when everything is done: all inputs, all validations, and all data formatting. While you could listen for the &#8220;click&#8221; event on the Submit button, you&#8217;d still have to either manually re-trigger all the forms validations again (assuming you have a real-time time form validation here), and once complete, THEN you know it&#8217;s truly submitted. The 2 problems with that are that you&#8217;re making the consumers of the form deal with that, and that&#8217;s not very OOP encapsulated of you.</p>
<p>The better strategy is to create a View; a class that handles all of those concerns where they are, lets those who want to use it know: when is the form ready. Your code can do all that form validation, and then at the end, simply:</p>
<pre lang="javascript">someDOMNode.dispatchEvent(new CustomEvent("formCompleted"));</pre>
<p>And registering for it?</p>
<pre lang="javascript">function onFormCompleted(event)
{
	console.log("Form's complete, yo!");
}
someDOMNode.addEventListener("formCompleted", onFormCompleted);</pre>
<p>To get multiple listeners, simply go:</p>
<pre lang="javascript">someDOMNode = document.createElement('div');
function onFormCompleted(event)
{
	console.log("Form's complete, yo!");
}

function onFormCompleted2(event)
{
	console.log("check it, form's done mah man.");
}

var cow = {
	onFizzOrm: function(e)
	{
		console.log("moo and stuff, form's done and stuff.");
	}
};

someDOMNode.addEventListener("formCompleted", onFormCompleted);
someDOMNode.addEventListener("formCompleted", onFormCompleted2);
someDOMNode.addEventListener("formCompleted", cow.onFizzOrm);
someDOMNode.dispatchEvent(new CustomEvent('formCompleted'));
// Form's complete, yo!
// check it, form's done mah man.
// moo and stuff, form's done and stuff.</pre>
<p>You&#8217;ll notice I passed an object&#8217;s method in the 3rd listener. Again, as long as it&#8217;s a function, she&#8217;ll work, regardless of where she&#8217;s located. #scopeLoversPizzaBeware</p>
<p><A name="wrappers"></a><H3>Wrappers</h3>
<p>Some languages provide Event dispatching as a core mechanism that can be optionally added to DisplayObject tree&#8217;s. Sadly <a href="http://www.w3.org/TR/DOM-Level-2-Events/ecma-script-binding.html">ECMAScript</a> requires <a href="http://en.wikipedia.org/wiki/Document_Object_Model">Document Object Model</a> (called DOM for short) elements. This means you cannot use Event dispatch capabilities in your data layer (code that has nothing to do with View&#8217;s, HTML, CSS, div&#8217;s, etc). This is often why many frameworks tend to eschew Events for View level concerns, and use their own pub sub library for Controller and Model level concerns. It&#8217;s also funny to see Polymer do it <a href="http://flex.apache.org/">like Flex did</a> where you have an http call co-chilling next to a bar chart and they be all like, &#8220;Sup dawwwwg, I&#8217;m bound to you, and you to me, and we&#8217;re separated by just 1 line break&#8230; small world, right!?&#8221;  </p>
<p><a href="http://backbonejs.org/">Backbone</a> assumes you&#8217;ll use <a href="http://jquery.com/">JQuery</a> for DOM level concerns and Events, but will use <a href="http://backbonejs.org/#Events">Backbone.Events</a> as a way for Views and Models to talk to each other. <a href="https://angularjs.org/">Angular</a> actually embraces this DOM lover scenario with <a href="https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$emit">emit</a> and <a href="https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$broadcast">broadcast</a>. Polymer embraces the basic event structure of CustomEvents with a wrapper method called <a href="http://www.polymer-project.org/docs/polymer/polymer.html#fire">fire</a>. Node&#8217;s got <a href="http://nodejs.org/api/events.html">EventEmitters</a>, but has no event bubbling capabilities &#8217;cause there ain&#8217;t no DOM on the server in the API code.</p>
<p><A name="eventbubbling"></a></p>
<h3>Event Bubbling</h3>
<p>If you&#8217;ve ever built composite GUI&#8217;s, i.e. components that contain components, then you&#8217;ll understand the concept of event bubbling pretty quickly. For those familiar with Angular, it&#8217;s similar to <a href="https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$emit">$scope.$emit</a>.</p>
<p>Considering a UI is built from clickable parts that can contain other clickable parts, no longer is it as simple as &#8220;I clicked on this thing here&#8221;. When you stack 20 things on top of each other, which one did you really click on? You&#8217;d think the one on top, but EACH thing gets its own click event. To be clear, &#8220;things&#8221; in the HTML world is <a href="http://en.wikipedia.org/wiki/Span_and_div">div</a>, or more specifically Node (not Node.js) and <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget">EventTarget</a> mashed together. While people traditionally think of buttons and other controls as the things you click on, nowadays not so much.</p>
<p>Many controls are not easily skinnable, are missing functionality, or work differently across different browsers vs. mobile. Some are even made of <a href="http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/">ShadowDOM</a> parts. For these reasons divs are often what you click on. These divs can also contain other divs which are effectively components/buttons/controls in their own right.</p>
<pre lang="html"><!-- you can click on both of these things -->
<button>Click Me</button>
<div>Click Me</div></pre>
<p>Sometimes you just want to know &#8220;the user clicked on the Submit button in the form&#8221;; whether it&#8217;s an actual &lt;button&gt;, a div you&#8217;ve decorated, or a series of things inside a ShadowDOM custom web component. Other times you want to know &#8220;the user clicked on the form itself&#8221;. While still other times you want to know &#8220;the user clicked on item 39 of that long list buried deep in the dom sea&#8221; or in your custom draggable window &#8220;the user clicked on the header bar, not the window contents, thus I should start dragging the window&#8221;. That last one is a capture phase, when bubbling goes the opposite way, like tears in the rain.</p>
<p>In my <a href="http://adobe.com/products/flash/">Flash</a> and <a href="http://flex.apache.org/">Flex</a> experience, the use cases for actually using event bubbling are rare. The only ones I&#8217;ve used consistently are for lists, when creating draggable containers such as video game UI&#8217;s or emulating a windows based interface, or for <a href="http://martinfowler.com/eaaDev/SupervisingPresenter.html">Supervising Controller frameworks</a>.</p>
<p>Bubbling up items in some form of list or datagrid control so I can write the click event handler in 1 place instead of adding for each item. If I have 100 listen items, I don&#8217;t want to add 100 click handlers. Instead, you add 1, and any click that happens within the list is bubbled up to you. The same technique is used for tile based games such as a tower defense or point and click to walk to tile game. You don&#8217;t want a click handler for each tile in a hundred to thousand tile grid; you just want 1 and you use the X and Y values to do the math on what tile you clicked on.</p>
<p>For example, lets say you&#8217;ve created a dynamic list and want to know what piece of data the user clicked on.</p>
<p>You have to correlate the index number of the list item and use it to access the data in the Array. Now, in a simple world you could do so like this using the event&#8217;s target property to identify which of the list items was clicked on:</p>
<pre lang="html" line="1" escape="false">&lt;ol id="myList"&gt;&lt;/ol&gt;

&lt;script&gt;
data = ["Uno", "Dos", "Tres"]; 
list = document.getElementById('myList');

function itemClicked(item)
{
	console.log("you clicked on item:", item);
}

data.forEach(function(item)
{
	var listItem = document.createElement("li");
	listItem.innerHTML = item;
	list.appendChild(listItem);
	list.addEventListener("click", function(event)
	{
		itemClicked(item);
		console.log(event);
		event.stopImmediatePropagation();
	});
});
&lt;/script&gt;&lt;/pre&gt;</pre>
<p>You&#8217;ll notice on line 17, we create a new anonymous function for each list item. Since it&#8217;s created in that context, it retains a unique link to the item that was used to create it. This is nice; whenever it&#8217;s clicked on, we know which item it represents, and call itemClicked with it.</p>
<p>The bad? Really dude? A listener for EACH list item? What if you have a hundred or more list items, or the list redraws often? You&#8217;ll end up with a ton of listeners, many of which you&#8217;ll then later throw away. Dat shiz cray. You&#8217;ll make the Garbage Collector work overtime, and potentially get jank on your animations. Also notice we&#8217;re turning event bubbling OFF on line 21. I&#8217;ll explain that in a bit.</p>
<p>Let&#8217;s show how you make event bubbling work for you vs. against you:</p>
<pre lang="javascript" line="1">data = ["Uno", "Dos", "Tres"]; 
list = document.getElementById('myList');

function onItemClicked(event)
{
	console.log("you clicked on: " + event.target.getAttribute("data-item"));
}
list.addEventListener("click", onItemClicked);

data.forEach(function(item)
{
	var listItem = document.createElement("li");
	listItem.setAttribute("data-item", item);
	listItem.innerHTML = item;
	list.appendChild(listItem);
});</pre>
<p>The same technique goes for any DisplayObject based framework where you use many different vector shapes, bitmaps, or whatever to composite together to form an interface. It isn&#8217;t always flat.</p>
<p>Not all events bubble by default, but MouseEvents do.</p>
<p>The above is just 1 level deep, but the rabbit hole goes much deeper. The 2nd, less used use case is when you have some sort of View, whether a Backbone or <a href="http://emberjs.com/">Ember</a> child View, or even an Angular Controller. Much like the List example above, these are actual Views. They could just be a List item with some slightly extended functionality, or perhaps they&#8217;re complex Web Components using mad amounts of composition of other Views within them. Higher level Views are delegated with the responsibility of handling application level events such as navigating to other places in the View, basically things that deal with user interactions that don&#8217;t affect data.</p>
<p>In Backbone/Ember&#8217;s case, you simply dispatch your own events, except you ensure bubbling is true. They&#8217;ll wind their way up the DOM so those higher level Views can hear those events. This has the side benefit of not caring if you refactor your Views later because no matter where those child Views are, their message will be received.</p>
<pre lang="javascript">// some random child View
dispatchEvent("userClickedOnShowInventory", true);</pre>
<p>Note the 2nd parameter; it&#8217;s false by default.</p>
<p><A name="stoppingeventbubbling"></a></p>
<h3>Stopping Event Bubbling</h3>
<p>You can stop events from bubbling up further by either stopPropagation or stopImmediatePropagation.</p>
<p>These are hard to remember the difference, so here&#8217;s a definition of both written by an art major vs. a computer scientist.</p>
<p>Think of stopPropagation as &#8220;stop bubbling&#8221; and stopImmediatePropagation as &#8220;stop everything&#8221;. The word &#8220;immediate&#8221; should help you remember &#8220;omg, stop all the bubbling things!&#8221;.</p>
<p>The stopPropagation method will stop all event bubbling to any parents of the current element, but if other people have click events registered at your level, they&#8217;ll get their event handlers run in the same call stack. The stopImmediatePropgation stops everything after your handler is done executing.</p>
<p>Showing the modified example above, we&#8217;ve nested our list in 2 additional container divs, and added additional click handlers to them to see bubbling in action, and see what happens when we stop it. Observe:</p>
<pre lang="html">&lt;div id='appUpInThisMug'&gt;
	&lt;div id='datContainerThough'&gt;
		&lt;ol id="myList"&gt;&lt;/ol&gt;
	&lt;/div&gt;
&lt;/div&gt;</pre>
<p>And our updated code:</p>
<pre lang="javascript">data = ["Uno", "Dos", "Tres"]; 
list = document.getElementById('myList');

function onItemClicked(event)
{
	console.log("you clicked on: " + event.target.getAttribute("data-item"));
}
list.addEventListener("click", onItemClicked);
data.forEach(function(item)
{
	var listItem = document.createElement("li");
	listItem.setAttribute("data-item", item);
	listItem.innerHTML = item;
	list.appendChild(listItem);
});

function onContainerClicked1(event)
{
	console.log("onContainerClicked1");
}
function onContainerClicked2(event)
{
	console.log("onContainerClicked2");
}
var container = document.getElementById('datContainerThough');
container.addEventListener("click", onContainerClicked1);
container.addEventListener("click", onContainerClicked2);

var app = document.getElementById('appUpInThisMug');
app.addEventListener('click', function(event)
{
	console.log("app clicked 1");	
});</pre>
<p>When you click any in the list, you get:</p>
<p>you clicked on: Uno<br />
onContainerClicked1<br />
onContainerClicked2<br />
app clicked 1 </p>
<p>Cool, the list item gets his click first, it then bubbles up to the 2 container listeners, and finally to the top at app.</p>
<p>Let&#8217;s just stop all bubbling when it gets to the container:</p>
<pre lang="javascript">function onContainerClicked1(event)
{
	console.log("onContainerClicked1");
	event.stopPropagation();
}</pre>
<p>We now get:</p>
<p>you clicked on: Uno<br />
onContainerClicked1<br />
onContainerClicked</p>
<p>Notice the 2nd container still gets to run, but bubbling beyond that level has been stopped.</p>
<p>If we swap out stopImmediatePropagation:</p>
<pre lang="javascript">function onContainerClicked1(event)
{
	console.log("onContainerClicked1");
	event.stopImmediatePropagation();
}</pre>
<p>You see only the 1st bubbled event is fired, but his sibling and his parent are not:</p>
<p>you clicked on: Uno<br />
onContainerClicked1</p>
<p>You use stopImmediatePropagation if you want to ensure a bubbled event you know is up there somewhere isn&#8217;t fired. This can happen in games. It can also be useful when creating deeply nested Views and you&#8217;re manually propagating your own custom events that have more meaning than &#8220;click&#8221;.</p>
<p>I have no idea why you&#8217;d ever use stopPropagation.</p>
<p><A name="eventcancelling"></a></p>
<h3>Event Cancelling</h3>
<p>Another feature of events typically used mostly in UI operations is event cancelling. It&#8217;s sometimes used conjunction with event bubbling, but the more common use case is for stopping functionality from happening you don&#8217;t want to happen, thus a supported way of opt-ing out.</p>
<p>For example, by default an anchor tag will navigate the browser to whatever URL you&#8217;ve put in the href attribute. You can simply stop this behavior by calling preventDefault. This is different in event bubbling in that even if the event bubbles up, whatever native behavior the browser is supposed to do, it now won&#8217;t.</p>
<p><A name="eventpros"></a><H3>Event Pros</h3>
<p>You use events when you want to have multiple people hear abeout the same change. Callbacks are 1 to 1, whereas Events are 1 to many.</p>
<p>Events provide flexibility to emitting many different changes from a single object. For example, we can emit both MouseEvents, KeyboardEvents, and FocuseEvents all from the same Button. You can even give fine grain context about the event, such as a mouse up event vs. a mouse down event, or which key was pressed in the keyboard down event. Callbacks can do this as well, but again, only 1 object can hear about it.</p>
<p>Most events we care about in JavaScript web development support this format, as do Flash &amp; Flex, <a href="http://coronalabs.com/products/corona-sdk/">Corona SDK</a> using <a href="http://www.lua.org/">Lua</a>, and many others. It&#8217;s a common way of doing 1 to many message systems.</p>
<p>As you can already see, events prevent the parameter order problem; events are objects so order doesn&#8217;t matter.</p>
<p>You&#8217;ll notice that the event names are strings. This means you can create your own events with any name you want as long as it doesn&#8217;t conflict with built in ones such as &#8220;click&#8221;, &#8220;onfocus&#8221;, etc. This makes them flexible and easy to work with, even in strongly-typed languages.</p>
<p>For GUI systems, if you&#8217;re dealing with a bunch of lists or nested Views that handle application level events ONLY related to UI concerns, the bubbling can come in handy by reducing how many event listeners you need to create. This also makes handling View level concerns easier through Composition vs. letting a framework deal with it.</p>
<p>For asynchronous operations, finite state machines, or operations that take some random amount of time and may not succeed, events are perfect.</p>
<p><A name="eventcons"></a><H3>Event Cons</h3>
<p>You can&#8217;t object pool them in most frameworks. If you are dispatching many different events, each one is a unique object created, usually with an assumed limited lifetime, which has a performance impact both in creation as well as in garbage collection. It&#8217;s not noticeable in applications, more so in games.</p>
<p>Events on the client have also fallen out of fashion long ago for a variety of reasons. Yes, we have things &#8220;in fashion&#8221; in programming. It doesn&#8217;t mean those out of fashion are bad, it&#8217;s just harder to start a conversation with some people when you talk about the &#8220;boring&#8221; things.</p>
<p>First reason is JQuery&#8217;s rise to fame and it improving upon the events API via it&#8217;s own callbacks, not to be confused with the callbacks I&#8217;ve described at the top of this article. Keep in mind everything I described too is not the same cross browser. Different versions of IE, older versions of Firefox, etc. are all different. JQuery helped make all of that sane to work with, and developed it&#8217;s own conventions.</p>
<p>Events are very div specific whereas JQuery encourages you (vs. make you) think more in selectors, classes, and ID&#8217;s. Simple features help the sale, too, like an option to have an event only fire once. The syntax is a lot smaller too.</p>
<p>Second reason is pub sub messaging frameworks started popping up in JavaScript that helped provide a tighter syntax, better cross browser support, and worked in both UI and non-UI code. Basically globally; anywhere in your code. Most pub sub libraries could receive a message regardless if they were defined in UI code or application framework code. Events on the other hand don&#8217;t, they get cloned if you manually re-dispatch, and bubbling is strictly tied to the DOM tree. This is why <a href="http://nodejs.org/">Node.js</a> developed their own <a href="http://nodejs.org/api/events.html">EventEmitter</a>.</p>
<p>Third reason is that JQuery helped continue to fuel the Functional Programming momentum that Python and <a href="http://rubyonrails.org/">Ruby on Rails</a> helped popularize. This eventually matured to Reactive Programming which cemented things like Promises, Deferred, Observers, and Event Streams into standard (read: &#8220;cool and new and I must use it everywhere&#8221;) ways of doing GUI programming on the web. Kind of like how wearing Axe body spray makes you cool even if you weren&#8217;t before. Yeah.</p>
<p>Examples often cited include <a href="http://callbackhell.com/">&#8220;callback hell&#8221;</a> where dealing with multiple callbacks from asynchronous events results in a ton of &#8220;event registrations up top, handler soup at the bottom&#8221;. Worse is when you start nesting these callbacks like out of control if/then statements, and it&#8217;s basically hard to read and debug. Utilizing functional programming patterns makes the code easier to read and easier to debug.</p>
<p>Events have this awkward place in Reactive Programming, at least for the front-end, in that they are now merely a potential delivery message, and no longer the way to register and dispatch messages, thus keeping single parameter/result advantage that events have. Languages like Dart still support using both, but discourage their use indirectly by espousing their nice Reactive Programming implementation via Futures (Promises) and Streams.</p>
<p>Those using Streams intentionally avoid the 1 to many support Events have by continually merging streams of complex systems to funnel all events into 1 pipeline, leaving it to the consumer to filter out the events they want. On top of a View layer, this can work fine, but not within a View layer where events still reign supreme.</p>
<p>They aren&#8217;t going away in that all browsers support the basic ones for mouse events, touch events, keyboard events, focus, and form events to name a few. Most code nowadays, however, abstracts them away into a less verbose API.</p>
<p>They also survive in other languages that allowed a flattening of UI tree, such as Flash&#8217;s <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/EventDispatcher.html">EventDispatcher</a> and Corona&#8217;s <a href="http://docs.coronalabs.com/api/type/EventListener/index.html">EventListener</a> (which has View and Global versions). This, flattening the UI vs. using event bubbling, is especially important when you bring in OpenGL/3D functionality because you want as little composition as possible, so things like event bubbling constitute a code smell.</p>
<p><a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-2-of-7-callbacks.html" class="btn btn-primary">&lt;&lt; Part 2 &#8211; Callbacks</a> | <a href="http://jessewarden.com/2014/12/message-systems-in-programming-part-4-of-7-publish-subscribe.html" class="btn btn-primary">Part 4 &#8211; Publish Subscribe &gt;&gt;</a></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
