<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by David Souther on Medium]]></title>
        <description><![CDATA[Stories by David Souther on Medium]]></description>
        <link>https://medium.com/@davidsouther?source=rss-79ccc1b90972------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-k0qawQam-SZDoX1.jpg</url>
            <title>Stories by David Souther on Medium</title>
            <link>https://medium.com/@davidsouther?source=rss-79ccc1b90972------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 04:22:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davidsouther/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Song Flux]]></title>
            <link>https://medium.com/@davidsouther/song-flux-e1f9786579f6?source=rss-79ccc1b90972------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1f9786579f6</guid>
            <dc:creator><![CDATA[David Souther]]></dc:creator>
            <pubDate>Mon, 02 Feb 2015 16:16:14 GMT</pubDate>
            <atom:updated>2015-02-02T16:16:14.918Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Elegantly Fluxing the Angular Way</em></strong></p><h3>What is Flux?</h3><p>Flux is an approach to building large GUI applications popularized by Facebook’s React library. Characterized by <strong>enforcing a single data flow</strong>, flux guarantees certain behaviors and patterns when data moves through an application. These guarantees make it easier to reason about code, making applications and their modules more reliable, composable, and scalable. With better reasoning also come better techniques and tools to highlight and exorcise bugs. The potential for side effects, and time spent hunting bugs, is drastically reduced compared to similar MVC designs.</p><p>Song Flux is the Flux library adapted for use in Angular JS projects. Created by my colleague Gabo Obregon (<a href="https://twitter.com/gah_boh">@gah_boh</a>) and myself (<a href="https://twitter.com/david_souther">@david_souther</a>) to experiment with this approach to developing large applications in Angular, it is available on <a href="https://github.com/gah-boh/song-flux">Github</a> or <a href="https://www.npmjs.com/package/song-flux">via npm</a>.</p><p>The prevalent MVC architecture diagram component has three objects and six interactions (<em>Fig 1)</em>, but as applications scale, the clean, linear data flow grows and becomes cluttered (<em>Fig 2).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*FnpYmFlqW5IAM_yoJ6E5EQ.png" /><figcaption>Typical “MVC” triangle. Models notify Controllers and Views with Observable events. Controllers mutate views and state as desired. Views can ask for state at any time, and push user actions to controllers. Angular simplifies and obfuscates with two-way binding.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*G3K2mq_CTxhxFECVn8_g6Q.png" /><figcaption><em>Fig 2: </em>Typical “Data Binding” mishmash in MVVM, arising from loose application architecture and planning. Notice every arrow is two-way, and a new arrow can be added at any time.</figcaption></figure><p>Flux eschews the free-for-all two-way data binding in favor of certain well-defined push mechanisms. In flux, there are four parts to the pattern, each with one incoming and one outgoing data path, for a total of four interactions (<em>fig 3). </em>The pieces are <em>Actions</em>, objects that encapsulate a requested change in state; the <em>Dispatcher</em>, a utility that manages the data flow; <em>Stores</em>, containers and single sources of truth for application data; and <em>Components</em>, reusable and composable UI elements that make the view. In a complex application, the data flow goes from an application with numerous interdependent parts to one with many decoupled parts (<em>fig 4) — </em>any piece can be replaced with a few number of refactorings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*LE1PJQ33YAlNe_RXdeJ-sQ.png" /><figcaption><em>Fig 3: </em>Basic Flux data flow. Dispatchers call Stores with Actions. Components observe stores, and create Actions. Data flows one direction, and one arrow may be active at a time (no new actions while mutating).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*9Plsx78BcJhgfCaYjzLXcw.png" /><figcaption><em>Fig 4</em>: Flux data flow in a complex application. (The dispatcher is a singleton.)</figcaption></figure><p>When the Dispatcher component handles an Action, the dispatcher guarantees no other Actions are simultaneously being dispatched. This eliminates a “mutation cascade”, where a user action triggers some state to mutate, that itself causes some other state to mutate. These cascades can be very difficult to reason about both as a developer who must find the bug in a middle algorithm, or as a user when disparate pieces of the application all change together. Mutation cascades can also commonly have race conditions: either one section of data must be updated before another, or two sections deadlock waiting on the other to finish. In the case that order needs to be preserved between action handlers, the dispatcher has a <em>waitFor</em> method that will ensure correct sequencing events.</p><blockquote>How does this all fit together?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*XTft8PN87Py1HGFrbzS_WQ.png" /><figcaption>The four data paths in the original Flux implementation.</figcaption></figure><p>When the user fills in a new ToDo item in the input and hits ‘enter’, the Component asks the ToDo Action Creators to make a new Action. The Action Creators do so, and pass a TODO_CREATE action to the Dispatcher. The Dispatcher iterates any stores with a registered dispatch handler, passing the TODO_CREATE action to the handler. The ToDo store’s handler looks for the TODO_CREATE event, updating its internal collection of ToDos. After updating the ToDo store emits a Change event, which the ToDo component listens to. Upon receiving the Update event, the ToDo component rerenders, and the application is in a stable state.</p><h3>Song Flux</h3><blockquote>Multiplex by ActionConstructor</blockquote><p>Song Flux provides the Dispatcher component of the Flux architecture, with some modifications. In the original Flux implementation, Actions were a tuple of <em>(const string action, object data)</em>. In Song Flux, Actions are instances of Javascript Constructor Functions. Every type of Action is a function, which will be instantiated with the <em>new</em> operator when created by a component. Stores register not for all dispatched actions, but individually for each type of action the store is interested in receiving. This approach greatly reduces boilerplate overhead of setting up Flux data flows, and does not reduce flexibility or power of the approach.</p><blockquote>Unidirectional Data Flow</blockquote><p>Like the original Flux implementation, Song Flux enforces single action at a time in the Dispatcher. Actions are always dispatched within a <em>$digest</em> loop, either triggered by user action, like an <em>ng-click</em> handler, or as the result of some asynchronous callback, like an <em>$http</em> return. The dispatcher verifies that within an action dispatch, and within a <em>$digest</em> loop, only a single Action is generated. By preventing multiple actions per <em>$digest </em>developers cannot hit the frustrating situation of a mutation cascade, which will often result in the dreaded <em>$infDigest</em> error.</p><p>Song Flux does encourage “traditional” Angular MVVM architecture within reusable components of a web application. The benefits of two-way data binding have demonstrated themselves time and again in the Angular ecosystem. The failing is only when it comes to scaling an application beyond a couple interacting data sources and views.</p><blockquote>Single Actions object</blockquote><p>To consume Actions, the Action constructors must be injected in two places: Stores, for registering an Action handler, and Components, to instantiate and dispatch an Action. Actions can be created and injected individually; however, it was found to be much simpler in practice to combine all Action constructors for a part of the application (generally at the Store module level) into a single injectable <em>Actions</em> object, with each constructor being a property of that object.</p><h2>Song Flux Example</h2><h3>1. Create Action Constructors</h3><p><strong>Trkstr</strong> is a music player. In this code from the application, a <em>PlayAction</em> is dispatched whenever the music player should start playing a new track. Specifically, a Library component will create and dispatch a PlayAction when a user clicks on a track in an album listing. The <em>PlayAction</em> has a reference to which track to play, and a reference to a dispatcher keyed to the ‘<em>trkstr’</em> module, the root module for the entire application. It has a utility method to quickly dispatch itself on that dispatcher.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a262daf279375c9cf07ab7c8328fc35/href">https://medium.com/media/0a262daf279375c9cf07ab7c8328fc35/href</a></iframe><h3>2. Stores register for dispatch</h3><p>and</p><h3>3. Stores mutate single source of data</h3><p>The <strong>PlayerStore</strong> is a data source to manage the currently playing track, or “Nothing Playing…” if everything has been stopped. The PlayerStore extends prototypically from a global <em>EventEmitter</em> ptototype, has a reference to the <em>’trkstr’</em> dispatcher, and manages a set of events to notify listeners when the store’s data mutates. The store registers to any <em>PlayAction</em>s that are emitted, passing them to the <em>play</em> method on its prototype. The <em>play</em> method simply updates the current track and fires the event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6ee568afc3f12938094c43fccd45824/href">https://medium.com/media/b6ee568afc3f12938094c43fccd45824/href</a></iframe><h3>4. Store signals mutation,<br>component renders data</h3><p>The PlayerComponent is a combination of a traditional Angular Directive, Controller, and Template. The Directive is fairly thin, but uses a Directive Factory pattern. Rather than simply being a function, the Directive is a class with a static method to return new instances as needed. The Directive constructor then sets the typical Directive Definition properties on itself. By convention, the Directive exposes the controller as <em>state</em> to the Template; the component always uses an isolate scope; and the isolate scope properties (none in this example) are attached to the Controller instance. The controller itself watches for the TrackChanged event, where it updates the isolate scope <em>track</em> variable and lets traditional two-way databinding drive the update to the audio’s <em>src</em> attribute.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c14d3242fe6a75e0360cfb88adb12215/href">https://medium.com/media/c14d3242fe6a75e0360cfb88adb12215/href</a></iframe><p>The template just binds to the current track title and path, letting the HTML5 audio tag do the heavy lifting.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27373f98093006ff892e9b479a7651c7/href">https://medium.com/media/27373f98093006ff892e9b479a7651c7/href</a></iframe><h3>5. On user interaction, component sends new Action to dispatcher</h3><p>This excerpt from the Library Component manages a list of Albums and their tracks. The Library manages a collection of albums and their track listings. The template iterates those listings, and when a user clicks a track the <em>ng-click</em> binding executes the Controller’s <em>play</em> action inside a <em>$scope.$digest</em>. The <em>play</em> method creates a new PlayAction with the track and dispatches. The dispatcher sends it to the handler registered at <em>PlayStore.prototype.pla</em>y. The PlayStore triggers a <em>TrackChanged</em> event. The <em>Player</em> Component sees the new track. The <em>$digest</em> is still in progress, so it updates the new (primitive string) value. The Dispatch backs out, the <em>$digest</em> settles, and the Audio tag begins playing the new track.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/504a45b0697bee20152cf5eeece7664c/href">https://medium.com/media/504a45b0697bee20152cf5eeece7664c/href</a></iframe><h2>The Architecture, Explained</h2><p>Angular developers should be familiar with the common “injectable concepts” — <em>services</em>, <em>factories</em>, <em>filters</em>, <em>directives</em>, etc. Song flux introduces three new concepts, as well as the Song Factory for creating dispatchers per module. The three new concepts are <em>stores</em>, an extension of factories; <em>components</em>, a combined <em>directive</em>, <em>controller</em>, and <em>template</em>; and <em>actions</em>, instantiable functions representing Flux actions.</p><blockquote>Store — Single Source of Truth</blockquote><p>A Store is an extension on top of ServiFactoProviders. Stores are expected to be the single source of truth for a particular bit of data in an application. Stores are the only code that registers to receive dispatched events. Stores can expose their registration hooks, to allow Stores to explicitly declare asynchronous</p><blockquote>Component — Read-only reference to SSOT &amp; internal view logic</blockquote><p>A Component is a combination of a Directive, a Controller, and a Template. Components themselves follow the data-bound MVC approach very closely, but do so in isolation. The Directive exposes the Component in HTML; the Controller listens for events from the Stores the component is interested in, and the Template provides the HTML for the view. Song Flux recommends that Component Directives always use isolate scopes in conjunction with bindToController, and always set <em>controllerAs</em> to <em>state</em>. Controllers should be instantiable functions, should have Actions and Stores injected, and should listen to Store mutation events to update internal data. Templates should only include local binding and data, isolating dependence on other components through known properties exposed by the controller. User interaction should have templates call controller methods, which create and dispatch Actions.</p><blockquote>Action: Encapsulate a request to change state</blockquote><p>An Action is an object that represents a request to change application state. In traditional MVC a user action would trigger a method on a controller, which directly updates state in the model. Flux decouples this interaction. While the vast majority of time a dispatched action will go directly to some store and result in updated state, Flux decouples these to allow for creating more complex interaction flows. In the canonical examples, this is used when a store calculates meta data, but wants to guarantee the store handling the data itself has a chance to update the base data list. In Song Flux, Actions are instantiable function constructors. This allows the Action Constructor itself to be used as a key for registering and dispatching, rather than relying on pattern matching strings.</p><blockquote>Dispatcher: Utilities, EventEmitter, etc</blockquote><p>The dispatcher and other utilities are provided by Song Flux, and have APIs similar to their Facebook counterparts. Eventing must happen separately — the Angular <em>$scope</em> eventing mechanism shows its weaknesses using more structured architectures. Advanced projects can play with using immutable data structures backing the data in Stores.</p><h3>Benefits</h3><blockquote>Bugs are obvious</blockquote><p>Bugs now live in one of two places: business algorithms, flux application wiring. When debugging and testing, all data is immediately local and numerous common issues can be detected by the library at runtime. This includes dispatching incorrect events, or tying to an action to the wrong module namespace.</p><blockquote>Testing: super isolated, super mockable</blockquote><p>Because each section of code relies only on a single object with a well-known type signature or shape, any piece of the application can be pulled out and replaced with a mock, stub, or spy. Components can be given a piece of mock data, rendered, and have their DOM inspected independent of the implementation of the data store. Stores can be filled with mock data, dispatched Actions, and spied on to assert mutation events were fired and that data was mutated correctly.</p><blockquote>Highly decoupled (see below)</blockquote><p>Want to go crazy? Have your AB test selectively change the template and component code. The store doesn’t care, your component only needs to know the given data structure and Actions available. Change the backing persistence store on the fly from immutable in-memory to LocalStorage to a REST backend. The component doesn’t care, the store only has to fire mutation events and provide an encapsulated (or dare I say, open/closed) interface for components.</p><h3>Cons</h3><blockquote>Trades complexity- 4 things before you see progress</blockquote><p>One huge early draw of Angular JS was (and is) the ease at which anyone with a little HTML knowledge can immediately build rich interactions on the web. As projects scale in codebase, developer contributions, and user base, an enforced architecture grows ever more critical. With an approach like Song flux, the barrier to entry rises- to see any result on screen, four objects must be instantiated and wired together.</p><blockquote>Team decisions- create constructor vs create action</blockquote><p>The architecture is not “complete” — there are many decisions teams must make in what idioms they will use for their project. Do Actions self-dispatch? Does a factory create an action constructor or an action instance? Song Flux does not care which one is used leaving the decision purely to the team and project.</p><blockquote>Highly decoupled (see above)</blockquote><p>Along with the first con, the application becomes massively decoupled. There are in fact more moving parts, even if there are fewer places for the parts to be moving. Within components, UI specific data still flows in the “traditional” angular <em>$digest</em> way. This approach might not be for the weekend warrior projects. It is hard to see the benefit until applications get to the size of several interacting pieces.</p><h2><strong>Go Forth and Create</strong></h2><p><strong>I thought the switch from jQuery to Angular was a tumultuous time for the web — it seems that was just a precursor to the “framework wars” of 2015. My challenge to other developers is to take the best pieces from any and all of the projects, see what works well together, and build great software.</strong></p><p><strong>You can get started with Song Flux in your angular applications today, by including the </strong><a href="https://github.com/gah-boh/song-flux"><strong>Song Flux</strong></a><strong> repository from </strong><a href="https://twitter.com/gah_boh"><strong>@gah-boh</strong></a><strong> —<br><em>npm install song-flux</em></strong></p><p><em>If you would like help or advice adapting this approach to your project, give me a shout </em><a href="https://twitter.com/david_souther"><em>@david_souther</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1f9786579f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>