<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title>Learn Mithril</title>
		<description>A Javascript framework for building brilliant applications</description>
		<link>http://lhorie.github.io/mithril-blog/</link>
		<item>
			<title>Thoughts on performance</title>
			<link>http://lhorie.github.io/mithril-blog/thoughts-on-performance.html</link>
			<description><![CDATA[
<h2 id="thoughts-on-performance">Thoughts on performance</h2>
<p>These past few weeks, there&#39;s been a lot of activity in the Mithril <a href="https://groups.google.com/forum/#!forum/mithriljs">mailing list</a> and in the <a href="https://github.com/lhorie/mithril.js/issues">issue tracker</a> surrounding performance. It kinda started with <a href="https://groups.google.com/d/msg/mithriljs/l8CoZuqfH20/zrzozkh0XJkJ">this link</a>, a benchmark of various virtual DOM operations, in which Mithril was doing poorly compared to other virtual dom libraries.</p>
<p>This naturally surprised a lot of the community since Mithril had been shown to perform well on <a href="http://matt-esch.github.io/mercury-perf/">an earlier TodoMVC benchmark</a> (lower is better). As it turns out, <a href="https://github.com/localvoid/vdom-benchmark/issues/3">according to the author of the vdom benchmark, the metrics he was using are bad</a>, but nevertheless, members of the Mithril community started tinkering with Mithril&#39;s codebase and we now have a whole bunch of performance improvements in various stages of progress (some landed, some still being tuned), and the end result is that thanks to the efforts of G00fy-, Alex Galays and others, the next release of Mithril will fix weaknesses that made it choke on that benchmark, and we&#39;ll have a faster framework. Big shout out to everyone who is contributing!</p>
<p>But anyways, all of the talk about performance made think a little bit about performance in general, and it made me remember my foolish younger self, who would naively try to optimize code that really didn&#39;t need it. Hopefully you know better, but in any case, read on.</p>
<hr>
<h3 id="when-does-performance-matter">When does performance matter</h3>
<p>Obviously performance improvements in a framework are always welcome.</p>
<p>One might be tempted to think that optimizing a framework falls under the category of premature optimization, and that Donald Knuth&#39;s &quot;Premature optimization is the root of all evil&quot; quote is wrong. After all, all the work that goes into optimizing a framework happens before even a single line of your code runs, right?</p>
<p>But the reality is that a lot of the time, performance only starts mattering late in the game. Prototype.js used to be a major Javascript framework, but one of the defining moments for jQuery was release <a href="http://blog.jquery.com/2007/07/01/jquery-113-800-faster-still-20kb/">1.1.3</a>, which introduced a 800% (!) performance improvement over its previous version, effectively bringing the performance topic to the center of the stage for selector engines.</p>
<p>But by then, there were several players in the arena (Prototype, jQuery, MooTools, Dojo, to name a few), and the semantics of CSS selectors were well established.</p>
<p>One could argue that a similar thing happened with browsers themselves, when Chrome came into the picture with its V8 engine, basically forcing all the other browsers to up their performance games. By that time, the semantics of the Javascript language were also standardized.</p>
<p>What these examples illustrate is that performance optimization happens <em>late</em>, when the race of who has better features starts to stagnate.</p>
<hr>
<h3 id="performance-isn-t-a-vaccuum">Performance isn&#39;t a vaccuum</h3>
<p>In corporate projects, there&#39;s a similar trend of lateness: requirements change, deadlines loom, and performance optimization efforts are things that you are forced to do in the rush to get ready to ship.</p>
<p>It&#39;s often possible to get around a performance problem by changing your approach altogether. An example of this can be found in the <a href="http://lhorie.github.io/mithril/optimizing-performance.html">Mithril docs</a>: if your user does not need to be innundated with data in a grid, then taking steps to decrease cognitive load (e.g. paginating, filtering, etc) will also make the performance problem go away. Interestingly, when we have the foresight to mitigate cognitive load of a huge grid, we call it good usability design. When we don&#39;t have this foresight, then it&#39;s a performance problem. And it happens late because the lack of foresight leads to building something naively, and the problem only becomes apparent after dumping a bunch of data through the system.</p>
<p>We can say that implementing pagination and filtering is optimizing early, but remember that the problem only became apparent in hindsight. Religiously applying this optimization to every new grid can add another problem: complexity where it&#39;s not needed.</p>
<p>At my previous job, we had a peculiar case of this: one mission critical view was a fully dynamic grid that could be filtered in every conceivable way, so that people could filter not only rows but also columns. It was an extremely flexible interface for sure, but it was also nearly impossible to maintain. The solution? It turned out that using highly-specialized Trello-style views allowed for effective slicing and organizing of data for important use cases.</p>
<p>It&#39;s interesting to note that it takes some lateral thinking to go from a performance problem to a usability problem, and similarly to go from a complexity problem to a usability one.</p>
<p>Sometimes you can feed parameters back from your performance problem into your solution - iterating through usability improvements, for example. Sometimes the spec is too strict and you don&#39;t get too much wiggle room. But the key is that by the time an effort to optimize performance starts, you should have very concrete requirements and concrete goals.</p>
<p>When we try to naively tackle performance early - think perf&#39;ing if statements vs switch statements in some random place in the codebase - we&#39;re effectively doing the same as the fully dynamic grids from my previous example: It adds complexity but it doesn&#39;t necessarily improve anything. You need to have a bigger picture to macroscopically measure the impact of a change. If there&#39;s no competition to beat, if the user can&#39;t notice the speed boost, performance optimization can be a waste of time and a creator of code debt.</p>

			]]></description>
		</item>
		<item>
			<title>Drag-n-drop file uploads</title>
			<link>http://lhorie.github.io/mithril-blog/drag-n-drop-file-uploads.html</link>
			<description><![CDATA[
<h2 id="drag-n-drop-file-uploads-with-mithril">Drag n Drop file uploads with Mithril</h2>
<p>The other day, a co-worker was asking me for some help porting an HTML5 drag-n-drop file upload directive from Angular to Mithril.</p>
<p>At a glance it may seem like a pretty difficult task for a backend guy who just started learning Mithril. As it turns out, there&#39;s a lot domain-specific knowledge required, but the Mithril aspect is not particularly daunting.</p>
<p>So, let&#39;s see how this would work. First, let&#39;s get the plain vanilla drag-n-drop to work outside of Mithril.</p>
<p>The drag-n-drop API requires some amount of setup to get going. On the UI side, we want to visually indicate to the user that they have dragged something over a droppable area (and likewise, reset the visuals if the user drops or drags away from the droppable area). In addition we want to run <em>something</em> once a file is dropped.</p>
<p>So for starters, we need to define events to handle all of these cases.</p>
<pre><code class="lang-javascript">var element = document.body //let&#39;s just use body for now

element.addEventListener(&quot;dragover&quot;, activate)
element.addEventListener(&quot;dragleave&quot;, deactivate)
element.addEventListener(&quot;dragend&quot;, deactivate)
element.addEventListener(&quot;drop&quot;, deactivate)
element.addEventListener(&quot;drop&quot;, update)
window.addEventListener(&quot;blur&quot;, deactivate)

function activate(e) {
    e.preventDefault()
}
function deactivate() {}
function update(e) {
    e.preventDefault()
}
</code></pre>
<p>The boilerplate above takes care of setting up all the relevant event handlers, but for now each event just calls empty functions. The <code>activate</code> and <code>update</code> functions need to call <code>preventDefault</code> in order for drag and drop to work correctly.</p>
<p>Let&#39;s make things a bit more functional. Since the files are only available once the <code>update</code> event is triggered, we need to expose the data with another event handler:</p>
<pre><code class="lang-javascript">function dragdrop(element, options) {
    options = options || {}

    element.addEventListener(&quot;dragover&quot;, activate)
    element.addEventListener(&quot;dragleave&quot;, deactivate)
    element.addEventListener(&quot;dragend&quot;, deactivate)
    element.addEventListener(&quot;drop&quot;, deactivate)
    element.addEventListener(&quot;drop&quot;, update)

    function activate(e) {
        e.preventDefault()
    }
    function deactivate() {}
    function update(e) {
        e.preventDefault()
        if (typeof options.onchange == &quot;function&quot;) {
            options.onchange((e.dataTransfer || e.target).files)
        }
    }
}
</code></pre>
<p>Now we can start using our <code>dragdrop</code> function instead of needing to type all that boilerplate all the time:</p>
<pre><code class="lang-javascript">dragdrop(document.body, {
    onchange: function(files) {
        console.log(files)
    }
})
</code></pre>
<p>Next, we need to create a function to upload files. In an MVC setting, this kind of concern belongs in the model layer. So let&#39;s create a model method to deal with file uploads.</p>
<pre><code class="lang-javascript">var Uploader = {}

Uploader.upload = function() {
    //todo: upload files
}
</code></pre>
<p>Let&#39;s suppose that we want to POST the files to the URL <code>/api/files</code>. The problem is that you can&#39;t just serialize a file into a regular HTTP request. Instead, we need to use the HTML5 <a href="https://developer.mozilla.org/en-US/docs/Web/API/FormData">FormData class</a>, which creates an object that can be sent via XMLHttpRequest, but encodes the request as <code>multipart/form-data</code>. In order to ajax a FormData instance instead of serializing data as JSON, we need to override <code>m.request</code>&#39;s default <code>serialize</code> option:</p>
<pre><code class="lang-javascript">Uploader.upload = function(files) {
    var formData = new FormData
    for (var i = 0; i &lt; files.length; i++) {
        formData.append(&quot;file&quot; + i, files[i])
    }

    return m.request({
        method: &quot;POST&quot;,
        url: &quot;/api/files&quot;,
        data: formData,
        //simply pass the FormData object intact to the underlying XMLHttpRequest, instead of JSON.stringify&#39;ing it
        serialize: function(value) {return value}
    })
}
</code></pre>
<p>Now we are able to take our <code>dragdrop</code> function and use it with our model entity:</p>
<pre><code>dragdrop(document.body, {onchange: Uploader.upload})
</code></pre><p>You can verify that the code is working by dropping a file onto the page, and inspecting the request object.</p>
<p><img src="images/upload-request.png" alt="File upload request body"></p>
<hr>
<h3 id="integrating-to-mithril">Integrating to Mithril</h3>
<p>In Mithril, templates are made out of virtual DOM elements (i.e. javascript objects that represent DOM elements).</p>
<p>The DOM elements themselves are only accessible from <code>config</code> functions in views. Let&#39;s hook our <code>dragdrop</code> function into a config:</p>
<pre><code class="lang-javascript">//an uploader module
var uploader = {}

uploader.controller = function(options) {
    return options
}

uploader.view = function(ctrl) {
    return m(&quot;.uploader&quot;, {
        config: function(element, isInitialized) {
            if (!isInitialized) {
                dragdrop(element, {onchange: ctrl.onchange})
            }
        }
    })
}
</code></pre>
<p>All we&#39;re doing here is calling the <code>dragdrop</code> function as we did before, but passing another event handler to it. This event handler will be defined by a parent component.</p>
<p>Now this module can be used by another components:</p>
<pre><code class="lang-javascript">var demo = {}

demo.controller = function() {
    return {
        title: m.prop(&quot;Upload something&quot;),
        uploader: submodule(uploader, {
            onchange: Uploader.upload
        })
    }
}

demo.view = function(ctrl) {
    return [
        m(&quot;h1&quot;, ctrl.title()),
        ctrl.uploader(),
        m(&quot;p&quot;, &quot;more stuff&quot;)
    ]
}

m.module(document.body, demo)
</code></pre>
<p>Notice we&#39;re using the <a href="http://lhorie.github.io/mithril-blog/module-partial-application.html"><code>submodule</code> helper from this article</a> to cut down on the amount of noise.</p>
<p><a href="http://jsfiddle.net/2psha3v6/3/">You can see a running example of this code here</a></p>
<hr>
<h3 id="conclusion">Conclusion</h3>
<p>As you play with this code, you&#39;ll likely want to add styling for when the user drags a file over the drop area, as well as remove the style when the user drag away from the drop area. This can be accomplished by adding and removing CSS classes in the <code>activate</code> and <code>deactivate</code> functions. I&#39;m leaving this as an exercise to the reader.</p>
<p>In this article we saw how we can work our way from a simple library to full Mithril integration. Understanding this workflow is a key in learning how to integrate third-party libraries to Mithril, how to write reusable components and how to organize the flow of data across different components.</p>
<p>And hopefully you&#39;ve also learned a thing or two about the nuts and bolts of the cool and flashy HTML 5 drag-n-drop API.</p>

			]]></description>
		</item>
		<item>
			<title>Organizing components</title>
			<link>http://lhorie.github.io/mithril-blog/organizing-components.html</link>
			<description><![CDATA[
<h2 id="organizing-components">Organizing components</h2>
<p>One requirement that I commonly run into is the ability to filter a list of things. Not just filtering an array, but filtering in the sense of a user specifying some criteria, and a list of things on screen updating to become more relevant as a result. Think Google&#39;s search result page.</p>
<p>In this article we&#39;ll look at one way of implementing a client-side filter.</p>
<p>First we need to decide roughly where we can separate concerns: usually the most logical way of breaking up the view is to have one template for the list of things and another for the filters, plus a top level component to glue everything together. But once we&#39;ve decided that, there are many different ways in which we could actually implement our components, and some ways lend themselves to be more tightly coupled than others. Ideally, we&#39;d like the sub-components to be as agnostic about the rest of the world as possible. Conversely, we want the top level component to specify what sub-components exist and how they interact with each other.</p>
<p>One may argue that then, the top component is tightly coupled. That&#39;s true and in fact it&#39;s a necessity: there&#39;s simply no way to have decoupled components talking to each other without some mechanism that ties them together into a context. This is the purpose of the top component.</p>
<p>Anyways, let&#39;s start by creating skeletons for our components.</p>
<pre><code class="lang-javascript">//top level component
var things = {}

things.controller = function() {}
things.view = function(ctrl) {
    return m(&quot;.row&quot;, [
        m(&quot;.col-md-2&quot;, [
            filter.view(ctrl.filter)
        ]),
        m(&quot;.col-md-10&quot;, [
            list.view(ctrl.list)
        ])
    ])
}

//filter
var filter = {}
filter.view = function() {}

//list
var list = {}
list.view = function() {}
</code></pre>
<p>Notice that the structural grid markup is in the top level component (I&#39;m using Bootstrap CSS classes in this case). As you get into refactoring more repetitive templates, you might be tempted to start putting this type of code in the subtemplates, but from a maintenance perspective, it&#39;s a lot easier to reason about the structure of the grid when the entire structure is in one place, rather than scattered around different functions. In addition, having this markup at the top level template means that each of our subtemplates is clean (and therefore easier to reuse)</p>
<p>Also, note that we&#39;re using <code>ctrl.filter</code> and <code>ctrl.list</code> in the view even though we haven&#39;t defined them yet. We&#39;ll get to these later on.</p>
<hr>
<h3 id="the-list">The list</h3>
<p>The list will need to be populated with data. So let&#39;s create a model to handle that:</p>
<pre><code class="lang-javascript">var Thing = {}
Thing.list = function() {
    return m.request({method: &quot;GET&quot;, url: &quot;/api/things&quot;})
}
</code></pre>
<p>Next, we use a controller to expose this data to a view.</p>
<pre><code class="lang-javascript">list.controller = function(options) {
    this.items = Thing.list()
    this.visible = options.visible
}
</code></pre><p>The <code>Thing.list</code> method ajaxes some JSON data and returns a promise that asynchronously resolves to the response data. So in the view, <code>ctrl.items</code> will hold the data that came back from the web service.</p>
<p>The <code>visible</code> property will be used to determine which of the items are visible on screen. This function will be passed to <code>Array.prototype.filter</code>, so it&#39;ll take an item as the argument and expect a boolean as the return value.</p>
<p>Next, let&#39;s create the template to display our list:</p>
<pre><code class="lang-javascript">list.view = function(ctrl) {
    return m(&quot;table&quot;, [
        ctrl.items().filter(ctrl.visible).map(function(item) {
            return m(&quot;tr&quot;, [
                m(&quot;td&quot;, item.id),
                m(&quot;td&quot;, item.name)
            ])
        })
    ])
}
</code></pre>
<p>The code above creates a table and iterates over the array in <code>items</code>. It filters out items based on the <code>ctrl.visible</code> function and displays table rows for the items that are visible.</p>
<hr>
<h3 id="the-filter">The filter</h3>
<p>Let&#39;s create a search input.</p>
<pre><code class="lang-javascript">filter.controller = function(options) {
    this.searchTerm = m.prop(&quot;&quot;)
}
</code></pre>
<p>Here we created a controller that has a member called <code>searchTerm</code>. We&#39;ll be using this getter-setter to store the value of the search input.</p>
<p>Next, let&#39;s create the template for the filter.</p>
<pre><code class="lang-javascript">filter.view = function(ctrl) {
    return m(&quot;input&quot;, {oninput: m.withAttr(&quot;value&quot;, ctrl.searchTerm)})
}
</code></pre>
<p>The code above simply defines a text input that populates <code>ctrl.searchTerm</code> as the user types. By using <code>m.withAttr</code>, we extract the <code>value</code> attribute of the input and pass it as the argument to <code>ctrl.searchTerm</code> when an <code>oninput</code> event is triggered.</p>
<hr>
<h3 id="putting-things-together">Putting things together</h3>
<p>Let&#39;s go back to our top level controller. Here we need to instantiate each of our sub-module controllers. </p>
<pre><code class="lang-javascript">things.controller = function() {
    var ctrl = this

    ctrl.list = new list.controller({
        visible: function(item) {
            return item.name.indexOf(ctrl.filter.searchTerm()) &gt; -1
        }
    })

    ctrl.filter = new filter.controller()
}
</code></pre>
<p>As you may recall, we needed to define <code>ctrl.filter</code> and <code>ctrl.list</code>, because we were using them in the top level template as the controllers for the sub-views.</p>
<p>Another thing to remember was that the <code>list</code> controller can receive a <code>visible</code> argument. This option determines how the items in the list are filtered.</p>
<p>The implementation of <code>visible</code> is straightforward: if the item name contains the search term, then the item is visible.</p>
<p>We can now run our code:</p>
<pre><code class="lang-javascript">//model
var Thing = {}
Thing.list = function() {
    return m.request({method: &quot;GET&quot;, url: &quot;/api/things&quot;})
}

//top level component
var things = {}

things.controller = function() {
    var ctrl = this

    ctrl.list = new list.controller({
        visible: function(item) {
            return item.name.indexOf(ctrl.filter.searchTerm()) &gt; -1
        }
    })

    ctrl.filter = new filter.controller()
}
things.view = function(ctrl) {
    return m(&quot;.row&quot;, [
        m(&quot;.col-md-2&quot;, [
            filter.view(ctrl.filter)
        ]),
        m(&quot;.col-md-10&quot;, [
            list.view(ctrl.list)
        ])
    ])
}

//filter
var filter = {}
filter.controller = function(options) {
    this.searchTerm = m.prop(&quot;&quot;)
}
filter.view = function(ctrl) {
    return m(&quot;input&quot;, {oninput: m.withAttr(&quot;value&quot;, ctrl.searchTerm)})
}

//list
var list = {}
list.controller = function(options) {
    this.items = Thing.list()
    this.visible = options.visible
}
list.view = function(ctrl) {
    return m(&quot;table&quot;, [
        ctrl.items().filter(ctrl.visible).map(function(item) {
            return m(&quot;tr&quot;, [
                m(&quot;td&quot;, item.id),
                m(&quot;td&quot;, item.name)
            ])
        })
    ])
}

//run
m.module(document.body, things)
</code></pre>
<hr>
<h3 id="-pshaw-i-could-write-that-in-less-lines-of-code-">&quot;Pshaw, I could write that in less lines of code!&quot;</h3>
<p>Our example is admittedly pretty simple, and it&#39;s very much possible to merge everything into the <code>things</code> module and end up with less code than we did. Likewise, it&#39;s also possible to add more code to make modules more pure and abstract.</p>
<p>The point of this article, though, is primarily to show one way of breaking larger modules into smaller ones. Organizing code in the way we did allows us to reuse the sub-components: the <code>filter</code> module is only concerned with what the user types in the search input, and the <code>list</code> module can be filtered in any way we desire. The <code>things</code> module is what glues the sub-components together and specifies how they interact with each other in the context of <code>things</code>.</p>
<p>If you&#39;ve been passing instances of parent controllers to child components, now you know how to re-organize code in a less tightly coupled way.</p>

			]]></description>
		</item>
		<item>
			<title>Module partial application</title>
			<link>http://lhorie.github.io/mithril-blog/module-partial-application.html</link>
			<description><![CDATA[
<h2 id="module-partial-application">Module partial application</h2>
<p>Today&#39;s article will be about a short and sweet idiom.</p>
<p>In Mithril modules, controllers are class constructors, which means that in order to manually use them, you need to instantiate them.</p>
<p>This is required in order to provide contextualization to modules (i.e. the ability to say when a module gets created and when it gets destroyed), but having to remember to pass controller instances to views can get a little cumbersome once you start breaking down a big app into a lot of modules:</p>
<pre><code class="lang-javascript">var root = {}

root.controller = function() {
    this.search = new search.controller()
    this.filters = new filters.controller()
    this.list = new list.controller()
}

root.view = function(ctrl) {
    search.view(ctrl.search)
    filters.view(ctrl.filters)
    list.view(ctrl.list)
}
</code></pre>
<p>A simple way to optimize this is to use <em>partial application</em> to pre-bind a controller instance:</p>
<pre><code class="lang-javascript">var submodule = function(module, args) {
    return module.view.bind(this, new module.controller(args))
}
</code></pre>
<p>This returns a view function with the controller already passed into it. We can then create references to that in the root controller instead:</p>
<pre><code class="lang-javascript">root.controller = function() {
    this.search = submodule(search)
    this.filters = submodule(filters)
    this.list = submodule(list)
}

root.view = function(ctrl) {
    ctrl.search(),
    ctrl.filters(),
    ctrl.list()
}
</code></pre>
<p>Just remember that controllers should never be instantiated from views (<a href="http://lhorie.github.io/mithril/components.html">as per the documentation</a>), which means you should never call <code>submodule</code> from a view.</p>
<hr>
<h3 id="shouldn-t-we-be-using-view-models-">Shouldn&#39;t we be using view-models?</h3>
<p>If you read that documentation page through to the end, you&#39;ll see I talk about moving logic out of controllers into view models.</p>
<p>But that doesn&#39;t mean controllers should just be abolished altogether. One case where nesting components is necessary is when dealing with dynamic or extensible component placement, i.e. when you have a container module where different modules might be dropped in. The classical example is a dashboard where users can customize what widgets show up.</p>
<p>The benefit of using the trick above is that you only need one variable to hold your module instance instead of two:</p>
<pre><code class="lang-javascript">//without using the partial application trick
var dashboard = {}

dashboard.controller = function(innerModule) {
    this.innerController = new innerModule.controller()
    this.innerView = innerModudle.view
}

//using it
var dashboard = {}

dashboard.controller = function(innerModule) {
    this.innerView = submodule(innerModule)
}
</code></pre><p>I hope you&#39;ll find this trick useful.</p>

			]]></description>
		</item>
		<item>
			<title>Common mistakes</title>
			<link>http://lhorie.github.io/mithril-blog/common-mistakes.html</link>
			<description><![CDATA[
<h2 id="common-mistakes">Common mistakes</h2>
<p>Any time we start learning something new, we are bound to stumble and make mistakes along the way. In this article, we&#39;ll look at some common issues that I&#39;ve seen people run into when they were getting into Mithril.</p>
<hr>
<h3 id="1-using-jquery">1. Using jQuery</h3>
<p>It&#39;s surprisingly tempting to use jQuery to manipulate the DOM from a controller or even a view-model, especially for those without experience in MVC frameworks. I&#39;ve <a href="http://lhorie.github.io/mithril/comparison.html">talked about jQuery&#39;s scalability problem before</a>. The gist is that jQuery DOM manipulation implicitly puts UI state data in the DOM itself, and as applications grow larger, it becomes harder and harder to reason about that state, and the tendency to build more functionality on top of it causes the application to become brittle and hard to modify.</p>
<p>Another problem with mixing jQuery is that it creates a tight coupling between the data and the presentation layer, making both harder to test in isolation.</p>
<p>The alternative to using jQuery is to apply the same MVC concepts that you would see in server-side frameworks: have data live in the model layer, and explicitly derive the state of the view from the data. I&#39;ve <a href="what-is-a-view-model.html">talked about using view-models</a> for <a href="mapping-view-models.html">separating ORM classes from UI state</a> within the model layer. Moving away from jQuery is simply an exercise in applying the same workflow as you would in your traditional server-side MVC framework of choice, and being mindful of the existence and the nature of UI state.</p>
<p>With all of this said, you <em>can</em> use jQuery to augment the behavior of an element via the <a href="http://lhorie.github.io/mithril/mithril.html#accessing-the-real-dom">config attribute</a>. Just avoid doing it in controllers and view-models.</p>
<hr>
<h3 id="2-misunderstanding-dynamic-scoping">2. Misunderstanding dynamic scoping</h3>
<p>Let&#39;s face it, the <code>this</code> keyword is confusing. Many seasoned developers still struggle with it, especially when you start adding nested anonymous functions, partial application, and functions-as-arguments into the picture. It&#39;s a good idea to consider using idioms without language-specific caveats to help ease new developers into the codebase.</p>
<p>One common way to make <code>this</code> more junion-friendly is to use the <code>var self = this</code> idiom. Be aware though that <code>self</code> is just as non-descriptive as a variable name as <code>this</code> and it can yield somewhat repetitive code.</p>
<p>The best thing to do to avoid <code>this</code> confusion as a team grows is to avoid using it altogether. Here&#39;s an example that uses <code>this</code>:</p>
<pre><code class="lang-javascript">var home = {}
home.vm = {
    init: function() {
        this.name = &quot;foo&quot;
    }
}
</code></pre>
<p>Here&#39;s an alternative way of writing the snippet above using the easier-to-understand lexical scoping:</p>
<pre><code class="lang-javascript">var home = {}
home.vm = {}
home.vm.init = function() {
    home.vm.name = &quot;foo&quot;
}
</code></pre>
<p>The structure of the data is now much more obvious, albeit at the expense of adding some repetition in the form of explicit <code>home.vm</code> references everywhere.</p>
<p>Here&#39;s a cleverer way of writing it that reduces repetition:</p>
<pre><code class="lang-javascript">var home = {}
new function(vm) {
    vm.init = function() {
        vm.name = &quot;foo&quot;
    }
}(home.vm = {})
</code></pre>
<hr>
<h3 id="3-backwards-controllers">3. Backwards controllers</h3>
<p>Controllers are a <em>scoping</em> mechanism. They are responsible to defining what is accessible by the view: what data can be iterated over, how is that data sliced from the server-side data set, what operations can be performed on this data. People are often confused about the role of controllers because its primary responsibity (scoping) is actually a form of state, but one that doesn&#39;t really fit in the model layer. Misunderstanding the role of controllers often lead people to put all non-ORM state in the controller itself, for the sake of &quot;consistency&quot; (a pattern colloquially known as &quot;fat controllers&quot;).</p>
<p>While fat controllers aren&#39;t necessarily bad per se, they can lead to some problems if you&#39;re not careful with their lifecycles. As a rule of thumb, controller classes should never be instantiated from a view.</p>
<p>It&#39;s technically possible to have controllers that get reconsctructed by views on every redraw (using anonymous stateless objects is an example of it), but the extra abstraction layer provided by OOP classes lulls developers into the common OOP pattern of encapsulating state within the class itself.</p>
<p>Since controllers in Mithril modules are nothing more than Javascript constructor functions, they can be as thin or as fat as a developer wants. The problem begins when a developer starts holding state in fat controllers for convenience instead of putting that state in view-models, and then proceeds to instantiate the constructor function from a view. Typically in Mithril, controllers are only meant to be initialized once in their lifecycle, but view functions run every time an event is triggered. When a controller is initialized by the view, it resets its internal state, which is almost never what the developer wants. So just don&#39;t do it.</p>
<p>Another related issue that comes up often is incidental complexity arising from adding a controller for its own sake. This happens most commonly when someone has a list of things and they want to wrap each item in its own module. Remember that controllers are a scoping mechanism: items in a list are already scoped and ready to be consumed by views, so adding another layer of controllers adds unnecessary boilerplate.</p>
<p>If you&#39;re running into issues with managing the lifecycle of sub-components that represent items in a list, then you probably should consider <a href="mapping-view-models.html">view model maps</a> instead. You can skip implementing the sub-module controller until your sub-module actually does need to be scoped on its own for another page where the sub-module exists but the list module does not.</p>
<hr>
<h3 id="4-premature-optimization">4. Premature optimization</h3>
<p>A relatively common mistake is creating gigantic DOMs, and then spending inordinate amounts of time trying to one-up the framework&#39;s rendering algorithm. The performance of all algorithms degrade as the size of data increases, and even the fastest algorithms can only run as fast as the hardware they run on. Rendering tens of thousands of elements on a page will be slow with any framework.</p>
<p>Rather than spending time fighting against the global nature of Mithril&#39;s virtual dom diff algorithm, it&#39;s usually more productive to think of ways to reduce the size of the DOM. Large tables are a classic example: their rendering performance degrade linearly as more rows and columns are displayed, but no human being can reasonably wade through thousands of rows filled with tabular data. Rather than spending time fighting the rendering algorithm (which is not even the culprit of the slowness), it&#39;s a lot more productive to implement pagination and search / filtering: doing so improves performance (both on redraws AND on page load), AND it improves usability as well.</p>
<hr>
<h3 id="conclusion">Conclusion</h3>
<p>Many mistakes that people make when starting out with Mithril are often related to years of old habits, or by lack of experience with javascript (or even programming in general). While there will inevitably those who misunderstand one or another small aspect of Mithril itself, I think the minimalist nature of the framework and the amount of documentation and public forums available are sufficient enough that the only problems left to pay attention to are those related to the general programming discipline. I hope this article helps you hone high-level application development skills, regardless of whether you end up using Mithril ten years from now or not.</p>

			]]></description>
		</item>
		<item>
			<title>Mapping view-models</title>
			<link>http://lhorie.github.io/mithril-blog/mapping-view-models.html</link>
			<description><![CDATA[
<h2 id="mapping-view-models">Mapping view models</h2>
<p>Fat javascript-driven applications usually have two types of data: domain data and application data.</p>
<p>Domain data is what users care about: user records, articles, projects, whatever. By definition, domain data is what makes an application useful; most user actions in an application revolve around reading and writing domain data.</p>
<p>Application data, on the other hand, is data about the state of the application itself: is this modal popup open, what filter is currently applied to this grid, should a loading icon be showing up right now, what was the original value of this input if I hit the cancel button to reset it?</p>
<p>Newer frameworks have started adopting the idea of view-models to deal with application state. <a href="what-is-a-view-model.html">I talked about it previously here</a>. The summary is that UI state is almost never a concern for the model entities that deal with domain data, and we often need to keep them separated somehow.</p>
<p>One challenge that people face when building complex apps is that it&#39;s inherently difficult to separate application state concerns from domain data concerns when working with lists of things. Lists can be sorted, filtered, sliced and spliced, and keeping a second list in sync is not trivial.</p>
<p>Today we&#39;re going to look at a pattern that I recently started using at work to help fix this problem.</p>
<p>Let&#39;s imagine that we&#39;re working with some user records:</p>
<pre><code class="lang-javascript">var users = [
    {id: 1, name: &quot;John&quot;, email: &quot;john@example.com&quot;},
    {id: 2, name: &quot;Mary&quot;, email: &quot;mary@example.com&quot;},
    {id: 3, name: &quot;Bob&quot;, email: &quot;bob@example.com&quot;}
]
</code></pre>
<p>And let&#39;s say we have an interface that displays all user names and there&#39;s a &quot;more&quot; button beside each user that displays the rest of the user information.</p>
<pre><code class="lang-javascript">var app = {}
app.controller = function() {
    this.users = users
}
app.view = function(ctrl) {
    return m(&quot;ul&quot;, [
        ctrl.users.map(function(user) {
            return m(&quot;li&quot;, [
                m(&quot;a[href=&#39;javascript:;&#39;]&quot;, {
                    onclick: function() {user.showEmail = !user.showEmail}
                }, user.name),
                user.showEmail ? m(&quot;div&quot;, user.email) : &quot;&quot;
            ])
        })
    ])
}
m.module(document.body, app)
</code></pre>
<p>In the snippet above, we loop through the list of users and display a list, which contains a name in a link. Clicking the link toggles the <code>div</code> with the email.</p>
<p>It&#39;s tempting to just put the show/hide flag in the user record itself as I did above, but imagine that a month down the road, your boss comes back and asks you to change the <code>div</code> into a form that lets users edit a user record. Now all of a sudden, there&#39;s a whole lot of additional application state that you weren&#39;t expecting: you need to put the temporary input value somewhere in case a user cancels out, you need a flag to indicate whether a loading icon should appear while the item is saving, you need to display an error if something goes wrong, etc. So now our user records store all sorts of not-really-user-related properties, and this was just one &quot;small&quot; change in the app! It&#39;s scary to realize how one little harmless hack can quickly snowball into a huge mess of mixed concerns.</p>
<p>Some might be wondering why we aren&#39;t just using the DOM to store this application state, as one would do with jQuery. The problem with having UI state live implicitly in the DOM is that you don&#39;t have a single source of canonical data, which makes it difficult to understand where a change begins and where it ends as it ripples through the system. Imagine the same scenario as above, in a jQuery codebase. You could start storing all the UI state I described directly in the DOM, but what if the data comes from the server, and your boss asks it to be filterable via a search input? How complicated does your code need to be now in order to re-render the rest of the grid while keeping the state of an active form intact? Ultimately what ends up happening is an exponential growth of custom code to handle every possible corner case that arises from the growing number of interactions between different use cases, all of which needs to be revised yet again when the next feature gets introduced. This simply doesn&#39;t scale.</p>
<p>Let&#39;s take a step back and think about the data structures.</p>
<pre><code class="lang-javascript">var users = [
    {id: 1, name: &quot;John&quot;, email: &quot;john@example.com&quot;},
    {id: 2, name: &quot;Mary&quot;, email: &quot;mary@example.com&quot;},
    {id: 3, name: &quot;Bob&quot;, email: &quot;bob@example.com&quot;}
]
</code></pre>
<p>As we saw earlier, our data is a relatively simple data structure, but let&#39;s break this down further. There&#39;s a list, and inside of the list, there&#39;s a bunch of objects. Each object has a bunch of properties, one of which (<code>id</code>) is a <em>unique identifier</em> value.</p>
<p>We want to map a varying number of UI-related properties to each record in this list, without polluting the records themselves.</p>
<p>And as it turns out, javascript has a data structure that is perfect for this task: objects. With it, we can build a <em>lazy map</em>, that is, a map that populates each key-value pair with a defined child structure on demand.</p>
<pre><code class="lang-javascript">var viewModelMap = function(signature) {
    var map = {}
    return function(key) {
        if (!map[key]) {
            map[key] = {}
            for (var prop in signature) map[key][prop] = m.prop(signature[prop]())
        }
        return map[key]
    }
}
</code></pre>
<p>The helper above is a factory that takes as input a <code>signature</code> object with getter-setter properties attached to it, and returns a function. The returned function takes as an input a key, and returns a clone of the <code>signature</code> object, initialized with the values from the signature. Here&#39;s an example of how to use it:</p>
<pre><code class="lang-javascript">var formVMs = viewModelMap({
    isEditing: m.prop(false),
    tempValue: m.prop(&quot;&quot;),
    error: m.prop(&quot;&quot;)
})

var vm1 = formVMs(1)
vm1.isEditing() // false
vm1.isEditing(true) // true

var vm2 = formVMs(2)
v1 === v2 // false

var vm1again = formVMs(1)
vm1 === vm1again // true
vm1again.isEditing() //true
</code></pre>
<p>Above, <code>formVMs</code> returns clones of the signature object corresponding to the number that we pass in. Calling it more than once for a single key returns the same object, with its state preserved.</p>
<p>We can now plug this back into our example from earlier:</p>
<pre><code class="lang-javascript">var app = {}
app.controller = function() {
    this.users = users

    this.usersVM = viewModelMap({
        isEditing: m.prop(false),
        tempValue: m.prop(&quot;&quot;),
        error: m.prop(&quot;&quot;)
    })
}
app.view = function(ctrl) {
    return m(&quot;ul&quot;, [
        ctrl.users.map(function(user) {
            var vm = ctrl.usersVM(user.id)
            return m(&quot;li&quot;, [
                m(&quot;a[href=&#39;javascript:;&#39;]&quot;, {
                    onclick: function() {vm.isEditing(!vm.isEditing())} //toggle div
                }, user.name),
                vm.isEditing() ? m(&quot;div&quot;, user.email) : &quot;&quot;
            ])
        })
    ])
}
m.module(document.body, app)
</code></pre>
<p>Notice that we copied the view model map to our controller, and that we replaced <code>user.showEmail</code> with <code>vm.isEditing</code>. Each view model maps to a user id.</p>
<p>Now the user records are kept clean of UI state, and the view model is easily extensible (just add more properties to the signature).</p>
<hr>
<h3 id="conclusion">Conclusion</h3>
<p>Linus Torvalds once said that mediocre programmers think in terms of code, but great programmers think in terms of data structures and how they interact with one another. In this article, we applied his lesson to our problem, using common techniques that should be familiar to most programmers: using functions as factories, using objects as maps, lazy initialization, etc.</p>
<p>Thinking in terms of data structures is a good piece of advice. For a lot of programmers, it&#39;s easy to eagerly jump into coding as soon as a problem presents itself, but taking that extra time upfront to design a good structure for our data can pay off enormously. Designing our code around the structure of data means that keeping data clean and organized is a top priority. This makes it easier to inspect it during maintenance, and paradoxically, tends to produce more discoverable code than when we spend all our energy crafting clever code paths (at least in my own experience).</p>

			]]></description>
		</item>
		<item>
			<title>Decreasing cognitive load</title>
			<link>http://lhorie.github.io/mithril-blog/decreasing-cognitive-load.html</link>
			<description><![CDATA[
<h2 id="decreasing-cognitive-load">Decreasing cognitive load</h2>
<p>You might have heard of something called <strong>the paradox of choice</strong>. We might think that having many options to choose from is a good thing, but given many similar choices, what actually happens often is that we end up spending so much time trying to analyze them, that we end up wasting more time than if we were to just randomly pick one. This phenomenon is also known as <em>choice paralysis</em>.</p>
<p>There&#39;s a similar phenomenon, known as <strong>information overload</strong>, that is similar in the way that it overwhelms us with information about a particular topic. The problem with information overload is that while all the presented information is ostensibly <em>correct</em>, it&#39;s also mostly irrelevant for the task at hand.</p>
<p>Frameworks are often difficult to learn due to similar cognitive patterns: a newbie comes in to a documentation side and is confronted with a variety of classes and methods that are all useful in one context or another, but it&#39;s not immediately obvious how they relate to the newbie&#39;s particular problem. When <em>every</em> problem that a developer encounters requires yet another dig through the documentation in order to learn some new incantation, or to remember what its syntax was, productivity is lost.</p>
<p>So, in order to not get in people&#39;s ways, it&#39;s important that frameworks and libraries try to minimize the amount of cognitive load they put on developers.</p>
<p>One trick that jQuery used to ease people into its vast API was function overloading:</p>
<pre><code class="lang-javascript">//set the color of one element
$(&quot;#foo&quot;).css(&quot;color&quot;, &quot;red&quot;)

//get the color
$(&quot;#foo&quot;).css(&quot;color&quot;)

//set the color on many elements
$(&quot;h1&quot;).css(&quot;color&quot;, &quot;red&quot;)
</code></pre>
<p>You don&#39;t need to remember if the method is called <code>getCss</code>, or <code>readCSS</code>, and whether the counterpart is <code>setStyle</code> or <code>setCSS</code> (and did you noticed the uppercase?). There&#39;s not a different API if you&#39;re setting styles on one vs many elements. It&#39;s just <code>css</code> all the time.</p>
<p>Compare it to Prototype.js, arguably the most popular javascript framework at the time jQuery came out:</p>
<pre><code class="lang-javascript">//set the color of one element
$(&quot;foo&quot;).setStyle({color: &quot;red&quot;})

//get the color
$(&quot;foo&quot;).style.color

//set the color of many elements
$$(&quot;h1&quot;).invoke(&quot;setStyle&quot;, {color: &quot;red&quot;})
</code></pre>
<p>You can clearly see why jQuery is still loved by many, and why Prototype.js fell by the sidelines. Having APIs that are easy to remember and that adapt to similar but slightly different use cases help the framework become transparent so that the developer can then focus on their own problems rather than be fighting against framework syntax.</p>
<p>Mithril also uses this design trick to help newbies ease into its API:</p>
<pre><code class="lang-javascript">//I just want a div
m(&quot;div&quot;)

//but it has text
m(&quot;div&quot;, &quot;Hello world&quot;)

//actually, I need to toggle a class on it too
m(&quot;div&quot;, {class: isActive ? &quot;active&quot; : &quot;&quot;}, &quot;Hello world&quot;)
</code></pre>
<p>Another slightly different example is <code>m.route</code>. It has three overloads that do fairly different things: define routes, redirect, and make links routed. This may seem weird at a glance, but it&#39;s an example of being <em>answer-oriented</em>. When it comes to routing, these are three common questions: &quot;how do I define a bunch of routes?&quot;, &quot;how do I redirect to a route?&quot;, and &quot;how do I make my link go to a routed path instead of a regular URL?&quot;. Having the answer always be the same (i.e. &quot;use m.route&quot;) means less names to memorize.</p>
<p>Mithril also takes it a step further and makes it easy for developers themselves to create predictable APIs with <code>m.prop</code>. We previously saw this in the <a href="the-uniform-access-principle.html">uniform access principle article</a>.</p>
<pre><code class="lang-javascript">var name = m.prop(&quot;&quot;)

//set the value
name(&quot;John&quot;)

//get the value
console.log(name()) // &quot;John&quot;
</code></pre>
<p>In a <a href="json-all-the-things.html">follow-up article</a>, we also saw another subtle place where Mithril encourages good API design:</p>
<pre><code class="lang-javascript">var User = function(data) {
    this.firstName = m.prop(data.firstName)
    this.lastName = m.prop(data.lastName)
}

//automatically convert response objects to User instances
m.request({method: &quot;GET&quot;, url: &quot;/users&quot;, type: User})
</code></pre>
<p>While this isn&#39;t technically function overloading per se, it uses the options argument pattern to provide an extensible map of parameters, so that it&#39;s easy to set as many or as few of the input parameters as you&#39;re able to. The options argument pattern effective makes every permutation of parameters a valid overload.</p>
<p>But more importantly, it makes the argument list for every model entity predictable: You don&#39;t need to remember the order of arguments, and knowing how to create one type of entity is enough knowledge to guess how to create others.</p>
<p>Which brings us to another aspect of predictable APIs: <em>consistency</em></p>
<p>Again, jQuery is a great example of this:</p>
<pre><code class="lang-javascript">//how I set some css?
$(&quot;#foo&quot;).css(&quot;color&quot;, &quot;red&quot;)

//attributes?
$(&quot;#foo&quot;).attr(&quot;title&quot;, &quot;hello&quot;)

//data?
$(&quot;#foo&quot;).data(&quot;name&quot;, &quot;john&quot;)
</code></pre>
<p>You can look at a method and guess (most likely correctly) how the other ones work.</p>
<hr>
<h3 id="interfaces-interfaces">Interfaces, interfaces</h3>
<p>Being conscious of consistency can make a significant difference in how one organizes code.</p>
<p>From my experience, I think it takes a bit of a mental shift to go from writing single-purpose application code to writing multi-purpose libraries. Single-purpose code doesn&#39;t strictly require much thought in terms of its API because it is typically only a <em>consumer</em>: it may assemble a bunch of different things, but it&#39;s rarely (if ever) used to compose into more than one bigger system.</p>
<p>But as systems get more complex the line between single-purpose application code and multi-purpose library code starts to blur: we often start needing  reusable application-level agglomerations of code in order to avoid problems like code duplication (i.e. two or more pieces of code that do <em>almost</em> the same thing, but not quite).</p>
<p>Striving for consistency implicitly means developers need to be aware of what code is already there in order to follow convention. This is, I think, where the mental shift happens. With many frameworks, conventions are baked into the boilerplate, but then teams without a good code review workflow start writing in whatever style they prefer and end up with a wild west of code when all these pieces start to come together into bigger things two years later.</p>
<p>As it turns out, for years OOP has offered tools like <em>interfaces</em> to help us improve code consistency. Even though Javascript isn&#39;t a statically typed OOP language, we can borrow some of these ideas.</p>
<p>Here&#39;s an example of some code I use at work, to illustrate:</p>
<pre><code class="lang-javascript">var select2 = {}
select2.config = function(options) {
    var type = options.type, prop = options.binds
    return function(element, isInitialized) {
        if (!isInitialized) {
            $(element).select2({
                ajax: {
                    url: type.url,
                    data: function(term) {
                        return {ForAutoCompleter:true, Keyword: term}
                    },
                    results: function(data) {
                        return {results: data.Entries.map(function(item) {
                            var instance = new type(item)
                            return {id: type.id(instance), text: type.label(instance), data: instance}
                        })}
                    }
                }
            })
            .on(&quot;change&quot;, function(e) {
                m.startComputation()
                prop(e.added ? e.added.data : null)
                m.endComputation()
            })

            var item = prop()
            if (item) {
                $(element).select2(&quot;data&quot;, {id: type.id(item), text: type.label(item)})
            }
        }
    }
}
</code></pre>
<p>The code above is an integration helper for the select2 autocompleter library. The exact details of the implementation aren&#39;t that important for this discussion. What we&#39;re really interested in is in seeing how it ties in to a larger system.</p>
<p>Let&#39;s imagine we have a model entity <code>User</code>:</p>
<pre><code class="lang-javascript">//in the model
var User = function(data) {
    this.id = m.prop(data.id)
    this.name = m.prop(data.name)
}
User.url = &quot;/users&quot;
User.id = function(user) {return user.id()}
User.text = function(user) {return user.name()}
</code></pre>
<p>This <code>User</code> class implements an interface: it has a static <code>url</code> property and two methods <code>id</code> and <code>text</code> which dereference a system ID and a user-friendly identifier for the <code>User</code> class. I might then later implement the same interface for a <code>Project</code> class, such that I can generically retrive the url, id and readable name for a project.</p>
<p>As I mentioned, Javascript doesn&#39;t have the concept of OOP interfaces, or generics, but if it was a statically typed OOP language, the interface would look something like this:</p>
<pre><code>interface IEntity&lt;T&gt; {
    static string url;
    static number id(T entity);
    static string name(T entity);
}
</code></pre><p>The way to use the select2 widget is to pass it a model entity like <code>User</code> and a <code>m.prop</code> getter-setter, like this:</p>
<pre><code class="lang-javascript">var vm = {
    user: m.prop()
}

//in the view
m(&quot;input&quot;, {config: select2.config({binds: vm.user, type: User})})

//if we select a user from the dropdown, then `vm.user()` will point to it
</code></pre>
<p>The <code>selec2.config</code> accepts a <code>type</code> parameter to which I can pass anything that implements the <code>IEntity</code> interface. It then internally takes care of hooking up the select2 plugin so that it reads the proper id and text fields from an ajax request that is made to the appropriate url.</p>
<p>The helper also accepts a <code>binds</code> property, which is expected to be an <code>m.prop</code> getter-setter, and the helper bi-directionally binds the dropdown&#39;s selected value to the getter-setter.</p>
<p>So when it all comes together, we are then able to freely swap out what model entity populates the options for the select2 widget, and when a user picks an option from the dropdown, we can put the selected item in any getter-setter (or anything that behaves like one).</p>
<pre><code class="lang-javascript">//this is what a project autocompleter might look like
m(&quot;input&quot;, {config: select2.config({binds: vm.project, type: Project})})

//or a booking autocompleter
m(&quot;input&quot;, {config: select2.config({binds: vm.booking, type: Booking})})

//or an article autocompleter
m(&quot;input&quot;, {config: select2.config({binds: vm.article, type: Article})})
</code></pre>
<p>The end result of having defined an interface is that we don&#39;t need to go look up the select2 documentation or copy-paste a bunch of options every time we create a dropdown. Instead, the widget API behaves more like an agnostic shell, much like generic collections that you might see in a statically typed language.</p>
<p>Creating a predictable access pattern via the IEntity interface also lets us pivot in interesting directions. What if we wanted a dropdown that showed all the users, but only for a single project? Easy, create a factory:</p>
<pre><code class="lang-javascript">//in the model
var projectUser = function(projectID) {
    var ProjectUser = function(data) {
        return new User(data)
    }
    ProjectUser.url = &quot;/projects/&quot; + projectID + &quot;/users&quot;
    ProjectUser.id = User.id
    ProjectUser.text = User.text

    return ProjectUser
}

//in the view
m(&quot;input&quot;, {config: select2.config({binds: vm.user, type: projectUser(projectID)})})
</code></pre>
<p>The <code>projectUser</code> creates a class that implements IEntity. We can be sure that it will work with the autocompleter because it fulfills the contract specified by IEntity, and we can easily tell what the scope of the dropdown will be just from looking at the <code>url</code> field.</p>
<hr>
<h3 id="naming-is-hard">Naming is hard</h3>
<p>We can take consistency further in other directions: for example, if we needed to create a date picker widget, it would also needs to bind to a getter-setter.</p>
<p>So why not call the argument for that <code>binds</code> as well? Naming bi-directional binding arguments the same across the board makes the API more discoverable than, say, having specially crafted event handler names for every single widget.</p>
<pre><code class="lang-javascript">//easy to guess if everything else uses the name `binds` as a convention
m(&quot;input&quot;, {config: datepicker.config({binds: vm.date})})

//not so easy to guess
m(&quot;input&quot;, {config: datepicker.config({value: vm.date(), ondatechange: m.withAttr(&quot;value&quot;, vm.date)})})
</code></pre>
<p>When we start bringing all of our conventions together, the end result becomes familiar:</p>
<pre><code class="lang-javascript">//define a component view
select2.view = function(options) {
    return m(&quot;input&quot;, {config: select2.config(options)})
}

//use the component
select2.view({binds: vm.user, type: User})
</code></pre>
<p>If you&#39;ve dabbled with components, you already know how use functions named <code>view</code>. We just saw what <code>binds</code> does, and we also saw what kinds of things can be plugged into <code>type</code>. So now, you could stumble across code like the following and immediately understand it, even without having seen any documentation:</p>
<pre><code class="lang-javascript">datepicker.view({binds: vm.date})
</code></pre>
<hr>
<h3 id="obvious-is-relative">Obvious is relative</h3>
<p>But just because <code>binds</code> and <code>IEntity</code> make sense to us now, it doesn&#39;t mean that they will be obvious to someone who&#39;s not familiar with them. Documentation is still a key piece in a predictable system. Co-workers leave for greener pastures, teams grow. If your system is non-trivial and needs to last longer than even just a couple of years, it&#39;s foolish to ignore the dynamic nature of the world.</p>
<p>Naming conventions such as <code>binds</code> can be documented in a style guide that shows examples of usage for various widgets that already use the convention.</p>
<pre><code class="lang-javascript">//call the `.view` method of a component from your templates in order to include them
//widgets can read and write from getter-setters via the `binds` parameter

select2.view({binds: vm.user, type: User})

datepicker.view({binds: vm.date})
</code></pre>
<p>It&#39;s also good practice to document how to create a trivial <code>binds</code> implementation, so that others can learn how to extend the system within the conventions.</p>
<pre><code class="lang-javascript">//here&#39;s how a create a `binds` option for bi-directional bindings
var getterSetter = m.prop()

//asks user to change the value of a getter-setter if one is not provided
var example = function(options) {
    if (!options.binds()) {
        options.binds(prompt(&quot;Set a value:&quot;))
    }
}

example({binds: getterSetter})
</code></pre>
<p>You can document interfaces by describing their API, and by showing examples of an implementation, as well as consumption:</p>
<pre><code class="lang-javascript">/*
interface IEntity&lt;T&gt; {
    static string url;
    static number id(T entity);
    static string name(T entity);
}
*/

//User implements IEntity
var User = function(data) {
    this.id = m.prop(data.id)
    this.name = m.prop(data.name)
}
User.url = &quot;/users&quot;
User.id = function(user) {return user.id()}
User.text = function(user) {return user.name()}

//-----------------------------------------
//consuming the interface (real world case)
select2.view({binds: vm.user, type: User})

//-----------------------------------------
//consuming the interface (simple example of generic code)
function consume(type, value) {
    console.log(&quot;url:&quot;, type.url, &quot;id:&quot;, type.id(value), &quot;text:&quot;, type.text(value))
}
consume(User, new User({id: 1, name: &quot;John&quot;}))
consume(Project, new Project({id: 1, name: &quot;John&#39;s Project&quot;}))

//exercise: make `ThirdPartyEntity` work w/ `consume`
consume(ThirdPartyEntity, new ThirdPartyEntity({ThirdPartyEntityID: 1, Description: &quot;3rd party entity&quot;}))
</code></pre>
<hr>
<h3 id="conclusion">Conclusion</h3>
<p>We can make complex systems less complex by creating consistent patterns, and documenting these patterns effectively.</p>
<p>Code grows and rots, so it&#39;s important to plan ahead.</p>
<p>I once read a theory that developers hit walls of complexity every time they increase the size of their codebases by an order of magnitude (i.e. the idea is that a junior developer might find it hard to expand their simple procedural programs past 3000 lines, and that developers hit another wall of complexity at 30,000 lines, and again at 300,000 and so on)</p>
<p>My own theory is that the these walls appear when the volume of complexity of a codebase exceeds the volume of complexity solved by the libraries it uses. For example, jQuery is undoubtedly useful when dealing with browser quirks, but once an application grows over a few thousand lines of code, unstructured jQuery code simply becomes too difficult to maintain, and you start needing the discipline of a framework to organize code. But when you&#39;re at tens of thousands of lines of code, you start to run out of entity types to CRUD, and your application growth starts to build on top of existing concepts. This is when you need the mental shift from being a library consumer to being a reusable component author, but with a focus on the interacting parts within the application (as opposed to generic one-glove-fit-all open source libraries).</p>
<p>Hopefully the ideas we saw in this article will help you tame complexity if you need to scale past the hundreds of lines of code wall.</p>

			]]></description>
		</item>
		<item>
			<title>A spreadsheet in 60 lines of javascript</title>
			<link>http://lhorie.github.io/mithril-blog/a-spreadsheet-in-60-lines-of-javascript.html</link>
			<description><![CDATA[
<h2 id="a-spreadsheet-in-60-lines-of-javascript">A spreadsheet in 60 lines of Javascript</h2>
<hr>
<p>Short on time? <a href="examples/spreadsheet-improved.html">See it in action here</a></p>
<hr>
<p>Apps with terse code have a special place in my heart. Note that I said <em>terse</em>, not <em>clever</em>. Cleverness is a tendency to sacrifice code clarity and readability in order to push code size to be smaller (think code golfing). Being terse, on the other hand, is the practice of seeking simplicity in order to make code easier to understand. It implies looking for elegant solutions and avoiding over-engineering.</p>
<p>One such app that looks particularly impressive is this <a href="http://jsfiddle.net/ondras/hYfN3/">spreadsheet</a>, written in a mere 30 lines of vanilla javascript.</p>
<p>I decided to write a version of it using <a href="http://lhorie.github.io/mithril">Mithril</a>. It may seem silly to require a framework (even if it&#39;s a really small one) to do something that has been proven to be doable without one, but the purpose of this exercise is precisely to get an idea of how much boilerplate would be required in order to implement the app using the Mithril framework.</p>
<p>This is an important consideration. Frameworks usually require boilerplate code in order to work, and frameworks like Angular can get notoriously verbose. Verbosity can add various costs to development: extra typing required, steep learning curves, more mental baggage to carry when reading code.</p>
<pre><code class="lang-javascript">//A simple, production-quality AngularJS factory
(function() {
    function something($http) {
        //code here
    }

    something.$injector = [&quot;$http&quot;]

    angular.module(&quot;spreadsheet&quot;).factory(something)
})()
</code></pre>
<p>Mithril positions itself as a minimalist framework. Minimalism can be a slippery slope. It&#39;s easy to make a &quot;minimalist&quot; framework that defers all the hard work to the application developer, but the real goal of minimalism in the context of frameworks is to enable developers to simplify their own codebases <em>in addition</em> to being a simple framework. So let&#39;s see how Mithril fares.</p>
<hr>
<h3 id="the-model-layer">The model layer</h3>
<p>Here&#39;s a <a href="examples/spreadsheet.html">port of the spreadsheet code to Mithril</a>.</p>
<p>The <code>data</code> variable is the in-memory data store. It reads from <code>localStorage</code> on page load and it&#39;s used throughout the code to store the current state of the spreadsheet data. It&#39;s a map of values, whose keys are expect to be named after their cells (e.g. <code>data[&quot;a1&quot;]</code>, <code>data[&quot;b3&quot;]</code>, etc)</p>
<pre><code class="lang-javascript">var data = JSON.parse(localStorage[&quot;spreadsheet&quot;] || &quot;{}&quot;)
</code></pre>
<p>The <code>update</code> function computes an expression if it&#39;s a string that starts with <code>&quot;=&quot;</code>. Then it saves the computed value to both in the in-memory map and <code>localStorage</code>. Here, again, cells are named by combining the letters for the x axis and the numbers from the y axis (e.g. <code>&quot;a1&quot;</code>)</p>
<pre><code class="lang-javascript">function update(cell, value) {
    if (value != null &amp;&amp; value[0] == &quot;=&quot;) {
        try { with (data) data[cell] = eval(value.substring(1)) } catch (e) {}
    }
    else data[cell] = isNaN(+value) ? value : +value
    localStorage[&quot;spreadsheet&quot;] = JSON.stringify(data)
}
</code></pre>
<h3 id="the-view-layer">The view layer</h3>
<p>The <code>grid</code> function creates a table and accepts an arbitrary Mithril template as an argument, which is cloned for every cell in the table.</p>
<pre><code class="lang-javascript">function grid(withCell) {
    for (var rows = [], i = 0; i &lt; 27; i++) {
        for (var cols = [], j = 0; j &lt; 17; j++) {
            var letter = String.fromCharCode(&quot;a&quot;.charCodeAt(0) + j - 1)
            cols.push(m(&quot;td&quot;, i &amp;&amp; j ? withCell(letter + i) : i || letter))
        }
        rows.push(m(&quot;tr&quot;, cols))
    }
    return m(&quot;table&quot;, m(&quot;tbody&quot;, rows))
}
</code></pre>
<p>The <code>view</code> function is the main template. It creates a grid of text inputs, each of which has bindings to synchronize their values to a slot in the <code>data</code> map.</p>
<p>The <code>cellName</code> argument is the name of the corresponding cell. The name of the very first cell is &quot;a1&quot;, the one beside that is &quot;a2&quot;, and so on.</p>
<pre><code class="lang-javascript">function view() {
    return grid(function(cellName) {
        return m(&quot;input&quot;, {
            onchange: m.withAttr(&quot;value&quot;, update.bind(this, cellName)),
            value: data[cellName] || &quot;&quot;
        })
    })
}
</code></pre>
<p>Finally, the last line tells Mithril to run the application:</p>
<pre><code class="lang-javascript">m.module(document.body, {controller: function() {}, view: view})
</code></pre>
<p>You may have noticed the empty controller. There&#39;s only a single writing method in the model (<code>update</code>), and we&#39;re calling it directly from the view to cut down on boilerplate.</p>
<p>As you can see, the code isn&#39;t that complicated: there&#39;s a map of values whose keys are the names of the cells. Whenever an input changes, its respective value is computed (if it&#39;s an <code>eval</code>able expression), and then saved to its respective slot in the <code>data</code> map (and also to <code>localStorage</code>). Then Mithril redraws and puts the UI back in sync with the data.</p>
<p>And this port only takes 28 lines of code, just like the original. Not bad.</p>
<hr>
<h3 id="extending-the-application">Extending the application</h3>
<p>We saw that porting the vanilla app to Mithril yields very little boilerplate, while keeping code quite readable. But the real test for terseness is whether we can build more functionality on top of it: <em>clever</em> code is full of obscurities and it&#39;s hard to understand and modify, but <em>elegant</em> code should be easy to refactor.</p>
<p>Conveniently, we can put our code to the test, because this spreadsheet app can use some improvements. As you might already know, the whole point of a spreadsheet is that they are supposed to be <em>reactive</em>. If the value of <code>a3</code> is <code>&quot;=a1+a2&quot;</code>, then changing the value of <code>a1</code> should also change <code>a3</code>.</p>
<p>Currently our app simply overwrites the expression so once it&#39;s computed, we lose its formula.</p>
<p>Here&#39;s a <a href="http://jsfiddle.net/dnv352kn/">rewrite that fixes that</a>.</p>
<p>The first major change is that our <code>update</code> function is now broken out into three parts: </p>
<ul>
<li>the <code>update</code> function takes care of saving to the in-memory data store and to localStorage as before (but it no longer performs the evaluation of expressions)</li>
<li>the <code>compute</code> function takes care of the expression evaluation logic</li>
<li>and finally, the <code>computable</code> function is a <strong>value object factory</strong>. If the input to this function is a number or a string, it simply returns that value, but if the input is an <code>eval</code>able expression (i.e. a string beginning w/ <code>=</code> and followed by a javascript expression), it returns a String object with a custom <code>valueOf</code> method that computes its <code>eval</code>able expression when called.</li>
</ul>
<pre><code class="lang-javascript">function computable(value) {
    var output = new String(value)
    output.valueOf = compute.bind(this, value)
    return isNaN(+value) ? output : +value
}
function compute(value) {
    if (value != null &amp;&amp; value[0] == &quot;=&quot;) {
        try { with (data) return eval(value.substring(1)) } catch (e) {}
    }
    else return value
}
function update(cell, value) {
    data[cell] = computable(value)
    localStorage[&quot;spreadsheet&quot;] = JSON.stringify(data)
}
</code></pre>
<p>Breaking out <code>compute</code> from <code>update</code> is a fairly standard type of refactorization: we&#39;re simply decoupling code for better separation of concerns and better reusability.</p>
<p>The creation of the <code>computable</code> factory is the key refactorization: a computable enables us to store expressions that can evaluate their values on demand. This function is used by the <code>update</code> function to store computable values in our in-memory <code>data</code> store, and it&#39;s also used at the very beginning of the script to turn the deserialized <code>localStorage</code> data into computable value objects.</p>
<pre><code class="lang-javascript">var data = JSON.parse(localStorage[&quot;spreadsheet&quot;] || &quot;{}&quot;)
for (var cell in data) data[cell] = computable(data[cell])
</code></pre>
<p>A computable value object is an immutable object that behaves mostly like a javascript primitive number or string, with one exception: when we attempt to use a computable entity in a mathematical expression, it implicitly calls the custom <code>valueOf</code> method and uses the evaluated expression instead of using the string value. This allows expressions like <code>a1+a2</code> to perform mathematical computations seamlessly regardless of whether <code>a1</code> and <code>a2</code> are numbers or computables. And since computables can evaluate to expressions that reference other computables, they can recursively cascade a data change through a complex web of computable expressions.</p>
<p>Here are some tests to demonstrate the expected behavior of the computable value object:</p>
<pre><code class="lang-javascript">computable(1) == 1 // true
computable(&quot;hello&quot;) == &quot;hello&quot; // true
computable(&quot;=1+1&quot;).toString() == &quot;=1+1&quot; // true
computable(&quot;=1+1&quot;).valueOf() == 2 // true

data.a1 = 1
computable(&quot;=a1+2&quot;) + 3 == 6 //true

data.a1 = 1
data.a2 = computable(&quot;=a1+2&quot;)
computable(&quot;=a2+3&quot;) + 4 == 10 //true
</code></pre>
<p>In the last two tests you can see how tightly integrated to the language <code>valueOf</code> is. The <code>toString</code> and <code>valueOf</code> methods are implicitly called by Javascript whenever type casting is implied. Computable expressions take advantage of this language feature to implement reactivity.</p>
<hr>
<p>The second major change is that now there&#39;s a formula input at the top. This UI addition lets us see and edit the un-evaluated expression for any given cell.</p>
<p>You can see how the bindings for this input work by looking at the <code>view</code> function:</p>
<pre><code class="lang-javascript">function view() {
    return [
        m(&quot;input.formula&quot;, {
            onchange: m.withAttr(&quot;value&quot;, update.bind(this, cell())),
            value: data[cell()] || &quot;&quot;
        }),
        grid(function(cellName) {
            var value = compute(data[cellName]) || &quot;&quot;
            return m(&quot;input&quot;, {
                onkeydown: move,
                onfocus: cell.bind(this, cellName),
                onchange: m.withAttr(&quot;value&quot;, update.bind(this, cellName)),
                value: value,
                style: {textAlign: isNaN(value) || value === &quot;&quot; ? &quot;left&quot; : &quot;right&quot;}
            })
        })
    ]
}
</code></pre>
<p>The <code>cell</code> variable is simply a view-model getter-setter that holds the name of a cell.</p>
<p>The <code>&quot;input.formula&quot;</code> element has a binding that references the <code>cell</code> getter-setter: when this input is changed, we update the data for the cell referenced by <code>cell()</code>. The value for this input is simply the string value of the <code>data</code> slot referenced by <code>cell()</code>.</p>
<p>In addition, each input in the grid now has a <code>onfocus</code> handler that sets the value of <code>cell</code> to their respective cell names. In short, focusing on a cell displays the uncomputed value for that cell.</p>
<hr>
<p>Finally, one handy UI improvement was added: the app is now keyboard-aware. Pressing the arrows on the keyboard now moves focus around the grid. This happens thanks to the <code>onkeypress</code> event handler <code>move</code>.</p>
<pre><code class="lang-javascript">function move(e) {
    var td = e.target.parentNode, tr = td.parentNode, table = tr.parentNode
    if (e.keyCode == 37) return highlight(tr.childNodes[Math.max(1, td.cellIndex - 1)].firstChild)
    else if (e.keyCode == 38) return highlight(table.childNodes[Math.max(1, tr.rowIndex - 1)].childNodes[td.cellIndex].firstChild)
    else if (e.keyCode == 39) return highlight(tr.childNodes[Math.min(tr.childNodes.length - 1, td.cellIndex + 1)].firstChild)
    else if (e.keyCode == 40) return highlight(table.childNodes[Math.min(table.childNodes.length - 1, tr.rowIndex + 1)].childNodes[td.cellIndex].firstChild)
    else m.redraw.strategy(&quot;none&quot;)
}
function highlight(cell) {
    cell.focus()
    cell.selectionEnd = cell.value.length
    return false
}
</code></pre>
<p>There&#39;s also a one-liner in <code>view</code> that takes care of text alignment of numbers vs text, but other than that, that&#39;s pretty much it. These few UI improvements add 16 lines to the code (more than half of the original size!), but I&#39;d argue that being able to navigate a spreadsheet with the keyboard and quickly be able to tell apart text from numbers are important features to have - if you disagree, you can reduce the code size by 16 lines and still have a reactive spreadsheet :)</p>
<hr>
<p>Once you understand the <code>computable</code> value object, the rest of the application is fairly straightforward: it boils down to the basic principle of data flowing from the model to the view, and then using event handlers to push changes back to the model.</p>
<p>We already covered in other articles some reasons as to what makes this Mithril app clean (despite it having non-trivial functionality like focus-aware reactivity), but it&#39;s worth mentioning them again: </p>
<ul>
<li>Mithril&#39;s &quot;call-me-when-you-need&quot; approach to tooling and the well-defined flow of data makes it easy to spend time thinking about the problem domain, rather than wasting time on framework-specific concepts.</li>
<li>Explicit data bindings (as opposed to cookie-cutter binding tools like <code>ng-model</code>) allow a greater degree of flexibility when connecting form elements to model data slots, which paradoxically results in less complexity.</li>
<li>The ability to idiomatically have procedural code live in functions in the view layer lets us express DOM actions without a lot of boilerplate integration code</li>
<li>Idiomatic Mithril code takes the concept of design patterns to heart: we implement <em>patterns</em> of code in their simplest form, rather than creating bulky classes named after patterns.</li>
</ul>
<p>Another thing that is worth noting (especially for those who are averse to Mithril&#39;s templating syntax), is that even though this app literally fills the page with DOM elements, there&#39;s very little &quot;markup&quot; code. This illustrates well the fact that, in non-trivial applications, logic often dominates in terms of code volume. A lot of boilerplate in other frameworks come from shuffling logic around in order to keep HTML &quot;clean&quot; in a way that is reminicent of <a href="http://en.wikipedia.org/wiki/Zero-sum_game">zero sum games</a> (i.e. get clarity over here at the expense of added complexity over there). We&#39;ve learned long ago to forego normalization purity in databases in favor of a pragmatic middle ground, and I think this app is an example that shows that pragmatism is a good design driver in frontend as well.</p>

			]]></description>
		</item>
		<item>
			<title>What is a view-model</title>
			<link>http://lhorie.github.io/mithril-blog/what-is-a-view-model.html</link>
			<description><![CDATA[
<h2 id="what-is-a-view-model">What is a View Model</h2>
<p><em>This article was adapted from an essay in the mailing list</em></p>
<p>Last week we saw how we can animate things with Velocity.js. A related topic that came up on the Mithril bug tracker (and that keeps coming up every once in a while) is the topic of <em>application</em> state (as opposed to <em>data</em> state). Today we&#39;ll explore that topic:</p>
<p>Let&#39;s imagine we have a button, and that when we click on that button, a panel shows up. When we click on the button again, the panel disappears. In jQuery, we can code this in an action-centered way: &quot;on click, show&quot;. Mithril, however, (and for that matter, most MVC frameworks) encourages us to be data-centered: &quot;if this flag is set, show&quot;. This means that when we are debugging, instead of having to use PhantomJS to emulate a user clicking through our app to get to a specific state in our application, we can always render the exact UI state that we want if we have our data setup in just the right way. And since data is easy to manipulate via plain javascript, the entire testing workflow is also a lot easier as a result.</p>
<p>But a &quot;this panel is open&quot; flag is not really a &quot;model&quot; value in the traditional sense. It doesn&#39;t map to &quot;Users&quot; or &quot;Projects&quot;, or to anything else that we might want to store in a database. It&#39;s merely data <em>about</em> the UI. This type of data is also known as <em>application state</em>.</p>
<p>Many people get confused when they need to decide where this application state should go. Should it go in the controller? Should it be hidden in the view layer behind a helper function?</p>
<p>The answer is that it is <strong>state</strong> after all, so it should be in the model layer.</p>
<p>The rationale for this goes back to the definition of MVC: </p>
<ul>
<li>the Model layer is responsible for application data, business rules and logic.</li>
<li>the View is responsible for displaying data</li>
<li>the Controller is a mechanism that translates user input into commands for the model layer</li>
</ul>
<hr>
<h3 id="a-little-bit-of-history">A little bit of history</h3>
<p>In classic MVC (the original Smalltalk one), the Model layer notifies the view of changes to data; the view can send messages to the controller to tell the app to do things; the controller then manipulates the model, which then notifies the view, ad infinitum. The controller may also modify the view without assistance from the Model layer (for example to show a loading icon.) In this original implementation, all layers could contain code: the view could subscribe to model events via the observer pattern, and likewise, the model could trigger events via the same mechanism.</p>
<p>Since then, a lot of twists have been made: we adapted the pattern from the realm of desktop apps to the realm of server-side architectures, and from there to thick client-side architectures. Somewhere along the lines, we started to conflate the View layer with HTML, the Model layer with database tables, and reached the conclusion that anything that is neither HTML nor SQL related must be part of the Controller layer.</p>
<p>In server-side architectures, application state largely became conflated with URLs (so much so, that POST-only URLs are still considered bad practice, since they make it hard to reach certain states). Client-side MVC became prominent precisely because URLs were not enough to express all possible states in heavily AJAX-driven applications. So as complexity grew, we started to see a sort of limbo with application state that didn&#39;t fit into a URL, and that didn&#39;t really fit anywhere else either (given the cookie-cutter molds that frameworks provided us).</p>
<p>One of the things I&#39;m trying to do with Mithril is encourage people to go back to the basics and realize that a lot of the assumptions and cloudiness surrounding MVC is actually wrong: the view layer isn&#39;t HTML-only, the model layer isn&#39;t supposed to be solely about ORM classes, controllers aren&#39;t supposed to be a pool where we dump things that we don&#39;t know how to fit into the rest of the framework.</p>
<p>Going back to the topic of application state: state is just data. <em>Meta</em> data, but still data. Here&#39;s an example to illustrate that point: sortable tables. You have a table full of data, you click on a header, it sorts by that header. What if you want to permalink this configuration? Often, we modify the app so that the sorting options are part of the URL. But what if we need to embed this table in another page that makes use of the URL for something else? Or what if the URL is too long? We can keep refactoring and refactoring for every new requirement, but at the end of the day, you have to save the sorting options somewhere.</p>
<p>Of the three layers in MVC, the Model is the one that we really should be using for that. Note that the model layer doesn&#39;t necessarily need to save things to a database on the server. If we now go backwards cutting off requirements, we can make a model entity that saves to localStorage, or heck, even to just memory, if the application state is transient enough to be discardable at page unload.</p>
<p>If we structure our code this way from the beginning, then we have a clear API to use the application state in our controllers and views, and we can isolate the exact persistence implementation details to the model layer.</p>
<hr>
<h3 id="enter-view-models">Enter view models</h3>
<p>Some newer frameworks (most notoriously .NET MVC) introduce the concept of &quot;View Models&quot;, i.e. Model layer entities that exist exclusively to store UI state. They are different from traditional MVC models because by definition, they are tightly tied to specific view components.</p>
<p>Using a singleton is perhaps the simplest way of implementing a View Model:</p>
<pre><code class="lang-javascript">app.widget1State = {isPressed: m.prop(false)}

/*...*/
m(&quot;button&quot;, {
  onmousedown: function(){ app.widget1State.isPressed(true) },
  onmouseup: function(){ app.widget1State.isPressed(false) }
})
</code></pre>
<p>I use <code>m.prop</code> above to ensure we can refactor the View Model (here, the <code>m.prop</code> getter-setter is an in-memory data storage mechanism; we could later replace it with a custom getter-setter function that saves to localStorage, or the database server, or what have you, because it follows the <a href="the-uniform-access-principle.html">uniform access principle</a>)</p>
<p>View Models are meant to store application state (e.g. if there&#39;s a field and a cancel button, and we need to store the temporary value while editing), and regular Models are meant to store data state (e.g. the value after you save that field). You don&#39;t really want to store stuff like <code>valueBeforeEdit</code> and <code>currentValue</code> in your data model class; these are details that only exist because of the UI requirements for a cancel button and are not something that your data model should care about. Similarly, the sorting options of our sortable table and the flag for whether a panel is visible are both cases of application state, so they should live in a view model.</p>
<hr>
<h3 id="scoping-view-models">Scoping view models</h3>
<p>Normally, for complex pages, it might be tempting to make one big view model to drive the whole page, but it often makes more sense to scope one view model to each component on a page. It&#39;s not uncommon that you might need to reference one view model from an unrelated component, but these are uni-directional desired dependencies.</p>
<p>For example, if our sortable table has edit buttons that open up a modal dialog w/ a form, these buttons might set a value in the form&#39;s view model. However, this dependency is <em>desired</em> because we <em>want</em> the form dialog to be tied to the button. And since a view model is largely a data storage mechanism, we can still use it in other unrelated scenarios without worrying about the sortable table view model.</p>
<p>Having a single monolithic view model makes it harder to pull out components and reuse them elsewhere without bringing a lot of unrelated baggage with it.</p>
<hr>
<h3 id="conclusion">Conclusion</h3>
<p>Hopefully this essay can help you figure out where to put what kind of code. A lot of it is more a matter of understanding the MVC pattern and organizing the code in a pragmatic way, as opposed to inventing a &quot;Mithril way&quot; of forcing things to work around dogmatic assumptions that we bring over from our experiences with other frameworks. At the end of the day, the MVC pattern is supposed to be helping us, not getting in our way.</p>

			]]></description>
		</item>
		<item>
			<title>Velocity.js animations in Mithril</title>
			<link>http://lhorie.github.io/mithril-blog/velocity-animations-in-mithril.html</link>
			<description><![CDATA[
<h2 id="velocity-js-animations-in-mithril">Velocity.js animations in Mithril</h2>
<p>Some people have asked me how they could get animations to work with <a href="http://lhorie.github.io/mithril">Mithril</a>, so today we&#39;ll look at how to run some simple <a href="http://julian.com/research/velocity/">Velocity.js</a>-powered animations in Mithril templates.</p>
<p>Velocity.js is a library that allows us to run Javascript-based animations which perform on par with CSS transitions (and which work in IE). It&#39;s designed to be a drop-in replacement for jQuery&#39;s <code>animate</code> method, but it can also be used as a standalone library (i.e. without jQuery).</p>
<p>The easiest way to get started with it is to include a reference to it from a CDN:</p>
<pre><code class="lang-markup">&lt;script src=&quot;//cdn.jsdelivr.net/velocity/1.0.0/velocity.min.js&quot;&gt;&lt;/script&gt;
</code></pre>
<p>Calling Velocity as standalone library typically looks like this:</p>
<pre><code class="lang-javascript">Velocity(theElement, {opacity: 0})
</code></pre>
<p>The code above should hopefully be self-explanatory: it animates the opacity of an element from its current value to zero. So, assuming it started at <code>opacity: 1</code>, then it performs a fade-out effect.</p>
<p>Let&#39;s create a contrived mini-application so we can hook up some animations. First let&#39;s define some data:</p>
<pre><code class="lang-javascript">//model
var people = [
    {id: 1, name: &quot;John&quot;},
    {id: 2, name: &quot;Mary&quot;},
    {id: 3, name: &quot;Bob&quot;}
]
</code></pre>
<p>Next, let&#39;s create a view to display a list of people:</p>
<pre><code class="lang-javascript">//view
var view = function() {
    return m(&quot;ul&quot;, [
        people.map(function(person) {
            return m(&quot;li&quot;, person.name)
        })
    ])
}
</code></pre>
<p>And finally, let&#39;s add a bit of functionality: removing a person when its list item is clicked.</p>
<pre><code class="lang-javascript">//controller
var controller = function() {
    this.remove = function(person) {
        people.splice(people.indexOf(person), 1)
    }
}

//view
var view = function(ctrl) {
    return m(&quot;ul&quot;, [
        people.map(function(person) {
            return m(&quot;li&quot;, {
                key: person.id,
                onclick: ctrl.remove.bind(this, person)
            }, person.name)
        })
    ])
}
</code></pre>
<p>One thing to notice is that we added a <code>key</code> attribute to the <code>&lt;li&gt;</code>. This is usually good practice if you delete list items because it allows Mithril&#39;s virtual DOM diffing engine to be smarter about DOM reuse by providing referential metadata.</p>
<p>Putting it all together:</p>
<pre><code class="lang-javascript">//model
var people = [
    {id: 1, name: &quot;John&quot;},
    {id: 2, name: &quot;Mary&quot;},
    {id: 3, name: &quot;Bob&quot;}
]

//controller
var controller = function() {
    this.remove = function(person) {
        people.splice(people.indexOf(person), 1)
    }
}

//view
var view = function(ctrl) {
    return m(&quot;ul&quot;, [
        people.map(function(person) {
            return m(&quot;li&quot;, {
                key: id,
                onclick: ctrl.remove.bind(this, person)
            }, person.name)
        })
    ])
}

//run the app
m.module(document.body, {controller: controller, view: view})
</code></pre>
<p>As we saw earlier, in order to create an animation with Velocity, we need to pass a DOM element as the first argument. In Mithril, templates like the <code>view</code> function above are merely javascript functions that spit out javascript objects, but we can get a handle to the real DOM element by declaring a <code>config</code> attribute.</p>
<p>The <code>config</code> callback gets called after rendering occurs, when all the DOM elements generated by the template are guaranteed to be attached to the HTML document. It is meant to be used for arbitrary DOM manipulation.</p>
<pre><code class="lang-javascript">var fadesIn = function(element, isInitialized, context) {
    if (!isInitialized) {
        element.style.opacity = 0
        Velocity(element, {opacity: 1})
    }
}

var view = function(ctrl) {
    return m(&quot;ul&quot;, [
        people.map(function(person) {
            return m(&quot;li&quot;, {
                key: id,
                onclick: ctrl.remove.bind(this, person),
                config: fadesIn
            }, person.name)
        })
    ])
}
</code></pre>
<p>In the snippet above, we defined a new helper function called <code>fadesIn</code>, which we use as a <code>config</code> callback for the <code>li</code>. It sets the list item&#39;s opacity to zero, and then animates it back to 1 (i.e. it fades the element in)</p>
<p>The <code>element</code> argument is, as the name suggests, the <code>&lt;li&gt;</code> element.</p>
<p>The second argument, <code>isInitialized</code> is a flag that is set to false on initial rendering, and true for subsequent renders. As you can see, we used it to run the animation only when the element gets created, as opposed to running it every time a redraw occurs.</p>
<p>The third argument is an object that can be used to store element-specific data between redraws. You can <a href="http://lhorie.github.io/mithril/mithril.html#persisting-config-data">read more about it here</a></p>
<p>With this <code>config</code> callback in place, you should now see the list items fade in when the page loads.</p>
<hr>
<h2 id="what-about-fading-out-">What about fading out?</h2>
<p>Fading out is not that much harder to implement, but there&#39;s a cognitive dissonance caveat associated with it that often confuses people.</p>
<p>When Mithril redraws, views always look at the current state of the data to figure out what DOM elements should or should not be in the document. But fading out <em>after</em> removing an element from the model breaks that thought model: by definition, an animation starts and ends at different times, so if we remove a person from the list, the system would need to know somehow that its corresponding <code>&lt;li&gt;</code> element should stay in the document for the duration of the animation, even though the person was already removed from our data object at the beginning of the animation.</p>
<p>But because we&#39;re using a third-party library to integrate animations to Mithril, the framework would not be able to hide some of the complexities that come with the asynchronous nature of the animations. For example, what is the framework supposed to do with a DOM element if an animation is cancelled mid-way? Should it force you to rollback the deletion in the data model? Should it assume that you will clean up the DOM element manually? If you allow the framework to remove it for you, it might do it too early (e.g. if a redraw happens during a animation), but if you forget to remove it manually or mark it for removal, there&#39;s no way the system would know when to handle it, and the element would just sit there forever.</p>
<p>A simpler solution to this conundrum is to shift back in time and allow the animation to happen <em>before</em> the destructive data change happens, and <em>only then</em>, allow the removal of the person to happen atomically in our model layer. Here&#39;s a helper that runs the animation before the removal:</p>
<pre><code class="lang-javascript">var fadesOut = function(callback) {
    return function(e) {
        //don&#39;t redraw yet
        m.redraw.strategy(&quot;none&quot;)

        Velocity(e.target, {opacity: 0}, {
            complete: function() {
                //now that the animation finished, redraw
                m.startComputation()
                callback()
                m.endComputation()
            }
        })
    }
}
</code></pre>
<p>The snippet above defines a helper function called <code>fadesOut</code>, which returns an event handler that runs an animation, and then runs an arbitrary callback when the animation finishes.</p>
<p>The <code>m.redraw.strategy(&quot;none&quot;)</code> line tells Mithril that we don&#39;t want to redraw when the event handler returns (because at that point, nothing has changed yet).</p>
<p>The <code>complete</code> callback that we pass to Velocity.js is an asynchronous 3rd party callback, so there we call <code>m.startComputation</code> and <code>m.endComputation</code> to tell Mithril that we want to potentially redraw. Notice that we are not calling <code>m.redraw</code> because that function forces a redraw to happen immediately. We might conceivably want to run AJAX requests or other asynchronous operations in the <code>callback</code> function, so we need to use <code>m.startComputation</code> and <code>m.endComputation</code> to allow Mithril to wait for those asynchronous operations to complete.</p>
<p>Using the <code>fadesOut</code> helper is simple: just wrap it around the <code>remove</code> function.</p>
<pre><code class="lang-javascript">var view = function(ctrl) {
    return m(&quot;ul&quot;, [
        people.map(function(person) {
            return m(&quot;li&quot;, {
                key: id,
                onclick: fadesOut(ctrl.remove.bind(this, person)),
                config: fadesIn
            }, person.name)
        })
    ])
}
</code></pre>
<p>Now we have list items that fade in on page load, and fade out when we click on them. Here&#39;s the entire code so far.</p>
<pre><code class="lang-javascript">//model
var people = [
    {id: 1, name: &quot;John&quot;},
    {id: 2, name: &quot;Mary&quot;},
    {id: 3, name: &quot;Bob&quot;}
]

//controller
var controller = function() {
    this.remove = function(person) {
        people.splice(people.indexOf(person), 1)
    }
}

//view
var view = function(ctrl) {
    return m(&quot;ul&quot;, [
        people.map(function(person) {
            return m(&quot;li&quot;, {
                key: person.id,
                onclick: fadesOut(ctrl.remove.bind(this, person)),
                config: fadesIn
            }, person.name)
        })
    ])
}

//view helpers
var fadesIn = function(element, isInitialized, context) {
    if (!isInitialized) {
        element.style.opacity = 0
        Velocity(element, {opacity: 1})
    }
}
var fadesOut = function(callback) {
    return function(e) {
        //don&#39;t redraw yet
        m.redraw.strategy(&quot;none&quot;)

        Velocity(e.target, {opacity: 0}, {
            complete: function() {
                //now that the animation finished, redraw
                m.startComputation()
                callback()
                m.endComputation()
            }
        })
    }
}

//run the app
m.module(document.body, {controller: controller, view: view})
</code></pre>
<hr>
<h3 id="what-about-page-changes-">What about page changes?</h3>
<p>The code above works well for actions within a single page, but what if we want to run animations when jumping between routes?</p>
<p>As per the documentation, <code>config: m.route</code> is the <a href="http://lhorie.github.io/mithril/mithril.route.html#mode-abstraction">idiomatic way of creating routed links</a>, but there&#39;s nothing stopping us from using a custom <code>config</code> function instead, if we want to run animations before leaving a page. Here&#39;s how one might go about implementing it:</p>
<pre><code class="lang-javascript">//helper
var fadesOutPage = function(element, isInitialized, context) {
    if (!isInitialized) {
        element.onclick = function(e) {
            e.preventDefault()
            Velocity(document.getElementById(&quot;container&quot;), {opacity: 0}, {
                complete: function() {
                    m.route(element.getAttribute(&quot;href&quot;))
                }
            })
        }
    }
}

//in the templates
m(&quot;#container&quot;, {config: fadesIn}, [
    m(&quot;a[href=&#39;/foo&#39;]&quot;, {config: fadesOutPage}, &quot;go to foo&quot;)
])
</code></pre>
<p>As you can see, the code is strikingly similar what we have been doing before.</p>
<p>The <code>fadesIn</code> helper makes the page fade in when it loads, as it did before.</p>
<p>On the link, we defined an <code>onclick</code> handler that calls Velocity to run some animations on the container element and then redirect using m.route after the animation is done. One difference is that defining an event handler within a <code>config</code> callback doesn&#39;t require us to call <code>m.redraw.strategy(&quot;none&quot;)</code>. Recall that <code>config</code> is designed to be used for integrating non-Mithril code to Mithril templates, and in this case the <code>onclick</code> handler is just plain vanilla javascript, which doesn&#39;t do any auto-redrawing. In addition, we don&#39;t need to call <code>m.startComputation</code> and <code>m.endComputation</code> either because the <code>m.route()</code> redirect forces the page to redraw anyways.</p>
<p>Note that we could have used <code>onclick</code> as we did with <code>fadesOut</code>, instead of <code>config</code> - There&#39;s really no hard rules for whether you should use one or the other. In this article, I used <code>onclick</code> for <code>fadesOut</code> to make it clear that there&#39;s a cause-effect relationship between clicking and fading and removing a person, and I used <code>config</code> for <code>fadesOutPage</code> to make it look consistent with the way regular <code>{config: m.route}</code> links do. But as we saw, the default rendering strategy when we attach an <code>onclick</code> in the template required us to add some extra code to prevent auto-redrawing from happening in that particular event handler. The rule of thumb is that an <code>onclick</code> handler auto-redraws by default (for the sake of convenience in the data-model-updating case), whereas <code>config</code> has auto-redrawing turned off by default (for convenience in the free-reign-over-the-DOM case). As we saw, it&#39;s perfectly possible to change these defaults, so just use your best judgement to decide what option makes your code the most readable.</p>

			]]></description>
		</item>
		<item>
			<title>Extending the view language</title>
			<link>http://lhorie.github.io/mithril-blog/extending-the-view-language.html</link>
			<description><![CDATA[
<h2 id="extending-the-view-language">Extending the view language</h2>
<p>As you may know, <a href="http://lhorie.github.io/mithril">Mithril</a> is a pretty minimalist framework, which allows sugar functionality to be created by the community.</p>
<p>A recurring mantra in Mithril is that if something is too noisy or repetitive, you can put the verbosity in a function and call that instead. Today we&#39;ll look at a somewhat surprising extension point, but one that is extremely powerful: wrapping around the <code>m</code> method.</p>
<p>First let&#39;s create a basic wrapper:</p>
<pre><code class="lang-javascript">var mx = function(selector, attrs, children) {
    return m(selector, attrs, children)
}
</code></pre>
<p>As you can see, this doesn&#39;t really do anything new. The key here, though, is that it allows us to programmatically edit the attributes before creating the virtual dom element via <code>m</code>.</p>
<p>Let&#39;s create a simple collection of <em>attribute transformers</em>:</p>
<pre><code class="lang-javascript">var customAttrs = {
    cautions: function(callback) {
        this.onclick = function(e) {
            if (prompt(&quot;Are you sure?&quot;)) callback(e)
        }
    },
    toggles: function(flag) {
        if (!this.style) this.style = {}
        this.style.display = flag ? &quot;block&quot; : &quot;none&quot;
    }
}
</code></pre>
<p>An attribute transformer is simply a method that is meant to be called on a attribute that modifies it. In the example above, <code>cautions</code> adds an <code>onclick</code> handler that prompts the user before running a callback. <code>toggles</code> shows or hides an element based on a flag.</p>
<p>We can now extend <code>mx</code> to tap into our collection:</p>
<pre><code class="lang-javascript">var mx = function(selector, attrs, children) {
    for (var attrName in attrs) {
        if (customAttrs[attrName]) customAttrs[name].call(attrs, attrs[attrName]) 
    }
    return m(selector, attrs, children)
}
</code></pre>
<p>What we&#39;re doing in the code above is look for attribute names that exist in the <code>customAttrs</code> dictionary. If one does, we call that function using the <code>attrs</code> object as the <code>this</code> object.</p>
<p>Now we can easily bind our custom attribute transformers to a template:</p>
<pre><code class="lang-javascript">var buttonVisible = m.prop(false)
var myView = function() {
    return [
        m(&quot;a&quot;, {onclick: buttonVisible.bind(this, !buttonVisible())})
        mx(&quot;button&quot;, {toggles: buttonVisible, cautions: ctrl.selfDestruct}, &quot;Press if evil plans are foiled&quot;)
    ]
}
</code></pre>
<p>In the code above, the button becomes visible when the <code>buttonVisible</code> getter-setter is set to true, and on click, it prompts the user to confirm that they do, in fact, want to call <code>selfDestruct</code>.</p>
<hr>
<h3 id="handling-conflicts">Handling conflicts</h3>
<p>A clever reader might notice that this transformer suffers from one problem - it can clobber attributes. For example: </p>
<pre><code class="lang-javascript">mx(&quot;button&quot;, {cautions: ctrl.remove, onclick: ctrl.doSomethingElse}, &quot;Remove&quot;)
</code></pre><p>In the snippet above, <code>cautions</code> assigns a function to the <code>onclick</code> attribute, which means that <code>ctrl.doSomethingElse</code> does not run when we click on the button.</p>
<p>Fortunately, javascript is a dynamic language, which allows us to use <strong>monkeypatching</strong> to easily solve this problem:</p>
<pre><code class="lang-javascript">var monkeypatch = function(f1, f2) {
    return function() {
        var output1, output2
        if (typeof f1 == &quot;function&quot;) output1 = f1.apply(this, arguments)
        if (typeof f2 == &quot;function&quot;) output2 = f2.apply(this, arguments)

        //make compatible w/ event handler `return false` behavior
        return output1 === false || output2 === false ? false : undefined
    }
}
var customAttrs = {
    cautions: function(callback) {
        this.onclick = monkeypatch(this.onclick, function(e) {
            if (prompt(&quot;Are you sure?&quot;)) callback(e)
        })
    }
}
</code></pre>
<p>This preserves an existing <code>onclick</code> if it already exists, so that if the new <code>onclick</code> gets called, both the existing <code>onclick</code> and the callback run one after the other. We can easily tweak the order of execution for event handlers by simply changing the order of the parameters, and we can even replace <code>monkeypatch</code> altogether with different helpers to achieve more advanced event handler coordination (e.g. preventing a handler from running based on the return value of another.)</p>
<hr>
<h3 id="conclusion">Conclusion</h3>
<p>By wrapping around the <code>m</code> function, we are able to add custom functionality to templates using the same familiar syntax as regular HTML attributes.</p>
<p>Not only can we mix and match different units of functionality in a single DOM element, but we can also maintain control over how they interact with each other, even in the hairiest scenarios.</p>
<p><em>And this is only the beginning.</em> We saw that the <code>mx</code> wrapper we saw above only passes attributes to the list of transformers. But it&#39;s perfectly possible to expand this method and make it also introspect the <code>selector</code> parameter, as well as the virtual element that is returned from the wrapped <code>m</code> call, and even the children virtual elements, so we can create flexible transformers that act differently based on various criteria.</p>
<p>Here&#39;s an example that makes a good exercise to the reader: bi-directional bindings. Try creating a transformer called <code>binds</code>, which can read and write to a <code>m.prop</code> getter-setter, and that can correctly attach itself to a virtual element, considering that you need to read the <code>value</code> attribute in text inputs, but you need to read the <code>checked</code> attribute for checkboxes and radio boxes, and so on.</p>
<p>Or try writing one that replaces an empty child list with a &quot;there are no items&quot; text node. Or one that changes the output of the selector <code>a[href]</code>&#39;s into the equivalent of <code>[href=&quot;javascript:;&quot;]</code>. There&#39;s an endless amount of niceties that you can add to improve the developer ergonomics of the system.</p>
<p>And we can use the same system to add non-trivial functionality. The fact that we can tap into Mithril&#39;s <code>config</code> attribute from transformers means that, in addition to being able to modify virtual elements on the fly, we can also wrap around 3rd-party library integration boilerplate while keeping the ability of managing element lifecycles. In other words, we can have complex widgets with nice syntax. <em>And</em> we can still mixin transformers. <em>And</em> we still have the ability to <a href="when-css-lets-you-down.html">introspect and edit</a> components after inclusion if needed.</p>
<p>Before I leave you with this cool new technique, remember that with great power comes great responsibility. A wrapper&#39;s job is to hide complexity, and in this case there&#39;s two interfaces to consider: how we use the wrapper in templates and how easy it is to add transformers to the system. In addition, you also need to be aware of the cost of the wrapper&#39;s complexity itself. You are responsible for deciding how often your version of <code>mx</code> is called and how much &quot;magic&quot; that wrapper performs, given that the cost of the wrapper is multiplied by the number of times you call it.</p>
<p>Generally speaking, the cost of a wrapper - even a complex one - is surprisingly negligible. (Fun fact: Mithril&#39;s templating engine is fast even though <code>m()</code> uses regular expressions!) However, calling a carelessly slow implementation of <code>mx</code> for every element in a page that has tens of thousands of elements is bound to cause problems. If push comes to shove, there <em>are</em> ways to get around performance problems of that nature, but it&#39;s always better to put some thought in the design phase than to fix mistakes in the maintenance phase.</p>
<p>Anyways, I hope this article gives you some ideas on how to make your templates cleaner and your experience with Mithril templating even more pleasant.</p>

			]]></description>
		</item>
	</channel>
</rss>