<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Knock Me Out]]></title>
  <link href="http://www.knockmeout.net/atom.xml" rel="self"/>
  <link href="http://www.knockmeout.net/"/>
  <updated>2022-10-18T16:08:41+00:00</updated>
  <id>http://www.knockmeout.net/</id>
  <author>
    <name><![CDATA[Ryan Niemeyer]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Knockout in 2019]]></title>
    <link href="http://www.knockmeout.net/2019/08/knockout-in-2019.html"/>
    <updated>2019-08-16T14:53:05-05:00</updated>
    <id>http://www.knockmeout.net/2019/08/knockout-in-2019</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://www.knockmeout.net/images/posts/hello.jpg"></p>

<p>Hello! Are you currently developing with <a href="http://knockoutjs.com">Knockout</a>? Much has changed in the landscape of client-side libraries since Knockout was considered a popular choice, but there still seem to be many successful projects using it today. I would love to hear about the interesting things that you are building with Knockout in 2019.</p>

<p>For the last several years, I have been working with <a href="https://reactjs.org/">React</a> on the front-end (and Node on the server-side) while working on <a href="http://leankit.com">LeanKit</a>. So, while I have been having lots of fun with JavaScript, I haven&rsquo;t had a chance to do anything new with Knockout lately. I would really enjoy spending time getting caught up and helping out in the Knockout world.</p>

<h3>Looking for feedback on these questions:</h3>

<ul>
<li>What would be useful for me to spend some time on?</li>
<li>What are your biggest challenges with Knockout in 2019?</li>
<li>Are there new plug-ins that could be created to solve a problem?</li>
<li>Should I update many of my existing libraries to have modern code and a up-to-date build system?</li>
<li>Any other ideas come to mind?</li>
</ul>


<p>Reply in the comments or send me an email at <a href="&#x6d;&#97;&#105;&#x6c;&#x74;&#111;&#x3a;&#114;&#x79;&#x61;&#110;&#x40;&#107;&#110;&#111;&#99;&#x6b;&#109;&#x65;&#111;&#x75;&#x74;&#46;&#110;&#x65;&#116;&#46;">&#114;&#x79;&#97;&#x6e;&#x40;&#107;&#110;&#111;&#99;&#107;&#x6d;&#101;&#111;&#117;&#x74;&#x2e;&#x6e;&#x65;&#x74;&#x2e;</a> Thanks!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Knockout.js 3.3 Released]]></title>
    <link href="http://www.knockmeout.net/2015/02/knockout-3-3-released.html"/>
    <updated>2015-02-18T10:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2015/02/knockout-3-3-is-out</id>
    <content type="html"><![CDATA[<p><a href="http://knockoutjs.com">Knockout</a> 3.3 is available now! This release features some nice refinements to the components functionality along with a number of other small enhancements and bug fixes. The full release notes can be found <a href="https://github.com/knockout/knockout/releases/tag/v3.3.0">here</a>.</p>

<p> In this release cycle, we welcomed <a href="https://github.com/brianmhunt">Brian Hunt</a> to the core team and he has brought some great energy and contributions to the project. <a href="https://github.com/SteveSanderson">Steve</a> and <a href="https://github.com/mbest">Michael</a> once again made the bulk of the major changes in this release along with a number of other pull requests from the community.</p>

<h2>Components refinements</h2>

<p>We received lots of great feedback regarding Knockout&rsquo;s component functionality. Many developers seem to be having great success using this style of development. For 3.3, we focused on a few low-level enhancements that should provide some increased flexibility.</p>

<h3>Synchronous Flag</h3>

<p>Components were always rendered asynchronously previously, even when the template/viewModel were already cached. Now, the component registration can include a &ldquo;synchronous&rdquo; flag to indicate that the component should render synchronously, if it can. In the case where you have many nested components, this can help alleviate issues with reflows and/or flickering while rendering. The syntax would look like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">components</span><span class="p">.</span><span class="nx">register</span><span class="p">(</span><span class="s2">&quot;my-component&quot;</span><span class="p">,</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">template</span><span class="o">:</span> <span class="s2">&quot;&lt;div data-bind=\&quot;text: firstName\&quot;&gt;&lt;/div&gt;&quot;</span><span class="p">,</span>
</span><span class='line'>    <span class="nx">viewModel</span><span class="o">:</span> <span class="p">{</span> <span class="nx">require</span><span class="o">:</span> <span class="s2">&quot;myModule&quot;</span> <span class="p">},</span>
</span><span class='line'>    <span class="nx">synchronous</span><span class="o">:</span> <span class="kc">true</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<h3>Working with component child nodes</h3>

<p>In Knockout 3.3, you now have options for working with the child nodes contained inside of a component. There are three enhancements that go together targetting this area:</p>

<p>1- The <code>template</code> binding can accept an array of DOM nodes directly via a <code>nodes</code> option</p>

<p>2- If you are using a <code>createViewModel</code> function for your component, it will now receive the child nodes and you can determine how to expose them on your component&rsquo;s view model for binding against the template binding</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">components</span><span class="p">.</span><span class="nx">register</span><span class="p">(</span><span class="s2">&quot;accordion-item&quot;</span><span class="p">,</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">template</span><span class="o">:</span> <span class="s2">&quot;&lt;h2 data-bind=\&quot;template: { nodes: headerNodes }\&quot;&gt;&lt;/h2&gt;&lt;div data-bind=\&quot;template: { nodes: bodyNodes }\&quot;&gt;&lt;/div&gt;&quot;</span><span class="p">,</span>
</span><span class='line'>    <span class="nx">viewModel</span><span class="o">:</span> <span class="p">{</span>
</span><span class='line'>        <span class="nx">createViewModel</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">params</span><span class="p">,</span> <span class="nx">componentInfo</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="k">return</span> <span class="p">{</span>
</span><span class='line'>                <span class="nx">data</span><span class="o">:</span> <span class="nx">params</span><span class="p">.</span><span class="nx">data</span><span class="p">,</span>
</span><span class='line'>                <span class="c1">// grab the first node (as an array) for the header</span>
</span><span class='line'>                <span class="nx">headerNodes</span><span class="o">:</span> <span class="nx">componentInfo</span><span class="p">.</span><span class="nx">templateNodes</span><span class="p">.</span><span class="nx">slice</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span>
</span><span class='line'>                <span class="c1">// grab any additional nodes for the body</span>
</span><span class='line'>                <span class="nx">bodyNodes</span><span class="o">:</span> <span class="nx">componentInfo</span><span class="p">.</span><span class="nx">templateNodes</span><span class="p">.</span><span class="nx">slice</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
</span><span class='line'>            <span class="p">};</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>3- There is a new <code>$componentTemplateNodes</code> context variable that contains the nodes directly. In normal cases, this will allow you to avoid exposing DOM nodes in your view model and bind in the template directly.</p>

<p>For example, a component template might simply want to add some wrapping markup like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;my-component&quot;</span> <span class="na">data-bind=</span><span class="s">&quot;template: { nodes: $componentTemplateNodes, data: data }&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>You could then add the component to your page:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;my-component</span> <span class="na">params=</span><span class="s">&quot;{ data: item }&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;h1&gt;</span>My Data<span class="nt">&lt;/h1&gt;</span>
</span><span class='line'>    <span class="nt">&lt;p&gt;</span>Body one<span class="nt">&lt;/p&gt;</span>
</span><span class='line'>    <span class="nt">&lt;p&gt;</span>Body two<span class="nt">&lt;/p&gt;</span>
</span><span class='line'><span class="nt">&lt;/my-component&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>If would still be possible to manipulate (<code>slice</code>) <code>$componentTemplateNodes</code> directly in the binding, depending on the complexity of the markup/scenario.</p>

<h3><code>$component</code> context variable</h3>

<p>Sometimes inside of a component&rsquo;s template, when looping through nested structures, you may want to bind up to the root of the component. Rather than trying to manage <code>$parents[x]</code>, you can now use <code>$component</code> to get the nearest components root. This is a similar concept to <code>$root</code> for the entire application, but is specific to a component.</p>

<h2>Other Enhancements</h2>

<p>A few other enhancements that I think are interesting:</p>

<h3>awake/sleep notifications from pure and deferred computeds</h3>

<p>You can now subscribe to notifications from a <code>pureComputed</code> for when it wakes up and for when it goes to sleep (when nothing depends on it). Additionally, a deferred computed now notifies when it wakes up as well. The subscriptions would look like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="k">this</span><span class="p">.</span><span class="nx">fullName</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">pureComputed</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">firstName</span><span class="p">()</span> <span class="o">+</span> <span class="s2">&quot; &quot;</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">lastName</span><span class="p">();</span>
</span><span class='line'><span class="p">},</span> <span class="k">this</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="k">this</span><span class="p">.</span><span class="nx">fullName</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">value</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;fullName is awake with a value: &quot;</span> <span class="o">+</span> <span class="nx">value</span><span class="p">);</span>
</span><span class='line'><span class="p">},</span> <span class="k">this</span><span class="p">,</span> <span class="s2">&quot;awake&quot;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="k">this</span><span class="p">.</span><span class="nx">fullName</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;fullName is sleeping&quot;</span> <span class="o">+</span> <span class="nx">value</span><span class="p">);</span>
</span><span class='line'><span class="p">},</span> <span class="k">this</span><span class="p">,</span> <span class="s2">&quot;sleep&quot;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="k">this</span><span class="p">.</span><span class="nx">fullPhoneNumber</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">computed</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="k">this</span><span class="p">.</span><span class="nx">areaCode</span><span class="p">()</span> <span class="o">+</span> <span class="s2">&quot; &quot;</span> <span class="k">this</span><span class="p">.</span><span class="nx">phoneNumber</span><span class="p">();</span>
</span><span class='line'><span class="p">},</span> <span class="k">this</span><span class="p">,</span> <span class="p">{</span> <span class="nx">deferEvaluate</span><span class="o">:</span> <span class="kc">true</span> <span class="p">});</span>
</span><span class='line'>
</span><span class='line'><span class="k">this</span><span class="p">.</span><span class="nx">fullPhoneNumber</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">value</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;fullPhoneNumber is awake with a value: &quot;</span> <span class="o">+</span> <span class="nx">value</span><span class="p">);</span>
</span><span class='line'><span class="p">},</span> <span class="k">this</span><span class="p">,</span> <span class="s2">&quot;sleep&quot;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<h3>Exposing a few additional functions to the release build</h3>

<ul>
<li><code>ko.ignoreDependencies(callback, callbackTarget, callbackArgs)</code> - executes a function and ignores any dependencies that may be encountered. This can be useful sometimes in a computed observable or in a custom binding when you want to execute code, but not trigger updates when any dependencies from that code change. You would use it like:</li>
</ul>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">ignoreDependencies</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">myAfterUpdateHandler</span><span class="p">,</span> <span class="k">this</span><span class="p">,</span> <span class="p">[</span><span class="kc">true</span><span class="p">]);</span>
</span></code></pre></td></tr></table></div></figure>


<ul>
<li><code>ko.utils.setTextContent(element, textContent)</code> handles cross-browser setting the text of a node and handles virtual elements</li>
</ul>


<h2>Fixes</h2>

<p>3.3 also includes a number of nice fixes and performance improvements listed <a href="https://github.com/knockout/knockout/releases/tag/v3.3.0">here</a>. This includes making the <code>css</code> binding work properly with SVG elements, which has been a long-standing issue.</p>

<p>Please check out Knockout 3.3.0 today! It is available from <a href="https://github.com/knockout/knockout/releases/tag/v3.3.0">GitHub</a>, the <a href="http://knockoutjs.com">main site</a>, Bower (<code>bower install knockout</code>), and NPM (<a href="https://www.npmjs.com/package/knockout">knockout</a>).</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Cleaning up after yourself in Knockout.js]]></title>
    <link href="http://www.knockmeout.net/2014/10/knockout-cleaning-up.html"/>
    <updated>2014-10-03T10:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2014/10/knockout-cleaning-up</id>
    <content type="html"><![CDATA[<p>Last summer, I had the opportunity to speak at <a href="http://modernwebconf.com/">ModernWebConf</a>, <a href="https://www.thatconference.com/">ThatConference</a>, and <a href="http://www.devlink.net/">devLink</a> on the topic of browser memory leaks. The talk was focused on the tools and techniques that you can use for memory leak testing and situations in JavaScript that comonly cause these leaks. Slides for the presentation can be found <a href="http://presentboldly.com/rniemeyer/browser-memory-leak-testing/">here</a>.</p>

<p>With the rise of single-page applications and increased complexity (and amount) of JavaScript on the client-side, memory leaks are a common occurrence. <a href="http://knockoutjs.com">Knockout.js</a> applications are not immune to these problems. In this post, I will review some scenarios that often contribute to memory leaks and discuss the APIs in Knockout that can be used to prevent and resolve these issues.</p>

<h2>The main source of leaks in KO</h2>

<p>Memory leaks in KO are typically caused by long-living objects that hold references to things that you expect to be cleaned up. Here are some examples of where this can occur and how to clean up the offending references:</p>

<h3>1. Subscriptions to observables that live longer than the subscriber</h3>

<p>Suppose that you have an object representing your overall application stored in a variable called <code>myApp</code> and the current view as <code>myViewModel</code>. If the view needs to react to the app&rsquo;s language observable changing, then you might make a call like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">myApp</span><span class="p">.</span><span class="nx">currentLanguage</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="nx">myCurrentView</span><span class="p">.</span><span class="nx">languageHandler</span><span class="p">,</span> <span class="nx">myCurrentView</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>What this technically does is goes to <code>myApp.currentLanguage</code> and adds to its list of callbacks with a bound function (<code>languageHandler</code>) that references <code>myCurrentView</code>. Whenever <code>myApp.currentLanguage</code> changes, it notifies everyone by executing each registered callback.</p>

<p>This means that if <code>myApp</code> lives for the lifetime of your application, it will keep <code>myCurrentView</code> around as well, even if you are no longer using it. The solution, in this case, is that we need to keep a reference to the subscription and call <code>dispose</code> on it. This will remove the reference from the observable to the subscriber.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">myCurrentView</span><span class="p">.</span><span class="nx">languageSubscription</span> <span class="o">=</span> <span class="nx">myApp</span><span class="p">.</span><span class="nx">currentLanguage</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="nx">myCurrentView</span><span class="p">.</span><span class="nx">languageHandler</span><span class="p">,</span> <span class="nx">myCurrentView</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// somewhere later in the code, when you are disposing of myCurrentView</span>
</span><span class='line'><span class="nx">myCurrentView</span><span class="p">.</span><span class="nx">languageSubscription</span><span class="p">.</span><span class="nx">dispose</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<h3>2. Computeds that reference long-living observables</h3>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">myCurrentView</span><span class="p">.</span><span class="nx">userStatusText</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">computed</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="nx">myApp</span><span class="p">.</span><span class="nx">currentUser</span><span class="p">()</span> <span class="o">+</span> <span class="s2">&quot; (&quot;</span> <span class="o">+</span> <span class="nx">myCurrentView</span><span class="p">.</span><span class="nx">userStatus</span> <span class="o">+</span> <span class="s2">&quot;)&quot;</span><span class="p">;</span>
</span><span class='line'><span class="p">},</span> <span class="nx">myCurrentView</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this case, the <code>userStatusText</code> computed references <code>myApp.currentUser()</code>. As in the subscription example, this will add to the list of callbacks that <code>myApp.currentUser</code> needs to call when it changes, as the <code>userStatusText</code> computed will need to be updated.</p>

<p>There are a couple of ways to solve this scenario:</p>

<ul>
<li>we can use the <code>dispose</code> method of a computed, like we did with a manual subscription.</li>
</ul>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="c1">// in disposal code</span>
</span><span class='line'><span class="nx">myCurrentView</span><span class="p">.</span><span class="nx">userStatusText</span><span class="p">.</span><span class="nx">dispose</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<ul>
<li>in KO 3.2, a specialized computed called a <code>ko.pureComputed</code> was added (docs <a href="http://knockoutjs.com/documentation/computed-pure.html">here</a>). A pure computed can be created by using <code>ko.pureComputed</code> rather than <code>ko.computed</code> or by pasing the <code>pure: true</code> option when creating a normal computed. A pure computed will automatically go to sleep (release all of its subscriptions) when nobody cares about its value (nobody is subscribed to it). Calling <code>dispose</code> on a pure computed would likely not be necessary for normal cases, where only the UI bindings are interested in the value. This would work well for our scenario where a temporary view needs to reference a long-living observable.</li>
</ul>


<h3>3. Event handlers attached to long-living objects</h3>

<p>In custom bindings, you may run into scenarios where you need to attach event handlers to something like the <code>document</code> or <code>window</code>. Perhaps the custom binding needs to react when the browser is resized. The target needs to keep track of its subscribers (like an observable), so this will create a reference from something long-living (<code>document</code>/<code>window</code> in this case) back to your object or element that is bound.</p>

<p>To solve this issue, inside of a custom binding, Knockout provides an API that lets you execute code when the element is removed by Knockout. Typically, this removal happens as part of templating or control-flow bindings (<code>if</code>, <code>ifnot</code>, <code>with</code>, <code>foreach</code>). The API is <code>ko.utils.domNodeDisposal.addDisposeCallback</code> and would be used like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">bindingHandlers</span><span class="p">.</span><span class="nx">myBinding</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">init</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">valueAccessor</span><span class="p">,</span> <span class="nx">allBindings</span><span class="p">,</span> <span class="nx">data</span><span class="p">,</span> <span class="nx">context</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">handler</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>            <span class="c1">// do something with element, valueAccessor, etc.</span>
</span><span class='line'>        <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>        <span class="nx">$</span><span class="p">(</span><span class="nb">window</span><span class="p">).</span><span class="nx">on</span><span class="p">(</span><span class="s2">&quot;resize&quot;</span><span class="p">,</span> <span class="nx">handler</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>        <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">domNodeDisposal</span><span class="p">.</span><span class="nx">addDisposeCallback</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>            <span class="nx">$</span><span class="p">(</span><span class="nb">window</span><span class="p">).</span><span class="nx">off</span><span class="p">(</span><span class="s2">&quot;resize&quot;</span><span class="p">,</span> <span class="nx">handler</span><span class="p">);</span>
</span><span class='line'>        <span class="p">});</span>
</span><span class='line'>    <span class="p">})</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>If you did not have easy access to the actual handler attached, then you might consider using <a href="http://api.jquery.com/on/#event-names">namespaced events</a> like <code>$(window).on("resize.myPlugin", handler)</code> and then remove the handler with <code>$(window).off("resize.myPlugin")</code>.</p>

<h3>4. Custom bindings that wrap third-party code</h3>

<p>The above issue is also commonly encountered when using custom bindings to wrap third-party plugins/widgets. The widget may not have been designed to work in an environment where it would need to be cleaned up (like a single-page app) or may require something like a <code>destroy</code> API to be called. When choosing to reference third-party code, it is worthwhile to ensure that the code provides an appropriate method to clean itself up.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">bindingHandlers</span><span class="p">.</span><span class="nx">myWidget</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">init</span><span class="o">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">valueAccessor</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">myWidget</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="nx">element</span><span class="p">).</span><span class="nx">someWidget</span><span class="p">({</span>
</span><span class='line'>            <span class="nx">value</span><span class="o">:</span> <span class="nx">valueAccessor</span><span class="p">()</span>
</span><span class='line'>        <span class="p">});</span>
</span><span class='line'>
</span><span class='line'>        <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">domNodeDisposal</span><span class="p">.</span><span class="nx">addDisposeCallback</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>            <span class="c1">// or whatever code is necessary to clean-up the widget</span>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="nx">myWidget</span> <span class="o">&amp;&amp;</span> <span class="k">typeof</span> <span class="nx">myWidget</span><span class="p">.</span><span class="nx">destroy</span> <span class="o">===</span> <span class="s2">&quot;function&quot;</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>                <span class="nx">myWidget</span><span class="p">.</span><span class="nx">destroy</span><span class="p">();</span>
</span><span class='line'>            <span class="p">}</span>
</span><span class='line'>        <span class="p">})</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Reviewing the tools/API for clean-up in Knockout</h2>

<ol>
<li><p><code>dispose</code> function. Can be called on a manual subscription or computed to remove any subscriptions to it.</p></li>
<li><p><code>ko.utils.domNodeDisposal.addDisposeCallback</code> - adds code to run when Knockout removes an element and is normally used in a custom binding.</p></li>
<li><p><code>ko.pureComputed</code> - this <a href="http://knockoutjs.com/documentation/computed-pure.html">new type of computed</a> added in KO 3.2, handles removing subscriptions itself when nobody is interested in its value.</p></li>
<li><p><code>disposeWhenNodeIsRemoved</code> option to a computed - in some cases, you may find it useful to create one or more computeds in the <code>init</code> function of a custom binding to have better control over how you handle changes to the various observables the binding references (vs. the <code>update</code> function firing for changes to all observables referenced. This technique can also allow you to more easily share data between the <code>init</code> function and code that runs when there are changes (which normally would be in the <code>update</code>function.</p></li>
</ol>


<p>For example:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">bindingHandlers</span><span class="p">.</span><span class="nx">myBinding</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">init</span><span class="o">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">valueAccessor</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">options</span> <span class="o">=</span> <span class="nx">valueAccessor</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>        <span class="nx">ko</span><span class="p">.</span><span class="nx">computed</span><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">value</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">unwrap</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">value</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>            <span class="c1">// do something with value</span>
</span><span class='line'>        <span class="p">},</span> <span class="kc">null</span><span class="p">,</span> <span class="p">{</span> <span class="nx">disposeWhenNodeIsRemoved</span><span class="o">:</span> <span class="nx">element</span> <span class="p">});</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>        <span class="nx">ko</span><span class="p">.</span><span class="nx">computed</span><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">height</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">unwrap</span><span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">height</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>            <span class="c1">// do something with height</span>
</span><span class='line'>        <span class="p">},</span> <span class="kc">null</span><span class="p">,</span> <span class="p">{</span> <span class="nx">disposeWhenNodeIsRemoved</span><span class="o">:</span> <span class="nx">element</span> <span class="p">});</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note that the example is passing in the <code>disposeWhenNodeIsRemoved</code> option to indicate that these computeds should automatically be disposed when the element is removed. This is a convenient alternative to saving a reference to these computeds and setting up a handler to call <code>dispose</code> by using <code>ko.utils.domNodeDisposal.addDisposeCallback</code>.</p>

<h2>Keeping track of things to dispose</h2>

<p>One pattern that I have used in applications when I know that a particular module will often be created and torn down is to do these two things:</p>

<p>1- When my module is being disposed, loop through all top-level properties and call <code>dispose</code> on anything that can be disposed. Truly it would only be necessary to dispose items that have subscribed to long-living observables (that live outside of the object itself), but easy enough to dispose of anything at the top-level when some have created &ldquo;external&rdquo; subscriptions.</p>

<p>2- Create a <code>disposables</code> array of subscriptions to loop over when my module is being disposed, rather than assigning every subscription to a top-level property of the module.</p>

<p>A snippet of a module like this might look like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">var</span> <span class="nx">MyModule</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">disposables</span> <span class="o">=</span> <span class="p">[];</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">userStatus</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">userStatusText</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">computed</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">getUserStatusText</span><span class="p">,</span> <span class="k">this</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">disposables</span><span class="p">.</span><span class="nx">push</span><span class="p">(</span><span class="nx">myApp</span><span class="p">.</span><span class="nx">currentLanguage</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">handleLanguageChange</span><span class="p">,</span> <span class="k">this</span><span class="p">));</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">extend</span><span class="p">(</span><span class="nx">MyModule</span><span class="p">.</span><span class="nx">prototype</span><span class="p">,</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">getUserStatusText</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="nx">myApp</span><span class="p">.</span><span class="nx">currentUser</span><span class="p">()</span> <span class="o">+</span> <span class="s2">&quot; (&quot;</span> <span class="o">+</span> <span class="k">this</span><span class="p">.</span><span class="nx">userStatus</span> <span class="o">+</span> <span class="s2">&quot;)&quot;</span><span class="p">;</span>
</span><span class='line'>    <span class="p">},</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">handleLanguageChange</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">newLanguage</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="c1">// do something with newLanguage</span>
</span><span class='line'>    <span class="p">},</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">dispose</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>        <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">arrayForEach</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">disposables</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">disposeOne</span><span class="p">);</span>
</span><span class='line'>        <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">objectForEach</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="k">this</span><span class="p">.</span><span class="nx">disposeOne</span><span class="p">);</span>
</span><span class='line'>    <span class="p">},</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// little helper that handles being given a value or prop + value</span>
</span><span class='line'>    <span class="nx">disposeOne</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">propOrValue</span><span class="p">,</span> <span class="nx">value</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">disposable</span> <span class="o">=</span> <span class="nx">value</span> <span class="o">||</span> <span class="nx">propOrValue</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="nx">disposable</span> <span class="o">&amp;&amp;</span> <span class="k">typeof</span> <span class="nx">disposable</span><span class="p">.</span><span class="nx">dispose</span> <span class="o">===</span> <span class="s2">&quot;function&quot;</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="nx">disposable</span><span class="p">.</span><span class="nx">dispose</span><span class="p">();</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Conclusion</h2>

<p>Memory leaks are not uncommon to find in long-running Knockout.js applications. Being mindful of how and when you subscribe to long-living observables from objects that are potentially short-lived can help alleviate these leaks. The APIs listed in this post will help ensure that references from subscriptions are properly removed and your applications are free of memory leaks.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Knockout.js 3.2 Preview : Components]]></title>
    <link href="http://www.knockmeout.net/2014/06/knockout-3-2-preview-components.html"/>
    <updated>2014-06-12T10:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2014/06/knockout-3-2-preview-components</id>
    <content type="html"><![CDATA[<p><a href="http://knockoutjs.com">Knockout</a> 3.2 will include some exciting new functionality out-of-the-box to do modular development through creating <em>components</em>. From Knockout&rsquo;s point of view, a component allows you to asynchronously combine a template and data (a view model) for rendering on the page. Components in Knockout are heavily inspired by <a href="http://webcomponents.org/">web components</a>, but are designed to work with Knockout and all of the browsers that it supports (all the way back to IE6).</p>

<p>Components allow you to combine independent modules together to create an application. For example, a view could look like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;myapp-nav&gt;&lt;/myapp-nav&gt;</span>
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;myapp-grid</span> <span class="na">params=</span><span class="s">&quot;data: items, paging: true, sorting: true&quot;</span><span class="nt">&gt;&lt;/myapp-grid&gt;</span>
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;myapp-footer&gt;&lt;/myapp-footer&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>The idea of doing modular development with Knockout is certainly not a new one. Libraries like <a href="http://durandaljs.com/">Durandal</a> with its <code>compose</code> binding and the <code>module</code> binding from my <a href="https://github.com/rniemeyer/knockout-amd-helpers">knockout-amd-helpers</a> have been doing this same type of thing for a while and have helped prove that it is a successful way to build and organize Knockout functionality. Both of these libraries have focused on <a href="https://github.com/amdjs/amdjs-api">AMD</a> (Asynchronous Module Definition) to provide the loading and organization of modules.</p>

<p>Knockout&rsquo;s goal is to make this type of development possible as part of the core <strong>without being tied to any third-party library or framework</strong>. Developers will be able to componentize their code, by default, rather than only after pulling in various plugins. However, the functionality is flexible enough to support different or more advanced ideas/opinions through extensibility points. When KO 3.2 is released, developers should seriously consider factoring components heavily into their application architecture (unless already successfully using one of the other plugins mentioned).</p>

<h2>How does it work?</h2>

<p>By default, in version 3.2, Knockout will include:</p>

<ol>
<li>a system for registering/defining components</li>
<li>custom elements as an easy and clean way to render/consume a component</li>
<li>a <code>component</code> binding as an alternative to custom elements that supports dynamically binding against components</li>
<li>extensibility points for modifying or augmenting this functionality to suit individual needs/opinions</li>
</ol>


<p>Let&rsquo;s take a look at how this functionality is used:</p>

<h3>Registering a component</h3>

<p>The default component loader for Knockout looks for components that were registered via a <code>ko.components.register</code> API. This registration expects a component name along with configuration that describes how to determine the <code>viewModel</code> and the <code>template</code>. Here is a simple example of registering a component:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">components</span><span class="p">.</span><span class="nx">register</span><span class="p">(</span><span class="s2">&quot;simple-name&quot;</span><span class="p">,</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">viewModel</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="p">(</span><span class="nx">data</span> <span class="o">&amp;&amp;</span> <span class="nx">data</span><span class="p">.</span><span class="nx">name</span><span class="p">)</span> <span class="o">||</span> <span class="s2">&quot;none&quot;</span><span class="p">;</span>
</span><span class='line'>    <span class="p">},</span>
</span><span class='line'>    <span class="nx">template</span><span class="o">:</span> <span class="s2">&quot;&lt;div data-bind=\&quot;text: name\&quot;&gt;&lt;/div&gt;&quot;</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<h4>The viewModel key</h4>

<ul>
<li>can be a function. If so, then it is used as a constructor (called with <code>new</code>).</li>
<li>can pass an <code>instance</code> property to use an object directly.</li>
<li>can pass a <code>createViewModel</code> property to call a function that can act as a factory and return an object to use as the view model (has access to the DOM element as well for special cases).</li>
<li>can pass a <code>require</code> key to call the <code>require</code> function with the supplied value. This will work with whatever provides a global require function (like <code>require.js</code>). The result will again go through this resolution process.</li>
</ul>


<p>Additionally, if the resulting object supplies a <code>dispose</code> function, then KO will call it whenever tearing down the component. Disposal could happen if that part of the DOM is being removed/re-rendered (by a parent template or control-flow binding) or if the component binding has its name changed dynamically.</p>

<h4>The template key</h4>

<ul>
<li>can be a string of markup</li>
<li>can be an array of DOM nodes</li>
<li>can be an <code>element</code> property that supplies the id of an element to use as the template</li>
<li>can be an <code>element</code> property that supplies an element directly</li>
<li>can be a <code>require</code> property that like for <code>viewModel</code> will call <code>require</code> directly with the supplied value.</li>
</ul>


<p>A component could choose to only specify a <code>template</code>, in cases where a view model is not necessary. The supplied params will be used as the data context in that case.</p>

<h3>The component binding</h3>

<p>With this functionality, Knockout will provide a <code>component</code> binding as an option for rendering a component on the page (with the other option being a custom element). The component binding syntax is fairly simple.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">data-bind=</span><span class="s">&quot;component: &#39;my-component&#39;&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;div</span> <span class="na">data-bind=</span><span class="s">&quot;component: { name: &#39;my-component&#39;, params: { name: &#39;ryan&#39; } }&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span><span class='line'>
</span><span class='line'><span class="c">&lt;!-- ko component: &#39;my-component&#39; --&gt;&lt;!-- /ko --&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>The component binding supports binding against an observable and/or observables for the <code>name</code> and <code>params</code> options. This allows for handling dynamic scenarios like rendering different components to the main content area depending on the state of the application.</p>

<h3>Custom Elements</h3>

<p>While the component binding is an easy way to display a component and will be necessary when dynamically binding to components (dynamically changing the component name), custom elements will likely be the &ldquo;normal&rdquo; way for consuming a component.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;my-component</span> <span class="na">params=</span><span class="s">&quot;name: userName, type: userType&quot;</span><span class="nt">&gt;&lt;/my-component&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<h4>Matching a custom element to a component</h4>

<p>Knockout automatically does all of the necessary setup to make custom elements work (even in older browsers), when <code>ko.registerComponent</code> is called. By default, the element name will exactly match the component name. For more flexibility though, Knockout provides an extensibility point (<code>ko.components.getComponentNameForNode</code>) that is given a node and expected to return the name of the component to use for it.</p>

<h4>How params are passed to the component</h4>

<p>The params are provided to initialize the component, like in the component binding, but with a couple of differences:</p>

<ul>
<li>If a parameter creates dependencies itself (accesses the value of an observable or computed), then the component will receive a computed that returns the value. This helps to ensure that the entire component does not need to be rebuilt on parameter changes. The component itself can control how it accesses and handles any dependencies. For example, in this case:</li>
</ul>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;my-component</span> <span class="na">params=</span><span class="s">&quot;name: first() + &#39; &#39; + last()&quot;</span><span class="nt">&gt;&lt;/my-component&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>The component will receive a params object that contains a <code>name</code> property that is supplied as a computed in this case. The component can then determine how to best react to the <code>name</code> changing rather than simply receiving the result of the expression and forcing the entire component to re-load on changes to either of the observables.</p>

<ul>
<li>The <code>params</code> object supplied when using the custom element syntax will also include a <code>$raw</code> property (unless the <code>params</code> happens to supply a property with that same name) which gives access to computeds that return the original value (rather than the unwrapped value). For example:</li>
</ul>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;my-component</span> <span class="na">params=</span><span class="s">&quot;value: selectedItem().value&quot;</span><span class="nt">&gt;&lt;/my-component&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this case, since <code>selectedItem</code> is accessed, the param is supplied as a computed. When the computed is accessed, the unwrapped <code>value</code> is returned to avoid having to double-unwrap a param to get its value. However, you may want access to the <code>value</code> observable in this case, rather than its unwrapped value. In the component, this could be achieved by accessing  <code>params.$raw.value()</code>. The default functionality is slanted towards ease of use (not having to unwrap a param twice) while providing <code>$raw</code> for advanced cases.</p>

<h3>Custom loaders</h3>

<p>Knockout let&rsquo;s you add multiple &ldquo;component loaders&rdquo; that can choose how to understand what a component is and how to load/generate the DOM elements and data.</p>

<p>A loader provides two functions: <code>getConfig</code> and <code>loadComponent</code>. Both receive a callback argument that is called when the function is ready to proceed (to support asynchronous operations).</p>

<ul>
<li><code>getConfig</code> can asynchronously return a configuration object to describe the component given a component name.</li>
<li><code>loadComponent</code> will take the configuration and resolve it to an array of DOM nodes to use as the template and a <code>createViewModel</code> function that will directly return the view model instance.</li>
</ul>


<h4>The default loader</h4>

<p>To understand creating a custom component loader, it is useful to first understand the functionality provided by the default loader:</p>

<p>The default <code>getConfig</code> function does the following:</p>

<ul>
<li>this function simply looks up the component name from the registered components and calls the callback with the defined config (or null, if it is not defined).</li>
</ul>


<p>The default <code>loadComponent</code> function does the following:</p>

<ul>
<li>tries to resolve both the <code>viewModel</code> and <code>template</code> portions of the config based on the various ways that it can be configured.</li>
<li>if using <code>require</code> will call <code>require</code> with the configured module name and will take the result and go through the resolution process again.</li>
<li>when it has resolved the <code>viewModel</code> and <code>template</code> it will return an array of DOM nodes to use as the template and a <code>createViewModel</code> function that will return a view model based on however the <code>viewModel</code> property was configured.</li>
</ul>


<h4>A sample custom loader</h4>

<p>Let&rsquo;s say that we want to create a <code>widget</code> directory where we place templates and view model definitions that we want to require via AMD. Ideally, we want to just be able to do:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">data-bind=</span><span class="s">&quot;component: &#39;widget-one&#39;&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this case, we could create a pretty simple loader to handle this functionality:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="c1">//add a loader to the end of the list of loaders (one by default)</span>
</span><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">components</span><span class="p">.</span><span class="nx">loaders</span><span class="p">.</span><span class="nx">push</span><span class="p">({</span>
</span><span class='line'>    <span class="nx">getConfig</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">name</span><span class="p">,</span> <span class="nx">callback</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">widgetName</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="c1">//see if this is a widget</span>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="nx">name</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="s2">&quot;widget-&quot;</span><span class="p">)</span> <span class="o">&gt;</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="nx">widgetName</span> <span class="o">=</span> <span class="nx">name</span><span class="p">.</span><span class="nx">substr</span><span class="p">(</span><span class="mi">7</span><span class="p">).</span><span class="nx">toLowerCase</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>            <span class="c1">//provide configuration for how to load the template/widget</span>
</span><span class='line'>            <span class="nx">callback</span><span class="p">({</span>
</span><span class='line'>                <span class="nx">viewModel</span><span class="o">:</span> <span class="p">{</span>
</span><span class='line'>                    <span class="c1">//require the widget from the widget directory with just the name</span>
</span><span class='line'>                    <span class="nx">require</span><span class="o">:</span> <span class="s2">&quot;widgets/&quot;</span> <span class="o">+</span> <span class="nx">widgetName</span>
</span><span class='line'>                <span class="p">},</span>
</span><span class='line'>                <span class="nx">template</span><span class="o">:</span> <span class="p">{</span>
</span><span class='line'>                    <span class="c1">//use the text plugin to load the template from the same directory</span>
</span><span class='line'>                    <span class="nx">require</span><span class="o">:</span> <span class="s2">&quot;text!widgets/&quot;</span> <span class="o">+</span> <span class="nx">widgetName</span> <span class="o">+</span> <span class="s2">&quot;.tmpl.html&quot;</span>
</span><span class='line'>                <span class="p">}</span>
</span><span class='line'>            <span class="p">});</span>
</span><span class='line'>        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
</span><span class='line'>            <span class="c1">//tell KO that we don&#39;t know and it can move on to additional loaders</span>
</span><span class='line'>            <span class="nx">callback</span><span class="p">(</span><span class="kc">null</span><span class="p">);</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">},</span>
</span><span class='line'>    <span class="c1">//use the default loaders functionality for loading</span>
</span><span class='line'>    <span class="nx">loadComponent</span><span class="o">:</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">components</span><span class="p">.</span><span class="nx">defaultLoader</span><span class="p">.</span><span class="nx">loadComponent</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this custom loader, we just dynamically build the configuration that we want, so we don&rsquo;t necessarily have to register every &ldquo;widget&rdquo; as its own component, although registering will properly setup custom elements to work with the component. Loading the <code>widget-one</code> component would load a <code>one.js</code> view model and <code>one.tmpl.html</code> template from a <code>widgets</code> directory in this sample loader. If the component is not a &ldquo;widget&rdquo;, then the callback is called with <code>null</code>, so other loaders can try to fulfill the request.</p>

<h2>Summary</h2>

<p>Components are a major addition to Knockout&rsquo;s functionality. Many developers have found ways to do this type of development in their applications using plugins, but it will be great to have standard support in the core and the possibility for extensibility on top of it. <a href="http://blog.stevensanderson.com/">Steve Sanderson</a> recently did a great <a href="http://blog.stevensanderson.com/2014/06/11/architecting-large-single-page-applications-with-knockout-js/">presentation</a> at NDC Oslo 2014 that highlighted the use of components in Knockout. Check it out <a href="http://vimeo.com/97519516">here</a>.</p>

<p>Knockout 3.2 is well underway and should be ready for release this summer.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How does dependency detection work in Knockout.js?]]></title>
    <link href="http://www.knockmeout.net/2014/05/knockout-dependency-detection.html"/>
    <updated>2014-05-09T10:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2014/05/knockout-dependency-detection</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://www.knockmeout.net/images/posts/foggy.jpg"></p>

<p>I received a question over email asking about how <a href="http://knockoutjs.com">Knockout</a>&rsquo;s dependency detection actually works and thought that I would share an answer in this post. I know that I feel a bit uncomfortable whenever a library that I am using does something that I don&rsquo;t fully understand, so I hope that I can help ensure that this part of Knockout is not misunderstood or considered &ldquo;magic&rdquo;.</p>

<h2>A few questions to answer:</h2>

<ol>
<li><em>For a computed observable, how does KO know which dependencies should trigger a re-evaluation of the computed on changes?</em></li>
<li><em>How is it possible for the dependencies to change each time that a computed is evaluated?</em></li>
<li><em>For bindings, how are dependencies tracked?</em></li>
</ol>


<h3>Determining dependencies for a computed</h3>

<p><em>TLDR: Knockout has a middle-man object that is signalled on all reads to computed/observables and tells the current computed being evaluated that it might want to hook up a subscription to this dependency.</em></p>

<ul>
<li><p>Internally Knockout maintains a single object (<code>ko.dependencyDetection</code>) that acts as the mediator between parties interested in subscribing to dependencies and dependencies that are being accessed. Let&rsquo;s call this object the <em>dependency tracker</em>.</p></li>
<li><p>In a block of code that wants to track dependencies (like in a computed&rsquo;s evaluation), a call is made to the dependency tracker to signal that someone is currently interested in dependencies. As an example, let&rsquo;s simulate what a computed would call:</p></li>
</ul>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="c1">//a few observables to work with</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">test</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">(</span><span class="s2">&quot;one&quot;</span><span class="p">),</span>
</span><span class='line'>    <span class="nx">test2</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">(</span><span class="s2">&quot;two&quot;</span><span class="p">),</span>
</span><span class='line'>    <span class="nx">test3</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">(</span><span class="s2">&quot;three&quot;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//a computed internally ask to start tracking dependencies and receive a notification when anything observable is accessed</span>
</span><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">dependencyDetection</span><span class="p">.</span><span class="nx">begin</span><span class="p">({</span>
</span><span class='line'>    <span class="nx">callback</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">subscribable</span><span class="p">,</span> <span class="nx">internalId</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;original context: &quot;</span> <span class="o">+</span> <span class="nx">internalId</span> <span class="o">+</span> <span class="s2">&quot; was accessed&quot;</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<ul>
<li>Any read to an observable or computed triggers a call to the dependency tracker. A unique id is then assigned to the observable/computed (if it doesn&rsquo;t have one) and the callback from the currently interested party is passed the dependency and its id.</li>
</ul>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="c1">//access an observable</span>
</span><span class='line'><span class="nx">test</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//output:</span>
</span><span class='line'><span class="c1">//original context: 1 was accessed</span>
</span></code></pre></td></tr></table></div></figure>


<ul>
<li>The dependency tracker maintains a stack of interested parties. Whenever a call is made to start tracking, a new context is pushed onto the stack, which allows for computeds to be created inside of computeds. Any reads to dependencies will go to the current computed being evaluated.</li>
</ul>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="c1">//start another dependency detection inside of the current one</span>
</span><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">dependencyDetection</span><span class="p">.</span><span class="nx">begin</span><span class="p">({</span>
</span><span class='line'>    <span class="nx">callback</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">subscribable</span><span class="p">,</span> <span class="nx">internalId</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;    child context: &quot;</span> <span class="o">+</span> <span class="nx">internalId</span> <span class="o">+</span> <span class="s2">&quot; was accessed&quot;</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">});</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//inside of child context again access test and also test2</span>
</span><span class='line'><span class="nx">test</span><span class="p">();</span>
</span><span class='line'><span class="nx">test2</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//output</span>
</span><span class='line'><span class="c1">//child context: 1 was accessed</span>
</span><span class='line'><span class="c1">//child context: 2 was accessed</span>
</span></code></pre></td></tr></table></div></figure>


<ul>
<li>When a computed is done evaluating, it signals the dependency tracker that is is complete and the tracker pops the context off of its stack and restores the previous context.</li>
</ul>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="c1">//end child context</span>
</span><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">dependencyDetection</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//dependencies are back to the original (outer) context</span>
</span><span class='line'><span class="nx">test3</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//output</span>
</span><span class='line'><span class="c1">//original context: 3 was accessed</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//end original context</span>
</span><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">dependencyDetection</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<ul>
<li>When an observable/computed dependency is updated, then the subscription is triggered and the computed is re-evaluated.</li>
</ul>


<p>Here is a jsFiddle version of this code: <a href="http://jsfiddle.net/rniemeyer/F9CrA/">http://jsfiddle.net/rniemeyer/F9CrA/</a>. <em>Note that <code>ko.dependencyDetection</code> is only exposed in the debug build. In the release build it is renamed as part of the minification process.</em></p>

<p>So, Knockout doesn&rsquo;t need to parse the function as a string to determine dependencies or do any &ldquo;tricks&rdquo; to make this happen. The key is that all reads to observable/computeds go through logic that is able to signal the dependency tracker who can let the computed know to subscribe to the observable/computed.</p>

<h3>How can dependencies change when a computed is re-evaluated?</h3>

<p>Each time that a computed is evaluated, Knockout determines the dependencies again. For any new dependencies, a subscription is added. For any dependencies that are no longer necessary, the subscriptions are disposed. Generally, this is efficient and beneficial as long as you are only branching in computed code based either data that is observable or doesn&rsquo;t change. For example:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'> <span class="k">this</span><span class="p">.</span><span class="nx">errors</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">computed</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>     <span class="kd">var</span> <span class="nx">result</span> <span class="o">=</span> <span class="p">[];</span>
</span><span class='line'>
</span><span class='line'>     <span class="k">if</span> <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">showErrors</span><span class="p">())</span> <span class="p">{</span>
</span><span class='line'>         <span class="nx">result</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">arrayFilter</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">history</span><span class="p">(),</span> <span class="kd">function</span><span class="p">(</span><span class="nx">item</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="k">return</span> <span class="nx">item</span><span class="p">.</span><span class="nx">type</span><span class="p">()</span> <span class="o">===</span> <span class="s2">&quot;error&quot;</span><span class="p">;</span>
</span><span class='line'>         <span class="p">});</span>
</span><span class='line'>     <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>     <span class="k">return</span> <span class="nx">result</span><span class="p">;</span>
</span><span class='line'> <span class="p">},</span> <span class="k">this</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this example, when <code>showErrors</code> is false, this computed will only have a single dependency, <code>showErrors</code>. There is no need to depend on the history or trigger re-evaluation when the items change, as it will not influence the result of the function. If <code>showErrors</code> does become truthy, then the computed will depend on <code>showErrors</code>, the <code>history</code> observableArray, and the <code>type</code> of each item.</p>

<h3>What about bindings?  How do they track dependencies?</h3>

<p>Bindings in Knockout actually use computeds as a tool to facilitate their own dependency tracking. Each binding is evaluated within a computed observable for this purpose. Observables/computeds accessed in the <code>update</code> function of a binding become dependencies. Observables that are accessed within a binding string (like <code>items</code> in  <code>data-bind="if: items().length"</code>) are read when the <code>valueAccessor()</code> function is called (or via <code>allBindingsAccessor</code> - <code>allBindingsAccessor.get("if")</code> in this case). I think that it is useful to think of a binding&rsquo;s <code>update</code> function just like a normal computed observable where access to any dependencies will trigger the binding to run again.</p>

<p><em>Note: Prior to KO 3.0, all bindings on a single element were wrapped inside of a single computed. The parsing and evaluation of the binding string was also included in this computed. So, calling <code>valueAccessor()</code> would give the result of the expression rather than actually run the code. Dependency detection worked the same way, all bindings on an element were triggered together and it was not possible to isolate dependencies made in the binding string. See this <a href="http://www.knockmeout.net/2012/06/knockoutjs-performance-gotcha-3-all-bindings.html">post</a> for more details.</em></p>

<h3>Something new in KO 3.2 - ko.pureComputed</h3>

<p>There is an <a href="https://github.com/knockout/knockout/pull/1359">interesting feature</a> coming in KO 3.2 related to computed dependency tracking. <a href="https://github.com/mbest">Michael Best</a> implemented an option that allows a computed to not maintain any dependencies when it has no subscribers to it. This is not appropriate for all cases, but in situations where the computed returns a calculated value with no side-effects, if there is nothing depending on that calculated value, then the computed can go to &ldquo;sleep&rdquo; and not maintain subscriptions or be re-evaluated when any of the dependencies change. This will be useful for efficiency as well as potentially preventing memory leaks for a computed that was not disposed, but could be garbage collected if it was not subscribed to something observable that still exists. The option is called <code>pure</code> and a <code>ko.pureComputed</code> is provided as a shortcut.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Knockout.js 3.1 Released]]></title>
    <link href="http://www.knockmeout.net/2014/03/knockout-3-1-released.html"/>
    <updated>2014-03-04T10:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2014/03/knockout-3-1-is-out</id>
    <content type="html"><![CDATA[<p><a href="http://knockoutjs.com">Knockout</a> version 3.1 is available <a href="http://knockoutjs.com/downloads/knockout-3.1.0.js">now</a>! This was a nice incremental release with a few new features, some performance enhancements, and a number of bug fixes. For a complete list of changes, check out the <a href="https://github.com/knockout/knockout/releases/tag/v3.1.0">release notes</a>.</p>

<p>Here are some of my favorite changes:</p>

<h2>rateLimit extender</h2>

<p>There is a new <code>rateLimit</code> extender that handles throttle and debounce scenarios (<a href="http://knockoutjs.com/documentation/rateLimit-observable.html">docs here</a>). Some notes about this functionality:</p>

<ul>
<li>The <code>throttle</code> extender is deprecated. There are some slight differences between <code>rateLimit</code> and <code>throttle</code> described <a href="http://knockoutjs.com/documentation/rateLimit-observable.html#comparison-with-the-throttle-extender">here</a>.</li>
<li>The <code>rateLimit</code> extender returns the original value rather than a new computed like the <code>throttle</code> extender. This saves the overhead of an additional computed and better handles scenarios where the original value has already been extended in other ways (perhaps the original had an <code>isValid</code> sub-observable, which became inaccessible when the <code>throttle</code> extender created a new computed to stand in front of it.</li>
<li>The <code>rateLimit</code> extender works properly with observables, computeds, and observableArrays.</li>
<li>It supports a <code>method</code> option that by default is set to <code>notifyAtFixedRate</code> which corresponds to a throttling strategy. For a debounce scenario, the method can be set to <code>notifyWhenChangesStop</code>.</li>
</ul>


<p>For example, suppose that we define three observableArrays.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="c1">//when updated will notify subscribers immediately</span>
</span><span class='line'><span class="k">this</span><span class="p">.</span><span class="nx">normal</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observableArray</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//when updated will notify subscribers no more than every 500ms</span>
</span><span class='line'><span class="k">this</span><span class="p">.</span><span class="nx">throttled</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observableArray</span><span class="p">().</span><span class="nx">extend</span><span class="p">({</span>
</span><span class='line'>    <span class="nx">rateLimit</span><span class="o">:</span> <span class="mi">500</span>
</span><span class='line'><span class="p">});</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//when updated will notify subscribers when changes have stopped for 500 ms</span>
</span><span class='line'><span class="k">this</span><span class="p">.</span><span class="nx">debounced</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observableArray</span><span class="p">().</span><span class="nx">extend</span><span class="p">({</span>
</span><span class='line'>    <span class="nx">rateLimit</span><span class="o">:</span> <span class="p">{</span>
</span><span class='line'>        <span class="nx">timeout</span><span class="o">:</span> <span class="mi">500</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">method</span><span class="o">:</span> <span class="s2">&quot;notifyWhenChangesStop&quot;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>In the jsFiddle below, when you click the &ldquo;Start&rdquo; button, a new item will be pushed to each observableArray every 100ms for 100 iterations to demonstrate the behavior under each option.</p>

<iframe style="width: 100%; height: 400px" frameborder="0" seamless="seamless" src="http://jsfiddle.net/8m55g/embedded/result,js,html,css/light/"></iframe>


<p>The <code>rateLimit</code> extender will be a key tool going forward. I feel that after upgrading to 3.1 it would be worthwhile to review existing uses of the <code>throttle</code> extender in an app and update to <code>rateLimit</code>.</p>

<p><a href="http://jsfiddle.net/rniemeyer/8m55g/">Link to full sample on jsFiddle.net</a></p>

<h2>valueAllowUnset option</h2>

<p>There is now a <code>valueAllowUnset</code> option for scenarios where the <code>value</code> does not match what is contained in the <code>options</code>:</p>

<ul>
<li>With this option set to true, Knockout does not force the value to match an existing option.</li>
<li>The selection will be set to an empty option in the case of a mismatch, but the value is not overwritten.</li>
<li>This is very useful in scenarios where options are lazily loaded and there is an existing value.</li>
</ul>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>`<span class="nt">&lt;select</span> <span class="na">data-bind=</span><span class="s">&quot;value: selectedCategory, options: categories, valueAllowUnset: true&quot;</span><span class="nt">&gt;&lt;/select&gt;</span>`
</span></code></pre></td></tr></table></div></figure>


<pre><code>In this example, `selectedCategory` may be loaded with a value from the database and then when an editor is shown `categories` are loaded via an AJAX request. Without the `valueAllowUnset` option, Knockout would have recognized that the value of `selectedCategory` did not match an available option and tried to set it to the first option or undefined if there are no options. Without taking care to cache the original value, `selectedCategory` would have lost its value.
</code></pre>

<h2>ko.computedContext</h2>

<ul>
<li>You can now access the dependency count and whether it is the first evaluation within a computed. This could be useful in scenarios where you know that the function will never be called again (no dependencies) or to run special logic (or avoid logic) when it is the first evaluation. By using <code>ko.computedContext</code> while evaluating a computed, you have access to the <code>isInitial</code> and <code>getDependenciesCount</code> functions:</li>
</ul>


<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="k">this</span><span class="p">.</span><span class="nx">saveFlag</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">computed</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="kd">var</span> <span class="nx">cleanData</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">toJS</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">//don&#39;t save the data on the initial evaluation</span>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">ko</span><span class="p">.</span><span class="nx">computedContext</span><span class="p">.</span><span class="nx">isInitial</span><span class="p">())</span> <span class="p">{</span>
</span><span class='line'>      <span class="c1">//actually save the data</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">//recognize that we have no dependencies</span>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">ko</span><span class="p">.</span><span class="nx">computedContext</span><span class="p">.</span><span class="nx">getDependenciesCount</span><span class="p">())</span> <span class="p">{</span>
</span><span class='line'>       <span class="c1">//we might want to do some cleanup, as this computed will never be re-evaluated again</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">},</span> <span class="k">this</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<h2>array methods pass index</h2>

<p>The array utility methods now pass the array index as the second argument to the callbacks (in addition to the array item as the first argument).</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">arrayFilter</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">pages</span><span class="p">(),</span> <span class="kd">function</span><span class="p">(</span><span class="nx">page</span><span class="p">,</span> <span class="nx">index</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">//include any summary pages, besides the very first page</span>
</span><span class='line'>    <span class="k">return</span> <span class="nx">index</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="o">&amp;&amp;</span> <span class="nx">page</span><span class="p">.</span><span class="nx">type</span> <span class="o">===</span> <span class="s2">&quot;summary&quot;</span><span class="p">;</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Use <code>__proto__</code> for base types</h2>

<p>In browsers that support it, the base types (<code>ko.subscribable</code>, <code>ko.observable</code>, <code>ko.computed</code>, <code>ko.observableArray</code>) now use the <code>fn</code> objects as their prototype rather than copying functions from the <code>fn</code> objects to the result (since the result itself is a function, in older browsers it is not possible to set the prototype for it).</p>

<h2>Dependency tracking performance enhancement</h2>

<p>Dependencies are tracked in objects with unique ids, rather than in an array on each subscribable. This eliminates the need to loop internally to find an existing dependency, which has caused long-running script errors in older browsers when there were a large number of dependencies for a single observable/computed.</p>

<h2>Look for jQuery later</h2>

<p>Knockout looks for <code>jQuery</code> when <code>applyBindings</code> is called rather than when KO is loaded. This helps eliminate an issue with the order that KO and jQuery are loaded and in an AMD scenario you would not have to add <code>jQuery</code> as a dependency to KO in the shim configuration to have KO take advantage of <code>jQuery</code>.</p>

<p>There are many additional fixes listed in the release notes <a href="https://github.com/knockout/knockout/releases/tag/v3.1.0">here</a>. Please log any issues related to 3.1 to <a href="https://github.com/knockout/knockout/">GitHub</a>. <a href="https://github.com/mbest">Michael Best</a> again did a tremendous job with the bulk of the changes along with <a href="https://github.com/SteveSanderson">Steve Sanderson</a> as well as a number of community contributors.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Knockout.js 3.0 Highlights]]></title>
    <link href="http://www.knockmeout.net/2013/10/knockout-3-highlights.html"/>
    <updated>2013-10-25T10:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2013/10/knockout-3-is-out</id>
    <content type="html"><![CDATA[<p><a href="http://knockoutjs.com">Knockout</a> version 3.0 is now available. Here is a list of links with all of the info:</p>

<ul>
<li><a href="https://github.com/knockout/knockout/releases">Release on Github</a> - look at the 3.0 Beta and 3.0 RC releases to see a list of changes.</li>
<li><a href="http://knockoutjs.com/upgrade-notes/v3.0.0.html">Upgrade notes</a> - a list of potential breaking changes.</li>
<li><a href="http://blog.stevensanderson.com/2013/07/09/knockout-v2-3-0-released-v3-0-0-beta-available/">Blog post on 3.0 beta</a> - Steve Sanderson&rsquo;s post describing the features in 3.0 beta (bottom of post).</li>
<li><a href="http://blog.stevensanderson.com/2013/10/08/knockout-3-0-release-candidate-available/">Blog post on 3.0 RC</a> - another post by Steve on some additional features added in 3.0 RC.</li>
<li><a href="http://mbest.github.io/knockout.punches/">knockout.punches</a> - a great plugin by Michael Best that utilizes many of the new extensibility points added in KO 3.0. Michael was the driving force behind the major changes in 3.0 and continues to do amazing work on Knockout core.</li>
</ul>


<p>I put together a short screencast this morning with some highlights of the features and changes in 3.0:</p>

<iframe width="640" height="360" src="//www.youtube.com/embed/kep19WW7rp8" frameborder="0" allowfullscreen></iframe>


<p>The new extensibility points in KO 3.0 really open up a ton of interesting options for customizing the way that Knockout can be used. This is definitely an exciting and solid release!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[devLink 2013 - Knockout.js Tips and Tricks]]></title>
    <link href="http://www.knockmeout.net/2013/09/devlink-2013-ko-tips.html"/>
    <updated>2013-09-03T10:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2013/09/devlink-2013-knockout-tips</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://www.knockmeout.net/images/posts/dl.jpg" width="291" height="194" title="Photo by @jcreamer898" ></p>

<p>Last week, I was fortunate enough to attend <a href="http://devLink.net">devLink</a> in Chattanooga, Tennessee for the first time.  I had the chance to see many of my <a href="http://appendTo.com">appendTo</a> co-workers in person and meet a number of other folks that I had only corresponded with on-line. I attended many great sessions and overall felt that it was a great experience.</p>

<p>I presented a session on <a href="http://knockoutjs.com">Knockout</a> tips and tricks. These were some things that I felt would be useful to a developer after they have the basics of Knockout done. The session included these ten rounds of tips:</p>

<ol>
<li>Dynamic Templating</li>
<li>Controlling &ldquo;this&rdquo;</li>
<li>Throttling</li>
<li>Subscriptions</li>
<li>Custom Bindings</li>
<li>Extensions</li>
<li>Computed options</li>
<li>Binding Providers</li>
<li>Debugging Tips</li>
<li>Code Smells</li>
</ol>


<p>For this type of talk with lots of live coding, it is challenging to share the slides. So, I recorded a screencast of the presentation. Click <a href="http://vimeo.com/73627803">here</a> to watch in HD or to download it.</p>

<iframe src="http://player.vimeo.com/video/73627803" width="500" height="335" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>


<p> <p><a href="http://vimeo.com/73627803">devLink 2013 - KnockoutJS Tips and Tricks - Ryan Niemeyer</a></p></p>

<p>I am definitely hoping to return to devLink next year and would be happy to hear any feedback or questions about this presentation. <em>Photo by <a href="https://twitter.com/jcreamer898/">@jcreamer898</a></em>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Knockout.js 2.3.0 and 3.0.0 beta are out]]></title>
    <link href="http://www.knockmeout.net/2013/07/knockout-2-3-0-is-out.html"/>
    <updated>2013-07-09T10:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2013/07/knockout-2-3-0</id>
    <content type="html"><![CDATA[<p>Just a brief note that <a href="http://knockoutjs.com">Knockout</a> 2.3.0 is now <a href="https://github.com/knockout/knockout/releases/v2.3.0">available</a>. Additionally, there is a beta release of Knockout 3.0.0 available <a href="https://github.com/knockout/knockout/releases/v3.0.0beta">here</a>. Steve Sanderson has a great <a href="http://blog.stevensanderson.com/2013/07/09/knockout-v2-3-0-released-v3-0-0-beta-available/">post</a> highlighting the features/fixes in 2.3.0 and the changes in 3.0.0 beta. I look forward to writing more about 3.0 changes in the coming months.</p>

<p>2.3.0 contains a ton of fixes and improvements. Here is a copy of the 2.3.0 release notes:</p>

<p>Features:</p>

<ul>
<li><code>hasfocus</code> renamed to <code>hasFocus</code> (<code>hasfocus</code> will still continue to work as well)</li>
<li><code>name</code> parameter of <code>template</code> can accept an observable</li>
<li><code>ko.unwrap</code> added as substitute for <code>ko.utils.unwrapObservable</code></li>
<li><code>options</code> binding uses same technique as <code>foreach</code> to avoid unnecessary re-rendering</li>
<li><code>optionsAfterRender</code> callback added to allow for custom processing of the added options</li>
<li><code>optionsCaption</code> will display a blank caption if the value is an empty string</li>
</ul>


<p>Bugs fixed:</p>

<ul>
<li><code>hasfocus</code>: requires two Tab presses to blur (and related issues) in Chrome; throws error in IE9 on initial binding</li>
<li>Error when you try to inline knockout because of <code>&lt;/script&gt;</code> string</li>
<li>If first node in string template has a binding, the bindings in the template won&rsquo;t get updated</li>
<li><code>selectedOptions</code> doesn&rsquo;t update non-observable properties</li>
<li><code>css</code> won&rsquo;t accept class names with special characters</li>
<li>Applying binding twice to the same nodes fails in strange ways (now it fails with an obvious error message)</li>
<li>Two-way bindings overwrite a read-only computed property with a plain value</li>
<li>Empty template throws an error with jQuery 1.8+</li>
<li><code>observableArray</code> can be initialized with non-array values</li>
<li>Event binding init fails if <code>Object.prototype</code> is extended (fixed all <code>for...in</code> loops)</li>
<li>Calling <code>ko.isSubscribable</code> with <code>null</code> or <code>undefined</code> causes an error</li>
<li>Binding to <code>null</code> or <code>undefined</code> causes an error</li>
<li>Memory leak in IE 7, 8 and 9 from event handlers</li>
<li><code>options</code> binding causes error in IE8+ in compatibility mode</li>
<li><code>value</code> binding on <code>select</code> doesn&rsquo;t match <code>null</code> with caption option</li>
<li>Invalid element in string template can cause a binding error</li>
<li>Conditionally included select gets close to zero width in IE7-8</li>
<li><code>ko.toJS</code> treats Number, String and Boolean instances as objects</li>
<li><code>value</code> binding misses some updates (<code>1</code> -> <code>"+1"</code>)</li>
<li>Exception in <code>ko.computed</code> read function kills the computed</li>
<li>Error if spaces around <code>=</code> in <code>data-bind</code> attribute in string template</li>
</ul>


<p>Maintenance:</p>

<ul>
<li>Port tests to Jasmine</li>
<li>Support Node.js</li>
<li>Remove build output files and Windows build scripts</li>
<li>Build script runs tests using build output (using PhantomJS and Node.js)</li>
<li>Use faster string <code>trim</code> function</li>
<li>Add automated multi-browser testing using Testling-CI</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Knockout.js Troubleshooting Strategies]]></title>
    <link href="http://www.knockmeout.net/2013/06/knockout-debugging-strategies-plugin.html"/>
    <updated>2013-06-05T22:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2013/06/knockout-troubleshooting-strategies</id>
    <content type="html"><![CDATA[<p>This post contains a number of tips, tricks, and strategies that I have used over the last couple of years to debug <a href="http://knockoutjs.com">Knockout</a> applications. Feel free to share some of your own tips in the comments or suggest other areas that you would like to see discussed.</p>

<h2>Binding issues</h2>

<p>The most common errors encountered in Knockout typically center around incorrect or invalid bindings. Here are several different ways that you can diagnose and understand the context of your issue.</p>

<h3>The classic &ldquo;pre&rdquo; tag</h3>

<p>One of the main debugging tasks is to determine what data is being used to bind against a certain element. The quick-and-dirty way that I have traditionally accompished this is by creating a &ldquo;pre&rdquo; tag that outputs the particular data context that is in question.</p>

<p>Knockout includes a helper function called <code>ko.toJSON</code>, which first creates a clean JavaScript object that has all observables/computeds turned into plain values and then uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify</a> to turn it into a JSON string. You would apply this to a &ldquo;pre&rdquo; tag like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>    <span class="nt">&lt;pre</span> <span class="na">data-bind=</span><span class="s">&quot;text: ko.toJSON($data, null, 2)&quot;</span><span class="nt">&gt;&lt;/pre&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>As of KO 2.1, the second and third arguments are passed through to <code>JSON.stringify</code> with the third argument controlling the indentation to produce nicely formatted output. Prior to KO 2.1, you could still do this by using <code>JSON.stringify(ko.toJS($data), null, 2)</code>. You can use this technique to look at specific properties or use the special <a href="http://knockoutjs.com/documentation/binding-context.html">context variables</a> like <code>$data</code>, <code>$parent</code>, or <code>$root</code>. This will give you output like:</p>

<pre>
{
  "title": "Some items",
  "items": [
    {
      "description": "one",
      "price": 0
    },
    {
      "description": "two",
      "price": 0
    },
    {
      "description": "three",
      "price": 0
    }
  ],
  "titleUpper": "SOME ITEMS"
}
</pre>


<h3>Lazy? Then just console.log it</h3>

<p>Does that &ldquo;pre&rdquo; tag look like too much work?  An even easier and more direct solution is to simply put a <code>console.log</code> in your binding string. The binding string is parsed into a JavaScript object, so code that you place in it will be executed. In addition, you can also put bindings that don&rsquo;t exist into your binding string. This is because bindings can be used as options in other bindings (think <code>optionsText</code> or <code>optionsValue</code>), so KO does not throw an exception when it finds an undefined binding handler.  This means that you can simply do:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>    <span class="nt">&lt;input</span> <span class="na">data-bind=</span><span class="s">&quot;blah: console.log($data), value: description&quot;</span> <span class="nt">/&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>The block above will output your data to the console just before encountering a typo in the <code>description</code> property. You may even want to wrap your data in a call to <code>ko.toJS</code> or <code>ko.toJSON</code> depending on how you want the output to appear in the console.</p>

<p><em>Update: in KO 3.0, a binding with no actual handler, will no longer get executed. You would need to use an actual binding like the custom one described below or even something harmless like the built-in <code>uniqueName</code> binding.</em></p>

<h3>Extensions / bookmarklets</h3>

<p>There are several great community-created solutions for doing this type of investigation as well:</p>

<ul>
<li><a href="https://chrome.google.com/webstore/detail/knockoutjs-context-debugg/oddcpmchholgcjgjdnfjmildmlielhof?hl=en">Knockout Context Debugger</a> Chrome extension - adds a pane to the Chrome dev tools that allows you to see the context associated with a specific element. <em>Update: the latest version adds some nice tracing functionality as well.</em> Created by <a href="https://twitter.com/timstuyckens">Tim Stuyckens</a>.</li>
<li><a href="https://github.com/aaronpowell/glimpse-knockout">Knockout Glimpse plugin</a> - <a href="http://getglimpse.com/">Glimpse</a> is a powerful debugging tool for ASP.NET. <a href="http://www.aaron-powell.com/">Aaron Powell</a> created an excellent Knockout plugin for it.</li>
<li><a href="http://bowtie-ko.com/">Bowtie</a> - a bookmarklet by Max Pollack that lets you inspect the context associated with bindings and add watch values. Note - it does assume that the page includes jQuery.</li>
<li><a href="https://github.com/jmeas/knockout-debug">Knockout-debug</a> - a bookmarklet by James Smith that gives a nice display of your view model.</li>
</ul>


<h3>Performance testing - how often is a binding firing?</h3>

<p>Sometimes an interesting thing to explore/investigate is how often a certain binding is being triggered and with what values. I like to use a custom binding for this purpose.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="nx">ko</span><span class="p">.</span><span class="nx">bindingHandlers</span><span class="p">.</span><span class="nx">logger</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>        <span class="nx">update</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">valueAccessor</span><span class="p">,</span> <span class="nx">allBindings</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="c1">//store a counter with this element</span>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">count</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">domData</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="s2">&quot;_ko_logger&quot;</span><span class="p">)</span> <span class="o">||</span> <span class="mi">0</span><span class="p">,</span>
</span><span class='line'>                <span class="nx">data</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">toJS</span><span class="p">(</span><span class="nx">valueAccessor</span><span class="p">()</span> <span class="o">||</span> <span class="nx">allBindings</span><span class="p">());</span>
</span><span class='line'>
</span><span class='line'>            <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">domData</span><span class="p">.</span><span class="nx">set</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="s2">&quot;_ko_logger&quot;</span><span class="p">,</span> <span class="o">++</span><span class="nx">count</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">console</span> <span class="o">&amp;&amp;</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>                <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">count</span><span class="p">,</span> <span class="nx">element</span><span class="p">,</span> <span class="nx">data</span><span class="p">);</span>
</span><span class='line'>            <span class="p">}</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>This will show you a count of how many times the bindings on this element have been fired. You can either pass in a value to log or it will log the values provided to all bindings on that element. You may want to include a timestamp as well, depending on your needs. There are many times where this will open your eyes to a lot of unnecessary work happening in your UI. It may be from pushing <a href="http://www.knockmeout.net/2012/04/knockoutjs-performance-gotcha.html">again and again</a> to an observableArray or maybe a case where <a href="http://knockoutjs.com/documentation/throttle-extender.html">throttling</a> would be appropriate. For example, you might place this on an element like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>    <span class="nt">&lt;input</span> <span class="na">data-bind=</span><span class="s">&quot;logger: description, value: description, enable: isEditable&quot;</span> <span class="nt">/&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p> and expect output like:</p>

<p> <pre>
 1 &lt;input&hellip;/&gt; &ldquo;Robert&rdquo;
 2 &lt;input&hellip;/&gt; &ldquo;Bob&rdquo;
 3 &lt;input&hellip;/&gt; &ldquo;Bobby&rdquo;
 4 &lt;input&hellip;/&gt; &ldquo;Rob&rdquo;
 </pre></p>

<p>Just a note that in the KO 3.0 (almost in beta), each binding on an element will be fired independently, as opposed to now where <a href="http://www.knockmeout.net/2012/06/knockoutjs-performance-gotcha-3-all-bindings.html">all bindings fire together</a>. When KO 3.0 is released, you would want to use a binding like this with that in mind and likely only pass the specific dependencies that you are interested in logging.</p>

<h3>Undefined properties</h3>

<p>Another common source of binding issues is undefined properties. Here is a quick tip for handling scenarios where a property is missing and it will not be added later. This is not specifically a debugging tip, but it can help you avoid potential binding issues without much fuss.</p>

<p>For example, this would cause an error (if <code>myMissingProperty</code> is missing):</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>    <span class="nt">&lt;span</span> <span class="na">data-bind=</span><span class="s">&quot;text: myMissingProperty&quot;</span><span class="nt">&gt;&lt;/span&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>However, this will bind properly against <code>undefined</code>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>    <span class="nt">&lt;span</span> <span class="na">data-bind=</span><span class="s">&quot;text: $data.myMissingProperty&quot;</span><span class="nt">&gt;&lt;/span&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>In JavaScript it is an error to attempt to retrieve the value of a variable that is not defined, but it is fine to access an undefined property off of another object. So, while <code>myMissingProperty</code> and <code>$data.myMissingProperty</code> are equivalent, you can avoid the &ldquo;variable is not defined&rdquo; errors by referencing the property off of its parent object (<code>$data</code>).</p>

<h3>Catching exceptions using a custom binding provider</h3>

<p>Errors in bindings are inevitable in a Knockout application. Many of the techniques described in the first section can help you understand the context around your binding. There is another option that can also help you track and log problems in your bindings. A <a href="http://www.knockmeout.net/2011/09/ko-13-preview-part-2-custom-binding.html">custom binding provider</a> provides a nice extensibility point for trapping these exceptions.</p>

<p>For example, a simple &ldquo;wrapper&rdquo; binding provider might look like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>      <span class="kd">var</span> <span class="nx">existing</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">bindingProvider</span><span class="p">.</span><span class="nx">instance</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="nx">ko</span><span class="p">.</span><span class="nx">bindingProvider</span><span class="p">.</span><span class="nx">instance</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>            <span class="nx">nodeHasBindings</span><span class="o">:</span> <span class="nx">existing</span><span class="p">.</span><span class="nx">nodeHasBindings</span><span class="p">,</span>
</span><span class='line'>            <span class="nx">getBindings</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">node</span><span class="p">,</span> <span class="nx">bindingContext</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>                <span class="kd">var</span> <span class="nx">bindings</span><span class="p">;</span>
</span><span class='line'>                <span class="k">try</span> <span class="p">{</span>
</span><span class='line'>                   <span class="nx">bindings</span> <span class="o">=</span> <span class="nx">existing</span><span class="p">.</span><span class="nx">getBindings</span><span class="p">(</span><span class="nx">node</span><span class="p">,</span> <span class="nx">bindingContext</span><span class="p">);</span>
</span><span class='line'>                <span class="p">}</span>
</span><span class='line'>                <span class="k">catch</span> <span class="p">(</span><span class="nx">ex</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>                   <span class="k">if</span> <span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">console</span> <span class="o">&amp;&amp;</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>                       <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;binding error&quot;</span><span class="p">,</span> <span class="nx">ex</span><span class="p">.</span><span class="nx">message</span><span class="p">,</span> <span class="nx">node</span><span class="p">,</span> <span class="nx">bindingContext</span><span class="p">);</span>
</span><span class='line'>                   <span class="p">}</span>
</span><span class='line'>                <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>                <span class="k">return</span> <span class="nx">bindings</span><span class="p">;</span>
</span><span class='line'>            <span class="p">}</span>
</span><span class='line'>        <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">})();</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now, binding exceptions will be caught and logged with the error message, the element, and the binding context (contains <code>$data</code>, <code>$parent</code>, etc.). A binding provider can also be a useful tool to log and diagnose the amount of times that bindings are being hit.</p>

<h2>View Model issues</h2>

<p>Binding issues seem to be the most common source of errors in Knockout, but there are still errors/bugs on the view model side as well. Here are a few ways to instrument and control your view model code.</p>

<h3>Manul subscriptions for logging</h3>

<p>A basic technique to help understand how things are being triggered in your view model is to create manual subscriptions to your observables or computeds to log the values. These subscriptions do not create dependencies of their own, so you can freely log individual values or the entire object.  You can do this for observables, computeds, and observableArrays.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">firstName</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">firstName</span><span class="p">.</span><span class="nx">triggeredCount</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">firstName</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">newValue</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">console</span> <span class="o">&amp;&amp;</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="o">++</span><span class="k">this</span><span class="p">.</span><span class="nx">triggeredCount</span><span class="p">,</span> <span class="s2">&quot;firstName triggered with new value&quot;</span><span class="p">,</span> <span class="nx">newValue</span><span class="p">);</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>You could format the message to include whatever information is relevant to you. It would also be easy enough to create an extension to add this type of tracking to any observable/computed:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="nx">ko</span><span class="p">.</span><span class="nx">subscribable</span><span class="p">.</span><span class="nx">fn</span><span class="p">.</span><span class="nx">logIt</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">name</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">triggeredCount</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">newValue</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">console</span> <span class="o">&amp;&amp;</span> <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>                <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="o">++</span><span class="k">this</span><span class="p">.</span><span class="nx">triggeredCount</span><span class="p">,</span> <span class="nx">name</span> <span class="o">+</span> <span class="s2">&quot; triggered with new value&quot;</span><span class="p">,</span> <span class="nx">newValue</span><span class="p">);</span>
</span><span class='line'>            <span class="p">}</span>
</span><span class='line'>        <span class="p">},</span> <span class="k">this</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">return</span> <span class="k">this</span><span class="p">;</span>
</span><span class='line'>    <span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>Since the extension returns <code>this</code>, you can chain it onto an observable/computed during creation like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>   <span class="k">this</span><span class="p">.</span><span class="nx">firstName</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">(</span><span class="nx">first</span><span class="p">).</span><span class="nx">logIt</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">username</span> <span class="o">+</span> <span class="s2">&quot; firstName&quot;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this case, I chose to include the <code>username</code> to ensure that it is outputting a unique value in the case that I have a collection of objects that each have a <code>firstName</code> observable. The output would look something like:</p>

<pre>
1 "bob1234 firstName triggered with new value" "Robert"
2 "bob1234 firstName triggered with new value" "Bob"
3 "bob1234 firstName triggered with new value" "Bobby"
4 "bob1234 firstName triggered with new value" "Rob"
</pre>


<h3>The value of &ldquo;this&rdquo;</h3>

<p>Issues with the value of <code>this</code> is one of the most common challenges encountered when starting out with Knockout. Whenever you are binding to an event (<code>click</code> / <code>event</code> binding) and are using a function off of another context (like <code>$parent</code> or <code>$root</code>), you will generally need to worry about the context, as Knockout executes these handlers using the current data as the value of <code>this</code>.</p>

<p>There are several ways to ensure that you have the appropriate context:</p>

<p>1- you can use <code>.bind</code> to create a new function that is always bound to a specific context from within your view model. If the browser does not support <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bind</a> natively, then Knockout adds a shim for it.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>  <span class="k">this</span><span class="p">.</span><span class="nx">removeItem</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">item</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>      <span class="k">this</span><span class="p">.</span><span class="nx">items</span><span class="p">.</span><span class="nx">remove</span><span class="p">(</span><span class="nx">item</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}.</span><span class="nx">bind</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>  or if your function lives on the prototype, you would have to create a bound version on each instance (not ideal) like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>  <span class="k">this</span><span class="p">.</span><span class="nx">removeItem</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">removeItem</span><span class="p">.</span><span class="nx">bind</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>2- you can create a variable in your view model that corresponds to the current instance (<code>var self = this;</code>) and always use <code>self</code> rather than <code>this</code> in your handlers. This technique is convenient, but does not lend itself to placing functions on a prototype object or adding functions through mix-ins, as these functions need to access the instance through the value of <code>this</code> (unless bound like in #1).</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'> <span class="kd">var</span> <span class="nx">self</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">this</span><span class="p">.</span><span class="nx">removeItem</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">item</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>     <span class="nx">self</span><span class="p">.</span><span class="nx">items</span><span class="p">.</span><span class="nx">remove</span><span class="p">(</span><span class="nx">item</span><span class="p">);</span>
</span><span class='line'>  <span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>3- you can even use <code>.bind</code> in the binding string, depending on how comfortable you are with seeing it in your markup. This would look like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>    <span class="nt">&lt;button</span> <span class="na">data-bind=</span><span class="s">&quot;click: $parent.removeItem.bind($parent)&quot;</span><span class="nt">&gt;</span>Remove Item<span class="nt">&lt;/button&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Similarly, you could create a simple custom binding that wraps the <code>event</code> binding and takes in a handler and a context like <code>data-bind="clickWithContext: { action: $parent.removeItem, context: $parent }"</code>.</p>

<p>4- the way that I personally handle this now is to use my <a href="https://github.com/rniemeyer/knockout-delegatedEvents">delegated events plugin</a>, which will do event delegation and as a by-product is able to automatically call the method off of the object that owns it. This also makes it convenient/practical to place your functions on the prototype of your object. With this plugin, the above sample would simply look like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>    <span class="nt">&lt;button</span> <span class="na">data-click=</span><span class="s">&quot;removeItem&quot;</span><span class="nt">&gt;</span>Remove Item<span class="nt">&lt;/button&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>I have found that this removes the vast majority of the context binding concerns that I have in my viewmodel code.</p>

<h2>Using the console</h2>

<p>One of my favorite ways to debug/investigate a Knockout app is to use the browser&rsquo;s debugging console. If your view model is well written, you can generally control your entire application from the console. Recently, I ran a data conversion involving hundreds of records from the debugging console by loading the appropriate data, looping through each record to manipulate any observables that needed updating, and saving each record back to the database. This may not always be the best idea, but it was the most practical and efficient way for me to accomplish the conversion for my scenario.</p>

<h3>Accessing your data</h3>

<p>The first step is getting a reference to your data from the console. If your app is exposed globally, perhaps under a specific namespace, then you are already good to go. However, even if you call <code>ko.applyBindings</code> without your view model being available globally, you can still easily get at your data. Knockout includes <code>ko.dataFor</code> and <code>ko.contextFor</code> <a href="http://knockoutjs.com/documentation/unobtrusive-event-handling.html">helper methods</a> that given an element tell you the data/context that was available to the element during binding. For example, to get your overall view model, you may start with something like this in the console:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="kd">var</span> <span class="nx">data</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">dataFor</span><span class="p">(</span><span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now you have access to your overall view model (if you simply called <code>ko.applyBindings</code> without specifying a specific root element). With access to that view model, you can call methods, set observable values, and log/inspect specific objects.</p>

<h3>Making logging a bit smarter</h3>

<p>Anyone that has done debugging in Knockout has likely done a <code>console.log</code> on an <code>observable</code> or <code>computed</code> directly at some point and found some less than useful output like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">function</span> <span class="nx">d</span><span class="p">(){</span><span class="k">if</span><span class="p">(</span><span class="mi">0</span><span class="o">&lt;</span><span class="nx">arguments</span><span class="p">.</span><span class="nx">length</span><span class="p">){</span><span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="nx">d</span><span class="p">.</span><span class="nx">equalityComparer</span><span class="o">||!</span><span class="nx">d</span><span class="p">.</span><span class="nx">equalityComparer</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span><span class="nx">arguments</span><span class="p">[</span><span class="mi">0</span><span class="p">]))</span><span class="nx">d</span><span class="p">.</span><span class="nx">H</span><span class="p">(),</span><span class="nx">c</span><span class="o">=</span><span class="nx">arguments</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span><span class="nx">d</span><span class="p">.</span><span class="nx">G</span><span class="p">();</span><span class="k">return</span> <span class="k">this</span><span class="p">}</span><span class="nx">b</span><span class="p">.</span><span class="nx">r</span><span class="p">.</span><span class="nx">Wa</span><span class="p">(</span><span class="nx">d</span><span class="p">);</span><span class="k">return</span> <span class="nx">c</span><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>One way to improve this output is to add a <code>toString</code> function to the various types. I like to show the name of the type (like <code>observable</code> or <code>computed</code>) and the current value. This helps you quickly understand that it is indeed a KO object, which type it is, and the latest value. This might look like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">.</span><span class="nx">fn</span><span class="p">.</span><span class="nx">toString</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="s2">&quot;observable: &quot;</span> <span class="o">+</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">toJSON</span><span class="p">(</span><span class="k">this</span><span class="p">(),</span> <span class="kc">null</span><span class="p">,</span> <span class="mi">2</span><span class="p">);</span>
</span><span class='line'>    <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">ko</span><span class="p">.</span><span class="nx">computed</span><span class="p">.</span><span class="nx">fn</span><span class="p">.</span><span class="nx">toString</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="s2">&quot;computed: &quot;</span> <span class="o">+</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">toJSON</span><span class="p">(</span><span class="k">this</span><span class="p">(),</span> <span class="kc">null</span><span class="p">,</span> <span class="mi">2</span><span class="p">);</span>
</span><span class='line'>    <span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>The output in the Chrome console would now look like:</p>

<pre>
observable: "Bob"
computed: "Bob Smith"
observable: "Jones"
computed: "Bob Jones"
</pre>


<p>Note that not all browsers respect the <code>toString</code> function, but it certainly helps with Chrome. Also, observableArrays are a bit harder to handle. Chrome sees that the observableArray (function) has both a <code>length</code> and a <code>splice</code> method and assumes that it is an array. Adding a <code>toString</code> function is not effective in this case, unless you delete the <code>splice</code> function from observableArrays.</p>

<h2>Final notes</h2>

<ul>
<li><p><strong>Debugging Knockout core</strong> - When you encounter exceptions in your Knockout application, I would not recommend trying to debug the Knockout core library code as your first choice. It is almost always more effective and efficient to isolate the origin of the issue in your application code first and try to simplify the reproduction of that issue. In my experience, the main situation where stepping into Knockout core is potentially a good choice is if you are truly seeing inconsistent behavior between browsers. Knockout core can be challenging to step through and follow, so if you do find yourself debugging into the core library, a good place to start is within the binding handlers themselves.</p></li>
<li><p><strong>Be careful with logging</strong> - if you add logging or instrumentation to your code, be mindful of how this logging may contribute to the dependencies of your computeds/bindings. For example, if you logged <code>ko.toJSON($root)</code> in a <code>computed</code> you would gain a dependency on all observables in the structure. Additionally, if you have a large view model, be aware of the potential performance impact of frequently converting large object graphs to JSON and logging or displaying the result. Throttling may help in that scenario.</p></li>
<li><p><strong>console.log format</strong> - the <code>console.log</code> calls in the snippets are just samples. I understand that some browers don&rsquo;t support passing multiple arguments to <code>console.log</code> and some do not let you navigate object hierarchies. If you need to do this logging in a variety of browers, then make sure that you build suitable output. The normal case where I am doing logging is temporarily in Chrome during development.</p></li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Working with AMD modules in Knockout.js]]></title>
    <link href="http://www.knockmeout.net/2013/05/knockout-amd-helpers-plugin.html"/>
    <updated>2013-05-01T22:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2013/05/knockout-amd-helpers-plugin</id>
    <content type="html"><![CDATA[<p>After being a bit resistant at first, I have happily moved to using <a href="http://requirejs.org">require.js</a> to manage dependencies in most of the <a href="http://knockoutjs.com">Knockout.js</a> applications that I have written in the last year or so. With each application, I have tried a number of patterns to make it easier to work with <a href="https://github.com/amdjs/amdjs-api/wiki/AMD">AMD</a> (Asynchronous Module Definition) modules. Recently, I decided to formalize some of these patterns into a lightweight plugin that makes it simple to bind against modules and pull in templates that live in external files.</p>

<p>The result is this library: <strong><a href="https://github.com/rniemeyer/knockout-amd-helpers">knockout-amd-helpers</a></strong></p>

<h2>Why require.js and AMD modules</h2>

<p>Breaking an application down into small, decoupled modules is a pattern that works well when done right. Creating modules in JavaScript is often accomplished by using various namespacing patterns. As an application grows though, it is easy to lose sight of the individual dependencies of each module and eventually maintaining the order that all of your scripts need to be loaded in becomes a burden as well. AMD module loaders can help with these issues.</p>

<p>There are plenty of good resources that help explain require.js, dependency management, and AMD modules. Here are a few good ones:</p>

<ul>
<li>The require.js documentation on <a href="http://requirejs.org/docs/whyamd.html">AMD modules</a>.</li>
<li>Our <a href="http://knockoutjs.com/documentation/amd-loading.html">documentation</a> on using Knockout with require.js.</li>
<li>My co-worker <a href="https://twitter.com/jcreamer898">Jonathan Creamer</a>&rsquo;s <a href="http://net.tutsplus.com/tutorials/javascript-ajax/building-large-maintainable-and-testable-knockout-js-applications/">tutorial</a> on using Knockout.js in large-scale applications. He also recently did a presentation for <a href="http://live.dotnetconf.net/2013-04">dotnetConf</a> that can be found <a href="http://www.youtube.com/watch?v=EXqyZ7k1lnw">here</a> on using require.js and using it with ASP.NET MVC.</li>
<li>While require.js is the most mentioned option in this category, there are others including the excellent <a href="https://github.com/cujojs/curl">curl.js</a>.</li>
</ul>


<h2>A few pain points</h2>

<p>When developing Knockout applications using require.js, there are a couple of situations that out-of-the-box still seemed less than perfect to me.</p>

<p>1- After breaking down your application into specific modules, it is unfortunate to have to include all of your markup on a single page. There are server-side solutions to pull in partials for your templates, but that still results in a page that contains all of your markup from the start. There is also the <a href="https://github.com/ifandelse/Knockout.js-External-Template-Engine">external template engine</a>, which works well, but is not designed to leverage the capabilities of the AMD loader libraries (like optimization/bundling).</p>

<p>2- Dynamically requesting and binding against modules is not trivial. Normally, you would build a main &ldquo;App&rdquo; view model that contains all of the sub-modules that you want to bind against. It would be nice though to be able to dynamically pull in modules or use modules as reusable components in an app under any context.</p>

<h2>Looking at potential solutions</h2>

<p>Based on some of the different approaches that I have used in the past, I created the <a href="https://github.com/rniemeyer/knockout-amd-helpers">knockout-amd-helpers</a> plugin to hopefully help ease these issues.</p>

<h3>An AMD compatible template engine</h3>

<p>The first feature of the plugin is to use one of Knockout&rsquo;s extensibility points to replace the default template engine with one that is able to load named templates using the AMD loader&rsquo;s <code>text</code> plugin.</p>

<p>I used the template sources extensibility point that I discussed <a href="http://www.knockmeout.net/2011/10/ko-13-preview-part-3-template-sources.html">here</a>. When a named template is requested, it first checks to see if there is a <code>script</code> tag with the specified id (the default engine actually will grab any element with that id) and if not uses the text plugin to require the template. This will asynchronously load the template (unless it has already been loaded or is bundled and already available on the client). The template source uses an observable that triggers the <code>template</code> binding to update when the template is available.</p>

<p>For example, when using a binding like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>    <span class="nt">&lt;ul</span> <span class="na">data-bind=</span><span class="s">&quot;template: { name: &#39;itemView&#39;, foreach: items }&quot;</span><span class="nt">&gt;&lt;/ul&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>If there is no script tag with an id of <code>itemView</code>, it will attempt to load the template. The engine uses a default path of <code>templates</code> and a default suffix of <code>.tmpl.html</code>.  So, it would look for the template at <code>templates/itemView.tmpl.html</code>.  The default path and suffix can be configured and you can also pass a more specific path in for the name (<code>sub/path/itemView</code>).</p>

<h3>A module binding</h3>

<p>This updated template engine now helps keep your templates as modular as your view models, but it still would be nice to easily pull modules into an application without using a top-level view model that needs to contain everything that you might want to bind against.</p>

<p>To help with this situation, the plugin includes a <code>module</code> binding, which offers a flexible way to dynamically pull a module into your markup. Here is a basic example:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>    <span class="nt">&lt;nav</span> <span class="na">data-bind=</span><span class="s">&quot;module: &#39;navigation&#39;&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>This will require a <code>navigation</code> module (the base directory can be configured as well).  If the main element had children, then it would use them as an inline/anonymous template. However, in this case, since the element does not have children, it will use <code>navigation</code> as the template name and follow the template engine&rsquo;s rules for pulling in the template.</p>

<p>After the loading the module it will follow a few rules for deciding what data to bind against:</p>

<ol>
<li>If the module returns a function, then it will create a new instance</li>
<li>If the module returns an object, then it will, by default, call an <code>initialize</code> function on the object (if it exists) and either use the result of the function or the original object if there is not a return value.</li>
</ol>


<p>This gives you the flexibility of either constructing a new object, using an existing object, or calling a function that returns some object to bind against.</p>

<p>The <code>module</code> binding has a number of options that you can pass in as well. Here is an example passing all of the options:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>    <span class="nt">&lt;div</span> <span class="na">data-bind=</span><span class="s">&quot;module: { name: &#39;one&#39;, data: initialData, template: &#39;oneTmpl&#39;,</span>
</span><span class='line'><span class="s">                              initializer: &#39;createItem&#39;, afterRender: myCallback }&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>These options let you do things like customize the template to use, specify data to pass into the constructor or initializer, define the name of the function to call, and pass an afterRender function through to the <code>template</code> binding.</p>

<p>With this binding, it is possible to call <code>ko.applyBindings({})</code> and build your application strictly using the <code>module</code> binding. A <code>module</code> binding can be nested inside other <code>module</code> bindings and you can also use observables to dynamically specify your module.</p>

<h3>Communicating between modules</h3>

<p>When building an app using this structure, it would be less than ideal to rely on <code>$root</code> or <code>$parent</code> calls within the markup to communicate between modules. This can potentially couple your module to only working within a certain context. While this can certanily work, a better solution may be to use some type of messaging to communicate between the modules.</p>

<p>I have a library called <a href="https://github.com/rniemeyer/knockout-postbox/">knockout-postbox</a> that adds a <code>ko.postbox</code> object and some observable extensions that make it easy to publish values on a topic and update an observable based on a subscription to a topic.</p>

<p>For example, in a module that defines the main content, you could have an observable like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>   <span class="k">this</span><span class="p">.</span><span class="nx">sectionName</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">().</span><span class="nx">subscribeTo</span><span class="p">(</span><span class="s2">&quot;navigation.current&quot;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then, in the navigation module, publish on that topic like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>   <span class="k">this</span><span class="p">.</span><span class="nx">selectedNavItem</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">().</span><span class="nx">publishOn</span><span class="p">(</span><span class="s2">&quot;navigation.current&quot;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>The postbox library supports a number of options that control how the publish/subscribe process works, but if you are looking for a stand-alone library that supports a number of additional features (channels, wildcards, envelopes), then I would recommend <a href="https://github.com/postaljs/postal.js">postal.js</a></p>

<h2>Summary</h2>

<p>If you are using AMD modules in your Knockout application and are looking for a lightweight and simple, but flexible way to bind against templates and modules, then check out this new <a href="https://github.com/rniemeyer/knockout-amd-helpers">library</a>. It has been tested with both require.js and curl.js. I would be happy to help support any other AMD loaders, if there is interest. Please check out the README on the repository for additional documentation. I also plan to work on a better example, as time permits.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Joining appendTo]]></title>
    <link href="http://www.knockmeout.net/2013/03/joining-appendto.html"/>
    <updated>2013-03-28T09:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2013/03/joining-appendto</id>
    <content type="html"><![CDATA[<p>Just a quick note that I joined <a href="http://appendTo.com">appendTo</a> as a senior JavaScript engineer at the beginning of March. I am really excited to work with a great group of talented people and to get a chance to work on a wide variety of web development projects. I am especially eager to use some new technologies/libraries to solve real problems and can&rsquo;t wait to gain new perspectives on ways to improve or build on top of <a href="http://knockoutjs.com">Knockout</a>.</p>

<p>If you are looking for help with a significant Knockout project (or any other front-end technology), then I would encourage you to <a href="http://appendto.com/contact">contact</a> appendTo and maybe we could have the chance to work together. For general KO questions or if you are looking for help on a project that only requires a small time investment, feel free to contact me directly.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Tekpub Refactoring Knockout.js Screencast]]></title>
    <link href="http://www.knockmeout.net/2013/02/tekpub-knockoutjs-refactoring.html"/>
    <updated>2013-02-21T20:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2013/02/tekpub-knockout-video</id>
    <content type="html"><![CDATA[<p>Recently, I had the chance to do some pair programming with <a href="https://twitter.com/robconery">Rob Conery</a> to refactor a <a href="http://knockoutjs.com">Knockout</a>-based shopping cart for a <a href="http://tekpub.com">Tekpub</a> full throttle <a href="http://tekpub.com/products/knockout_refactor">video</a>. Rob has had a love/hate relationship with Knockout over the years and I have had several discussions with him in the past trying to work through some of his concerns.</p>

<p>He recently asked me to take a look at a Knockout-based shopping cart that he had written for another video. The code was working just fine, but as I dug into it, I started jotting down a <em>LOT</em> of notes. I ended up formatting them in markdown and sent them Rob&rsquo;s way. He thought that it would be a good idea to record a screencast to really dig into those notes.</p>

<p>Here is a trailer for the <a href="http://tekpub.com/products/knockout_refactor">screencast</a>:</p>

<iframe src="http://player.vimeo.com/video/60131454" width="500" height="313" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>


<p><a href="http://vimeo.com/60131454"></a></p>

<p>I personally have had a Tekpub subscription for around two years and definitely recommend the service. They are really putting out some great content lately and have a well-done Knockout <a href="http://tekpub.com/productions/knockout">series</a>.</p>

<p><strong>Update:</strong> here is a <a href="https://gist.github.com/rniemeyer/a715efc49acb8169a3e2">link</a> to the notes that I sent Rob.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A Simple Editor Pattern for Knockout.js]]></title>
    <link href="http://www.knockmeout.net/2013/01/simple-editor-pattern-knockout-js.html"/>
    <updated>2013-01-28T20:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2013/01/simple-editor-pattern-knockoutjs</id>
    <content type="html"><![CDATA[<p>Implementing an editor that allows users to accept or cancel their changes is a common task in <a href="http://knockoutjs.com">Knockout.js</a>. Previously, I <a href="http://www.knockmeout.net/2011/03/guard-your-model-accept-or-cancel-edits.html">suggested</a> the idea of a <code>protectedObservable</code> that is an extended observable with the ability to commit and reset the value being edited. Since Knockout 2.0, I would probably now implement that functionality using either <a href="http://knockoutjs.com/documentation/extenders.html">extenders</a> or by augmenting the <code>.fn</code> <a href="http://knockoutjs.com/documentation/fn.html">object</a> of the core types. However, I now use a different pattern.</p>

<p>I described this pattern in the Twin Cities Code Camp presentation <a href="http://www.knockmeout.net/2012/10/twincitiescodecamp-2012-session.html">here</a>. This technique allows you to easily copy, commit, and revert changes to an entire model. There are two rules that make this pattern work:</p>

<ol>
<li><p>The creation of observables and computeds needs to be separate from actually populating them with values.</p></li>
<li><p>The format of the data that you put in should be the same as the format that you are able to get out. Typically this means that calling <code>ko.toJS</code> on your model should result in an object that you could send back through the function described in step 1 to re-populate the values.</p></li>
</ol>


<h2>Separate creation and initialization</h2>

<p>The idea is that we can apply fresh data to our object at anytime, so our constructor function should just create our structure, while a separate method handles setting the values.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="kd">var</span> <span class="nx">Item</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">price</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
</span><span class='line'>    <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">Item</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">update</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">name</span><span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">name</span> <span class="o">||</span> <span class="s2">&quot;new item&quot;</span><span class="p">);</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">price</span><span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">price</span> <span class="o">||</span> <span class="mi">0</span><span class="p">);</span>
</span><span class='line'>    <span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>Our <code>update</code> function (call it whatever you like <code>init</code>, <code>initialize</code>, <code>hydrate</code>, etc.), needs to handle populating the values of all of the observables given a plain JavaScript object. It can also handle supplying default values.</p>

<h2>Data in matches data out</h2>

<p>To make this pattern work, we need to be able to put a plain JavaScript object in and get the equivalent object out. Ideally, simply calling <code>ko.toJS</code> on our model, will give us the plain object that we need. It is okay, if there are some additional computeds/properties on the object, but it needs to be appropriate for sending through the <code>update</code> function again.</p>

<p>A technique that I use frequently to &ldquo;hide&rdquo; data that I won&rsquo;t want when I turn the model into a plain JavaScript object or to JSON is to use a &ldquo;sub-observable&rdquo;. So, if we had a computed observable to show a formatted version of the price that we don&rsquo;t want in our output, we could specify it like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="kd">var</span> <span class="nx">Item</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">price</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">price</span><span class="p">.</span><span class="nx">formatted</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">computed</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">getFormattedPrice</span><span class="p">,</span> <span class="k">this</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
</span><span class='line'>    <span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>Since observables are functions and functions are objects that can have their own properties, it is perfectly valid to create a <code>formatted</code> computed off of the <code>price</code> observable. In the markup, we can bind against <code>price.formatted</code>. However, when calling <code>ko.toJS</code> or <code>ko.toJSON</code>, the <code>formatted</code> sub-observable will disappear, as we will simply be left with a <code>price</code> property and value.</p>

<h2>Reverting changes</h2>

<p>Now that we have these pieces in place, it is easy to create an editor that allows reverting changes. In the event that a user chooses to cancel their editing, all we need to do is send the original data back through our <code>update</code> function and we will be back to where we started.</p>

<p>We will need to track the original data, so that it is available to repopulate the model. A good place to cache this data is in the <code>update</code> function itself. It is useful to make sure that the data is &ldquo;hidden&rdquo; as well, so multiple edits don&rsquo;t result in recursive versions of the old data being kept around. If we were not using the prototype, then we could just use a local variable to store the data, but since we are placing our shared functions on the prototype in these samples, we need to find another way to hide this data. A simple solution is to create an empty <code>cache</code> function and store our data as property off of it. This will prevent calls to <code>ko.toJS</code> or <code>ko.toJSON</code> from capturing this data.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="kd">var</span> <span class="nx">Item</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">name</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">price</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">cache</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{};</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
</span><span class='line'>    <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">extend</span><span class="p">(</span><span class="nx">Item</span><span class="p">.</span><span class="nx">prototype</span><span class="p">,</span> <span class="p">{</span>
</span><span class='line'>      <span class="nx">update</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">name</span><span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">name</span> <span class="o">||</span> <span class="s2">&quot;new item&quot;</span><span class="p">);</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">price</span><span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">price</span> <span class="o">||</span> <span class="mi">0</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>        <span class="c1">//save off the latest data for later use</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">cache</span><span class="p">.</span><span class="nx">latestData</span> <span class="o">=</span> <span class="nx">data</span><span class="p">;</span>
</span><span class='line'>      <span class="p">},</span>
</span><span class='line'>      <span class="nx">revert</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">update</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">cache</span><span class="p">.</span><span class="nx">latestData</span><span class="p">);</span>
</span><span class='line'>      <span class="p">}</span>
</span><span class='line'>    <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this scenario, we will let edits persist to our observables and in the event that a user chooses to cancel, we will refresh our model with the original data.</p>

<h2>Committing changes</h2>

<p>When a user accepts the data, we need to make sure that we update the cached data with the current state of the model. For example, we could simply add a <code>commit</code> or <code>accept</code> function to our prototype that does:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="nx">commit</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">cache</span><span class="p">.</span><span class="nx">latestData</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">toJS</span><span class="p">(</span><span class="k">this</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>We now have the latest data cached, so the next time that a user cancels it will be reverted back to this updated state.</p>

<h2>Copying/cloning</h2>

<p>Sometimes in an editor, we would not want the currently edited observables to affect the rest of the UI until the user chooses to accept the changes. In this case, we can use these same methods to create a copy of the item for editing and then apply it back to the original. Here is how our overall view model might look:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="kd">var</span> <span class="nx">ViewModel</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">items</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="c1">//turn the raw items into Item objects</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">items</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observableArray</span><span class="p">(</span><span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">arrayMap</span><span class="p">(</span><span class="nx">items</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="k">return</span> <span class="k">new</span> <span class="nx">Item</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
</span><span class='line'>        <span class="p">});</span>
</span><span class='line'>
</span><span class='line'>        <span class="c1">//hold the real currently selected item</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">selectedItem</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>        <span class="c1">//make edits to a copy</span>
</span><span class='line'>        <span class="k">this</span><span class="p">.</span><span class="nx">itemForEditing</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
</span><span class='line'>    <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">extend</span><span class="p">(</span><span class="nx">ViewModel</span><span class="p">.</span><span class="nx">prototype</span><span class="p">,</span> <span class="p">{</span>
</span><span class='line'>        <span class="c1">//select and item and make a copy of it for editing</span>
</span><span class='line'>        <span class="nx">selectItem</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">item</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="k">this</span><span class="p">.</span><span class="nx">selectedItem</span><span class="p">(</span><span class="nx">item</span><span class="p">);</span>
</span><span class='line'>            <span class="k">this</span><span class="p">.</span><span class="nx">itemForEditing</span><span class="p">(</span><span class="k">new</span> <span class="nx">Item</span><span class="p">(</span><span class="nx">ko</span><span class="p">.</span><span class="nx">toJS</span><span class="p">(</span><span class="nx">item</span><span class="p">)));</span>
</span><span class='line'>        <span class="p">},</span>
</span><span class='line'>
</span><span class='line'>        <span class="nx">acceptItem</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">item</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">selected</span> <span class="o">=</span> <span class="k">this</span><span class="p">.</span><span class="nx">selectedItem</span><span class="p">(),</span>
</span><span class='line'>                <span class="nx">edited</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">toJS</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">itemForEditing</span><span class="p">());</span> <span class="c1">//clean copy of edited</span>
</span><span class='line'>
</span><span class='line'>            <span class="c1">//apply updates from the edited item to the selected item</span>
</span><span class='line'>            <span class="nx">selected</span><span class="p">.</span><span class="nx">update</span><span class="p">(</span><span class="nx">edited</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>            <span class="c1">//clear selected item</span>
</span><span class='line'>            <span class="k">this</span><span class="p">.</span><span class="nx">selectedItem</span><span class="p">(</span><span class="kc">null</span><span class="p">);</span>
</span><span class='line'>            <span class="k">this</span><span class="p">.</span><span class="nx">itemForEditing</span><span class="p">(</span><span class="kc">null</span><span class="p">);</span>
</span><span class='line'>        <span class="p">},</span>
</span><span class='line'>
</span><span class='line'>        <span class="c1">//just throw away the edited item and clear the selected observables</span>
</span><span class='line'>        <span class="nx">revertItem</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>            <span class="k">this</span><span class="p">.</span><span class="nx">selectedItem</span><span class="p">(</span><span class="kc">null</span><span class="p">);</span>
</span><span class='line'>            <span class="k">this</span><span class="p">.</span><span class="nx">itemForEditing</span><span class="p">(</span><span class="kc">null</span><span class="p">);</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>So, we make edits to a copy of the original and on an accept we apply those edits back to the original. We can use <code>ko.toJS</code> to get a plain JavaScript object and feed it into our <code>update</code> function to apply the changes. In this scenario, the <code>revertItem</code> function can simply throw away the copied item and clear our the selected value.</p>

<iframe style="width: 100%; height: 350px" frameborder="0" seamless="seamless" src="http://jsfiddle.net/K3gJT/embedded/result,js,html,css/light/"></iframe>


<p><a href="http://jsfiddle.net/rniemeyer/K3gJT/">Link to sample on jsFiddle.net</a></p>

<p>If you were going to reuse this technique often, then you could even create an extension to an observableArray that adds the appropriate observables and functions off of the observableArray itself like in this <a href="http://jsfiddle.net/rniemeyer/MQVr3/">sample</a>.</p>

<h2>Updating from server</h2>

<p>Our <code>update</code> function is also a handy way to apply updates from the server to our existing view model. In our case, we would likely need to add an <code>id</code> to the <code>Item</code> objects, so that we can identify which object needs updating. This works very well with something like <a href="http://signalr.net">SignalR</a> or <a href="http://socket.io/">socket.io</a> to keep various clients in sync with each other. This is an easier pattern than trying to swap items in an array or update specific properties one by one.</p>

<h2>Summary</h2>

<p>Editors with accept/cancel options are a common scenario in a Knockout.js application. By separating the creation of observables/computeds from poplating their values, we can commit, reset, and update models by feeding a version of the data through our <code>update</code> function. When you think in terms of the plain JS object that you can get out of or put into a model, it makes many of these scenarios easy to handle.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Revisting Event Delegation in Knockout.js]]></title>
    <link href="http://www.knockmeout.net/2012/11/revisit-event-delegation-in-knockout-js.html"/>
    <updated>2012-11-19T20:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2012/11/revisiting-event-delegation-in-knockoutjs</id>
    <content type="html"><![CDATA[<p>Previously, I <a href="http://www.knockmeout.net/2011/04/event-delegation-in-knockoutjs.html">discussed</a> a technique to do event delegation in <a href="http://knockoutjs.com">Knockout.js</a>. That post was created before Knockout 2.0, which added the ability to use <code>ko.dataFor</code> and <code>ko.contextFor</code> to retrieve the data context related to a specific element (as described <a href="http://knockoutjs.com/documentation/unobtrusive-event-handling.html">here</a>).  With these new tools, there are now much better ways to add a single handler on a parent element that can respond to events triggered on its child elements.</p>

<p><em>Note: based on the techniques in this post, I created a plugin called <code>knockout-delegatedEvents</code> located here: <a href="https://github.com/rniemeyer/knockout-delegatedEvents">https://github.com/rniemeyer/knockout-delegatedEvents</a>.</em></p>

<h2>Why event delegation in Knockout.js?</h2>

<p>Currently when you use the <code>click</code> or <code>event</code> binding in Knockout, an event handler is attached directly to that element. Generally this is fine and causes no real problems. However, if you face a scenario where you have a large number of elements that require these bindings, then there can be a performance impact to creating and attaching these handlers to each element, especially in older browsers. For example, you may be creating a grid where each cell needs various event handlers or a hierarchical editor where you are potentially attaching handlers to interact with the parent items as well as each child (and each child may have children).</p>

<p>In this case, there are advantages to using event delegation:</p>

<ul>
<li>you only have to attach one (or a few) event handlers rather than one on each element. Events bubble up to the higher-level handler and can understand the original element that triggered it.</li>
<li>dynamically added content does not need new event handlers added to them (largely not an issue with KO bindings and templating)</li>
</ul>


<h2>Normal event delegation with KO 2.0+</h2>

<p>With Knockout 2.0+, the common way to use event delegation is to avoid attaching event handlers in the bindings themselves and add another layer of code to attach a single handler to a parent element using something like jQuery&rsquo;s <a href="http://api.jquery.com/on/">on</a> (previously <a href="http://api.jquery.com/live/">live</a>/<a href="http://api.jquery.com/delegate/">delegate</a>). So, rather than doing:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;ul</span> <span class="na">data-bind=</span><span class="s">&quot;foreach: items&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">&quot;#&quot;</span> <span class="na">data-bind=</span><span class="s">&quot;click: $root.selectItem, text: name&quot;</span><span class="nt">&gt;&lt;/a&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/li&gt;</span>
</span><span class='line'><span class="nt">&lt;/ul&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>You would instead do:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;ul</span> <span class="na">id=</span><span class="s">&quot;items&quot;</span> <span class="na">data-bind=</span><span class="s">&quot;foreach: items&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">&quot;#&quot;</span> <span class="na">data-bind=</span><span class="s">&quot;text: name&quot;</span><span class="nt">&gt;&lt;/a&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/li&gt;</span>
</span><span class='line'><span class="nt">&lt;/ul&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>and attach an event handler elsewhere like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">$</span><span class="p">(</span><span class="s2">&quot;#items&quot;</span><span class="p">).</span><span class="nx">on</span><span class="p">(</span><span class="s2">&quot;click&quot;</span><span class="p">,</span> <span class="s2">&quot;a&quot;</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="kd">var</span> <span class="nx">context</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">contextFor</span><span class="p">(</span><span class="k">this</span><span class="p">);</span> <span class="c1">//this is the element that was clicked</span>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span><span class="nx">context</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="nx">context</span><span class="p">.</span><span class="nx">$root</span><span class="p">.</span><span class="nx">selectItem</span><span class="p">(</span><span class="nx">context</span><span class="p">.</span><span class="nx">$data</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>Attaching a single handler like this works quite well. However, there are a few issues that I still have with this technique:</p>

<ul>
<li>you have another layer of code to manage besides your view model. This is the type of code that Knockout generally helps you get away from.</li>
<li>this code is tightly coupled (fairly) with this view&rsquo;s markup</li>
<li>in our example, if the entire <code>ul</code> is part of a template that gets swapped, then we would need to hook up our handler again or choose to add our handler at a higher level (possibly up to the <code>body</code>)</li>
<li>this particular code also adds a dependency on jQuery that is not really necessary</li>
</ul>


<p>In my perfect Knockout application, you have your view and your view model with the only code outside of that being a call to <code>ko.applyBindings</code>. To accomplish this, we would need to be able to wire it up declaratively in the view. I have been exploring a few ways to make this happen.</p>

<h2>Declaratively adding a handler</h2>

<p>The first step is attaching a handler on the parent or root element that will respond when events bubble up to it. This is pretty easy to accomplish with a custom binding. When the event is handled, we can determine the original element and use <code>ko.dataFor</code> or <code>ko.contextFor</code> to get the original data context and then execute some method.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="c1">//add a handler on a parent element that reponds to events from the children</span>
</span><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">bindingHandlers</span><span class="p">.</span><span class="nx">delegatedHandler</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">init</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">valueAccessor</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="c1">//array of events</span>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">events</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">unwrapObservable</span><span class="p">(</span><span class="nx">valueAccessor</span><span class="p">())</span> <span class="o">||</span> <span class="p">[];</span>
</span><span class='line'>        <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">arrayForEach</span><span class="p">(</span><span class="nx">events</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">registerEventHandler</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">event</span><span class="p">,</span> <span class="nx">createDelegatedHandler</span><span class="p">(</span><span class="nx">event</span><span class="p">,</span> <span class="nx">element</span><span class="p">));</span>
</span><span class='line'>        <span class="p">});</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>To create the handler, we take the target element and get its context:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="c1">//create a handler for a specific event like &quot;click&quot;</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">createDelegatedHandler</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">eventName</span><span class="p">,</span> <span class="nx">root</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">//return a handler</span>
</span><span class='line'>    <span class="k">return</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">el</span> <span class="o">=</span> <span class="nx">event</span><span class="p">.</span><span class="nx">target</span><span class="p">,</span>
</span><span class='line'>            <span class="nx">data</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">dataFor</span><span class="p">(</span><span class="nx">el</span><span class="p">),</span>
</span><span class='line'>            <span class="nx">action</span> <span class="o">=</span> <span class="nx">findAnAction</span><span class="p">(</span><span class="nx">el</span><span class="p">,</span> <span class="nx">context</span><span class="p">);</span> <span class="c1">//??? how do we know what method to call</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>        <span class="c1">//execute the action</span>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="nx">action</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="c1">//call it like KO normally would with the data being both the value of `this` and the first arg</span>
</span><span class='line'>            <span class="nx">result</span> <span class="o">=</span> <span class="nx">action</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="nx">data</span><span class="p">,</span> <span class="nx">data</span><span class="p">,</span> <span class="nx">event</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>            <span class="c1">//prevent the default action, unless the function returns true</span>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="nx">result</span> <span class="o">!==</span> <span class="kc">true</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>                <span class="k">if</span> <span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>                    <span class="nx">event</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
</span><span class='line'>                <span class="p">}</span>
</span><span class='line'>                <span class="k">else</span> <span class="p">{</span>
</span><span class='line'>                    <span class="nx">event</span><span class="p">.</span><span class="nx">returnValue</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>
</span><span class='line'>                <span class="p">}</span>
</span><span class='line'>            <span class="p">}</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">};</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>When used on an element, the binding would take in an array of events like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;ul</span> <span class="na">data-bind=</span><span class="s">&quot;delegatedHandler: [&#39;click&#39;, &#39;mouseover&#39;, &#39;mousedown&#39;]&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>...
</span><span class='line'><span class="nt">&lt;/ul&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>With this binding in place, we can handle the event, find the element that triggered the event, and determine the data context of the element. However, we still need to know what method to call. I looked at a few alternatives for this piece.</p>

<h2>Option #1 - using a binding</h2>

<p>On the child elements, we could use a binding that stores a reference to the function to call. The binding can use Knockout&rsquo;s <code>ko.utils.domData</code> functions to store and retrieve data on the element, as Knockout automatically cleans up this data whenever it removes elements from the document. For example, we could create a <code>delegatedClick</code> binding to make this association.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="c1">//associate a handler with an element that will be executed by the delegatedHandler</span>
</span><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">bindingHandlers</span><span class="p">.</span><span class="nx">delegatedClick</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">init</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">valueAccessor</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">action</span> <span class="o">=</span> <span class="nx">valueAccessor</span><span class="p">();</span>
</span><span class='line'>        <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">domData</span><span class="p">.</span><span class="nx">set</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="s2">&quot;ko_delegated_click&quot;</span><span class="p">,</span> <span class="nx">action</span><span class="p">);</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now, on a child element, you would associate a function like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;li&gt;</span>
</span><span class='line'>    <span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">&quot;#&quot;</span> <span class="na">data-bind=</span><span class="s">&quot;text: name, delegatedClick: $parent.selectItem&quot;</span><span class="nt">&gt;&lt;/a&gt;</span>
</span><span class='line'><span class="nt">&lt;/li&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>We could create additional bindings for other events that we are interested in and could even create a helper function to generate these bindings given an array of events that we need to handle.</p>

<h3>Pros</h3>

<ul>
<li>Can simply replace <code>click</code> bindings with <code>delegatedClick</code> (and other events) without any other changes</li>
<li>Can bind against specific functions and can execute code for cases where you need to call a function with a parameter to create a handler (<code>delegatedClick: $parent.createHandler('some_modifier')</code>)</li>
</ul>


<h3>Cons</h3>

<ul>
<li>The binding on the child elements is lightweight, but we still have to pay the overhead of parsing and executing a binding.</li>
</ul>


<h2>Option #2 - use a <code>data-</code> attribute with method name</h2>

<p>The first solution works well, but I still do not like having to pay the price of executing bindings on the child elements. For an alternative solution, I looked at a different approach where the child elements are tagged with a <code>data-eventName</code> attribute that contains the method name.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;li&gt;</span>
</span><span class='line'>    <span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">&quot;#&quot;</span> <span class="na">data-click=</span><span class="s">&quot;selectItem&quot;</span> <span class="na">data-bind=</span><span class="s">&quot;text: name&quot;</span><span class="nt">&gt;&lt;/a&gt;</span>
</span><span class='line'><span class="nt">&lt;/li&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>With this technique we would no longer need the child bindings. In the event handling code, we would now need to locate a method that matches our <code>data-eventName</code> attribute value.  This time we can use <code>ko.contextFor</code> to get back the entire <a href="http://knockoutjs.com/documentation/binding-context.html">binding context</a>. It is very common to call functions off of <code>$parent</code> or <code>$root</code> as well as off of the current data itself, so the <code>$parents</code> array allows us to walk up the scope chain to locate an appropriate method.</p>

<h3>Pros</h3>

<ul>
<li>No overhead of executing a binding on the child elements</li>
<li>Can execute the function with the correct owner, so we do not need to use <code>.bind</code> or <code>var self = this;</code> to ensure that the context is correct. This is a really nice benefit, we have to search for the method in each scope, so we know the appropriate owner of the method to use as the context.</li>
</ul>


<h3>Cons</h3>

<ul>
<li>could run into issues with clashing names (child has an <code>add</code> method, but you wanted to call parent&rsquo;s <code>add</code>)</li>
<li>cannot execute code to create a handler, as the attribute value would be a string that needs to match a method name</li>
</ul>


<h2>Option #3 - associate method and name in root/global object</h2>

<p>Another alternative might be to use the <code>data-</code> attribute, but use the string to key into an object that holds the associations between names and actions. Perhaps something like <code>ko.actions</code> or <code>ko.commands</code>. This object could hold just function references or maybe a function and owner. For arrays of objects, we would not be able to indicate an appropriate owner, so we would have to fall back to making sure that the function is properly bound on each instance. For example, we could even give the function an alias of <code>select</code> like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">actions</span><span class="p">.</span><span class="nx">select</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">action</span><span class="o">:</span> <span class="k">this</span><span class="p">.</span><span class="nx">selectItem</span><span class="p">,</span>
</span><span class='line'>    <span class="nx">owner</span><span class="o">:</span> <span class="k">this</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<h3>Pros</h3>

<ul>
<li>No overhead of executing a binding on the child elements</li>
<li>No issues with ambiguity in names, as names can be aliased</li>
<li>Functions outside of a view model could be included</li>
<li>Could dynamically change the definition of the action</li>
</ul>


<h3>Cons</h3>

<ul>
<li>have to manage adding (and maybe removing) functions to this object</li>
<li>different types of objects with the same method names would have to be aliased with unique names in this object</li>
</ul>


<h2>Summary</h2>

<p>In cases where you need to attach a large number of event handlers, using event delegation can be a nice win. Attaching these handlers declaratively provides an alternative to wiring this up outside of your view/viewmodel. While considering each of the techniques to determine the function to execute, I was leaning towards #2, as it does not require the child bindings and as a bonus gets the context right when it calls the handler. Instead though, I decided to create a plugin that can use all of these techniques interchangeably. The plugin lives at: <a href="http://github.com/rniemeyer/knockout-delegatedEvents">http://github.com/rniemeyer/knockout-delegatedEvents</a>. Please let me know if you have feedback or suggestions for the plugin.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Knockout.js 2.2 is out now!]]></title>
    <link href="http://www.knockmeout.net/2012/10/knockout-2-dot-2-is-out.html"/>
    <updated>2012-10-29T20:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2012/10/knockout-2-dot-2-is-out</id>
    <content type="html"><![CDATA[<p>Just a quick note that <a href="http://knockoutjs.com">Knockout</a> 2.2 is now available. You can read more about the details of this release in the <a href="https://groups.google.com/d/topic/knockoutjs/kP3IaZ6tqus/discussion">announcement</a> or Steve Sanderson&rsquo;s blog <a href="http://blog.stevensanderson.com/2012/10/29/knockout-2-2-0-released/">post</a>.</p>

<p>Here are a few of my favorite changes:</p>

<ul>
<li>The <code>css</code> binding can either toggle specific classes on and off like (<code>css: { error: hasError, required: isRequired }</code>) or now add one or more classes dynamically like <code>css: someClassOrClasses</code>. This is handy when the class names are dynamic. Previously, you could do something similar with the <code>attr</code> binding against the class attribute, but it would overwrite the class attribute completely. When using the <code>css</code> binding in this way, it will now preserve existing classes and will properly remove any class or classes that were previously added by the binding when the value changes.</li>
<li>The <code>if</code> and <code>ifnot</code> bindings now only re-render their contents when the bound value changes between truthy and falsy. This helps to alleviate the performance issue described in the first half of this <a href="http://www.knockmeout.net/2012/03/knockoutjs-performance-gotcha-1ifwith.html">post</a>.</li>
<li>There is a new <code>peek</code> function available on <code>observables</code> and <code>computed observables</code>. This allows you to retrieve its value without creating a dependency. This definitely can be useful when you want tight control over when bindings and other subscriptions are triggered, but I would use caution as it does circumvent the normal dependency tracking mechanism. If you find that you need this functionality, then you probably have a good reason why you don&rsquo;t want a dependency and would understand what does and doesn&rsquo;t trigger updates.</li>
<li>The <code>foreach</code> binding and the <code>foreach</code> option of the <code>template</code> binding now try to understand if items have been moved and will relocate the content rather than tearing it down and re-rendering it at its new position. This comes with some new callbacks (<code>beforeMove</code> and <code>afterMove</code>).</li>
<li>The <code>ko</code> variable is now available from within bindings, even if <code>ko</code> is not a global variable (common in AMD scenarios).</li>
</ul>


<p>You can download the 2.2 files from <a href="https://github.com/SteveSanderson/knockout/downloads">here</a>. There were no intentional breaking changes made in 2.2 (unless someone was relying on an existing bug), so if you have any issues with your application not behaving as it did in 2.1, please log an issue <a href="https://github.com/SteveSanderson/knockout/issues">here</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Getting the Most Out of Knockout.js Session From Twin Cities Code Camp]]></title>
    <link href="http://www.knockmeout.net/2012/10/twincitiescodecamp-2012-session.html"/>
    <updated>2012-10-09T20:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2012/10/twin-cities-code-camp-knockout-talk</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://www.knockmeout.net/images/posts/tccc.jpg" width="435" height="326" title="Photo by @JudahGabriel" ></p>

<p>Last weekend, I was invited to talk about <a href="http://knockout.js">Knockout.js</a> at <a href="http://twincitiescodecamp.com">Twin Cities Code Camp</a>. It was a very enjoyable day, as I saw several great presentations and had a chance to talk to many Knockout users.</p>

<p>I was told that there had been several sessions in the past that touched on Knockout, so for this talk I decided to focus on some tips, tricks, and techniques that can be used to get the most out of Knockout. The topics covered included:</p>

<ul>
<li>Brief introduction to Knockout</li>
<li>Getting data in and out</li>
<li>Extending Knockout&rsquo;s structures</li>
<li>Custom Bindings</li>
<li>Performance tips</li>
</ul>


<p>There was a small amount of overlap with the <a href="http://www.knockmeout.net/2012/08/thatconference-2012-session.html">session</a> that I did at <a href="http://thatConference.com">ThatConference</a> in August, but all of the samples were new for this talk. The project that I used to give the presentation is also described in the ThatConference <a href="http://www.knockmeout.net/2012/08/thatconference-2012-session.html">post</a> and a reference project lives <a href="https://github.com/rniemeyer/SamplePresentation">here</a>.</p>

<p>Here is a screencast of the presentation:</p>

<iframe src="http://player.vimeo.com/video/51103092" width="500" height="335" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>


<p> <p><a href="http://vimeo.com/51103092">Getting the Most Out of Knockout.js - 10/06/2012 - Twin Cities Code Camp</a></p></p>

<p>A few clarifications from the presentation:</p>

<ul>
<li>At the end of the &ldquo;getting data out&rdquo; part, I had typed <code>var meta</code> instead of <code>this.meta</code>.</li>
<li>In the <code>maxLength</code> extender, I used a writeable computed observable. In the <code>write</code> function, I should have written the new value to our observable (<code>original(newValue);</code>), in addition to checking its length.</li>
<li>In the <code>enterKey</code> custom binding, you probably would want to return the result of the actual function call, as when you return <code>true</code> from a handler called by the <code>event</code> binding, it will allow the default action to proceed, which can be useful at times.</li>
<li>In the <code>modal</code> binding where we add a handler for the <code>hidden</code> event, you may want to check if what you are dealing with can be written to as an observable (is an observable or writeable computed observable) by calling <code>ko.isWriteableObservable</code>. So, we might want to call <code>ko.isWriteableObservable(data)</code> before doing <code>data(null)</code>.</li>
<li>In the <code>modal</code> binding, the wrappers to the <code>with</code> binding, should really be written with <code>with</code> quoted like <code>return ko.bindingHandlers['with'].init.apply(this, arguments);</code> and <code>return ko.bindingHandlers['with'].update.apply(this, arguments);</code>. In IE &lt; 9 the use of <code>with</code> as a property name will cause an error, as it is a JavaScript keyword.</li>
</ul>


<p>Participating in the code camp was definitely worth the effort of traveling up to the Twin Cities. I would be happy to hear any type of feedback on the presentation. Photo by <a href="https://twitter.com/JudahGabriel/">@JudahGabriel</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Extending Knockout.js Session From ThatConference]]></title>
    <link href="http://www.knockmeout.net/2012/08/thatconference-2012-session.html"/>
    <updated>2012-08-15T20:35:00+00:00</updated>
    <id>http://www.knockmeout.net/2012/08/that-conference-knockout-talk</id>
    <content type="html"><![CDATA[<p><img class="right" src="http://www.knockmeout.net/images/posts/speaking.jpg" width="240" height="320" title="ThatConference" ></p>

<p>I had a wonderful time at <a href="http://thatConference.com">ThatConference</a> this week. It was really special to be in a place with so many people that are passionate about the same types of things that I am.
I also had the pleasure of giving a talk about Knockout. The session mainly focused on the various extensibility points in Knockout. After reviewing some Knockout basics, I discussed extending observables, creating custom bindings, and the idea of binding providers.</p>

<p>For the presentation, I knew that I wanted to show a lot of code, but I was not too excited about continually flipping between a slide show, an IDE, and a browser.  So, I decided to create a slideshow from scratch with Knockout that let me combine all three pieces into a single page app.  It was quite a bit of work, but it was a fun experience overall.</p>

<p>Here is a screencast of the presentation:</p>

<iframe src="http://player.vimeo.com/video/47567244" width="500" height="313" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>


<p> <p><a href="http://vimeo.com/47567244">Extending Knockout.js - 08/14/2012 - ThatConference</a></p>

<p>For creating the presentation app, I used these libraries:</p>

<ul>
<li><a href="http://knockoutjs.com">Knockout</a></li>
<li><a href="http://requirejs.org">require.js</a> &amp; the <a href="https://github.com/requirejs/text">text plugin</a> - for managing dependencies and dynamically loading view models, templates, and code samples.</li>
<li><a href="http://codemirror.net/">CodeMirror</a> - for the code editor</li>
<li><a href="http://jQuery.com">jQuery</a> - just for some animations</li>
<li><a href="http://jsplumb.org/jquery/demo.html">jqPlumb</a> - for drawing lines between two elements</li>
</ul>


<p>Here is a repository with a heavily stripped down version of the app that I created for this presentation <a href="https://github.com/rniemeyer/SamplePresentation">https://github.com/rniemeyer/SamplePresentation</a>.</p>

<p>The binding provider sample implementation is also available here <a href="https://github.com/rniemeyer/knockout-classBindingProvider">https://github.com/rniemeyer/knockout-classBindingProvider</a>.</p>

<p>I would love to hear any feedback on the presentation. Also, I was thinking about the possibility of recording some short (&lt; 10 minutes) screencasts on various Knockout topics. Would there be any interest in something like that?</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Knockout.js Performance Gotcha #3 - all bindings fire together]]></title>
    <link href="http://www.knockmeout.net/2012/06/knockoutjs-performance-gotcha-3-all-bindings.html"/>
    <updated>2012-06-22T23:55:00+00:00</updated>
    <id>http://www.knockmeout.net/2012/06/performance-gotcha-3-bindings-fired-together</id>
    <content type="html"><![CDATA[<h2>How bindings are processed</h2>

<p><em>Update: In Knockout 3.0, bindings are now fired independently on a single element, so this is no longer an issue for KO 3.0+.</em></p>

<p>When using multiple bindings on a single element, it is important to understand how Knockout triggers updates to bindings to avoid potential performance issues. For example, a common binding might look like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;select</span> <span class="na">data-bind=</span><span class="s">&quot;options: choices, value: selectedValue, visible: showChoices&quot;</span><span class="nt">&gt;&lt;/select&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>How are the bindings on this element processed? When Knockout determines that an element has bindings, a computed observable is created to aid in tracking dependencies. Inside the context of this computed observable, Knockout parses the <code>data-bind</code> attribute&rsquo;s value to determine which bindings to run and the arguments to pass. As the <code>init</code> and <code>update</code> functions for each binding are executed, the computed observable takes care of accumulating dependencies on any observables that have their value accessed.</p>

<p>Here is a simplified flow chart of the binding execution:</p>

<p><img src="http://www.knockmeout.net/images/posts/bindings.png"></p>

<p>There are a couple of important points to understand here:</p>

<ul>
<li><p>The <code>init</code> function for each binding is only executed once.  However, currently this does happen inside the computed observable that was created to track this element&rsquo;s bindings.  This means that you can trigger the binding to run again (only it&rsquo;s <code>update</code> function) based on a dependency created during initialization.  Since, the <code>init</code> function won&rsquo;t run again, this dependency will likely be dropped on the second execution (unless it was also accessed in the <code>update</code> function).</p></li>
<li><p>There is currently only <strong>one</strong> computed observable used to track <em>all</em> of an element&rsquo;s bindings.  This means that the <code>update</code> function for <em>all</em> of an element&rsquo;s bindings will run again when any of the dependencies are updated.</p></li>
</ul>


<p>This is definitely something to consider when writing custom bindings where your <code>update</code> function does a significant amount of work. Whenever bindings are triggered for the element, your <code>update</code> function will run, even if none of its observables were triggered. If possible, it is a good idea to check if you need to do work, before actually executing your <code>update</code> logic.</p>

<h2>Common problems with the default bindings</h2>

<p>1- A common scenario where this can cause an issue is when using the <code>template</code> binding in conjunction with other bindings. For example, you may attach a <code>visible</code> binding along with a <code>template</code> binding like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">data-bind=</span><span class="s">&quot;visible: showPlaylist, template: { name: &#39;playlistTmpl&#39;, data: playlist }&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p> In this case, if <code>showPlaylist</code> is frequently updated, it will cause the <code>template</code> binding to re-render the template again. In some cases, this may not cause a concern (it would just behave like the <code>if</code> binding). However, in a scenario where the template has significant markup and the <code>visible</code> binding&rsquo;s condition is frequently triggered this can cause an unnecessary performance hit. Note that when using the <code>foreach</code> option or binding, logic is executed to determine if any items were added or removed, so it will cause less of a performance hit in that case.</p>

<p>2- Another place where this can come into play with the default bindings is when using the <code>options</code> and <code>value</code> bindings together.  The <code>update</code> function of the <code>options</code> binding rebuilds the list of option tags for the select element. Whenever the <code>value</code> is updated, it will trigger all of the bindings on the element to execute.  So, instead of just setting the appropriate value, it will rebuild all of the options and then set the value.  If you have a situation where you have a large number of options, then this can cause a performance issue.</p>

<h2>Ways to address this concern</h2>

<p>1- In some cases, it makes sense to put bindings on separate elements or on a container element.  For example, you may be able to move a frequently triggered <code>visible</code> binding to a parent element rather
have it coupled with other bindings like the <code>template</code> binding.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">data-bind=</span><span class="s">&quot;visible: showPlaylist&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;div</span> <span class="na">data-bind=</span><span class="s">&quot;template: { name: &#39;playlistTmpl&#39;, data: playlist }&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span><span class='line'><span class="nt">&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here is a sample showing a <code>visible</code> and <code>template</code> binding on the same and different elements:</p>

<iframe style="width: 100%; height: 400px" frameborder="0" seamless="seamless" src="http://jsfiddle.net/jUsup/embedded/result,js,html,css/light/"></iframe>


<p>2- In the case of the <code>options</code> and <code>value</code> bindings, you can choose to build your option elements separately. It would be nice to just use a containerless <code>foreach</code> statement inside of a <code>select</code> element, but Internet Explorer will remove comments that it finds between <code>select</code> and <code>option</code> elements. An alternative would be to use Michael Best&rsquo;s <a href="https://github.com/mbest/knockout-repeat">repeat</a> binding on the <code>option</code> element like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;select</span> <span class="na">data-bind=</span><span class="s">&quot;value: selectedOption&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;option</span> <span class="na">data-bind=</span><span class="s">&quot;repeat: {foreach: items, bind: &#39;attr: { value: $item().id }, text: $item().name&#39;}&quot;</span><span class="nt">&gt;</span>
</span><span class='line'><span class="nt">&lt;/select&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>3- A more advanced way to handle these issues, is to create your own computed observable in the <code>init</code> function to handle updates yourself. Any observables accessed in your computed observable, will not be a dependency of the overall computed observable used to track all of the element&rsquo;s bindings.</p>

<p>This is a technique that I tend to use by default in any bindings that I write. It is also useful when you want a single binding to accept multiple observable options and you want to respond separately to each one changing (as opposed to using the <code>update</code> function to repond when any observable changes).  You can even wrap the existing bindings in this way to create an <code>isolatedOptions</code> binding.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">bindingHandlers</span><span class="p">.</span><span class="nx">isolatedOptions</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">init</span><span class="o">:</span> <span class="kd">function</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">valueAccessor</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">args</span> <span class="o">=</span> <span class="nx">arguments</span><span class="p">;</span>
</span><span class='line'>        <span class="nx">ko</span><span class="p">.</span><span class="nx">computed</span><span class="p">({</span>
</span><span class='line'>            <span class="nx">read</span><span class="o">:</span>  <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>               <span class="nx">ko</span><span class="p">.</span><span class="nx">utils</span><span class="p">.</span><span class="nx">unwrapObservable</span><span class="p">(</span><span class="nx">valueAccessor</span><span class="p">());</span>
</span><span class='line'>               <span class="nx">ko</span><span class="p">.</span><span class="nx">bindingHandlers</span><span class="p">.</span><span class="nx">options</span><span class="p">.</span><span class="nx">update</span><span class="p">.</span><span class="nx">apply</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="nx">args</span><span class="p">);</span>
</span><span class='line'>            <span class="p">},</span>
</span><span class='line'>            <span class="nx">owner</span><span class="o">:</span> <span class="k">this</span><span class="p">,</span>
</span><span class='line'>            <span class="nx">disposeWhenNodeIsRemoved</span><span class="o">:</span> <span class="nx">element</span>
</span><span class='line'>        <span class="p">});</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>A few notes on this technique:</p>

<ul>
<li>The idea is that we want to trap our dependencies in our own isolated computed observable.</li>
<li>We call the update function of the <code>options</code> binding using <code>.apply</code> with the original arguments that were passed ot the binding.</li>
<li>The <code>disposeWhenNodeIsRemoved</code> option ensures that this computed observable will be destroyed if Knockout removes our element, like in a templating scenario.</li>
<li>There is one minor issue with using this technique currently: observables that are accessed in the actual binding string are included in the overall computed observable during parsing rather than when you create you call <code>valueAccessor</code>. This means that if your binding contains an expression where you access the observable&rsquo;s value (<code>text: 'Hello ' + name()</code>) , then it will be tracked in the overall computed observable. This is likely to change in the near future.</li>
</ul>


<p>Here is a sample that shows using #2 and #3 with <code>options</code> and <code>value</code> bindings: <a href="http://jsfiddle.net/rniemeyer/QjVNX/">http://jsfiddle.net/rniemeyer/QjVNX/</a></p>

<h2>Future</h2>

<p>There has been some thought and work put into running each binding in the context of its own computed observable. <a href="https://github.com/mbest">Michael Best</a> has this working properly in his Knockout <a href="https://github.com/mbest/knockout">fork</a>. As these changes can be considered breaking, they will likely be carefully implemented over time using an opt-in approach, perhaps until a major version allows us to make some potentially breaking changes.  For now, it is wise to keep in mind how your bindings are triggered and how that affects other bindings on the same element.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using KO's native PubSub for decoupled synchronization]]></title>
    <link href="http://www.knockmeout.net/2012/05/using-ko-native-pubsub.html"/>
    <updated>2012-05-29T23:55:00+00:00</updated>
    <id>http://www.knockmeout.net/2012/05/using-kos-native-pub-slash-sub-for-decoupled-synchronization</id>
    <content type="html"><![CDATA[<p>In the previous <a href="http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html">post</a>, I suggested some ideas for binding against multiple view models in <a href="http://knockoutjs.com">Knockout.js</a>. When working with more than one view model, a common task is deciding how to communicate between the separate components. Creating direct references between them often doesn&rsquo;t feel right and can lead you down a path where each view model has lost its independence and cannot be used effectively without the other objects.</p>

<p>To handle this situation, we can keep our components loosely coupled by using a messaging system where each view model or component does not need to have direct references to its counterparts. There are several benefits to using this technique:</p>

<ul>
<li>Components remain independent. They can be developed, tested, and used in isolation.</li>
<li>Knockout view models and non-KO components can communicate using a common interface without direct knowledge of each other.</li>
<li>Components can be safely refactored. Properties can be renamed, moved, and adjusted without worrying about breaking compatibility.</li>
</ul>


<h2>Knockout&rsquo;s native pub/sub</h2>

<p>There are already many libraries and options for providing this type of message bus. One option might be triggering custom events or using great pub/sub libraries like <a href="http://amplifyjs.com/api/pubsub/">amplify.js</a> or <a href="https://github.com/ifandelse/postal.js">postal.js</a>. While these libraries provide robust capabilities, Knockout itself already has all of the tools to do basic pub/sub communication built-in. This is part of the <a href="http://knockoutjs.com/documentation/fn.html">ko.subscribable</a> type, which has its capabilities added to <code>observables</code>, <code>computed observables</code>, and <code>observableArrays</code>.</p>

<p>Normally, you would not construct a <code>ko.subscribable</code> directly, but it is easy enough to do so:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">var</span> <span class="nx">postbox</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">subscribable</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<p>In Knockout 2.0, support was added for <a href="http://www.knockmeout.net/2011/11/knockout-13-release-candidate-new.html">topic-based subscriptions</a> to aid in sending out <em>beforeChange</em> notifications. To create a topic-based subscription against our <code>ko.subscribable</code>, we would simply do:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">postbox</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="nx">callback</span><span class="p">,</span> <span class="nx">target</span><span class="p">,</span> <span class="nx">topic</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//with some actual code</span>
</span><span class='line'><span class="nx">postbox</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">newValue</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">latestTopic</span><span class="p">(</span><span class="nx">newValue</span><span class="p">);</span>
</span><span class='line'><span class="p">},</span> <span class="nx">vm</span><span class="p">,</span> <span class="s2">&quot;mytopic&quot;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>To send out a notification on this topic we would do:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">postbox</span><span class="p">.</span><span class="nx">notifySubscribers</span><span class="p">(</span><span class="nx">value</span><span class="p">,</span> <span class="s2">&quot;mytopic&quot;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now, we can do basic pub/sub messaging using <code>subscribe</code> and <code>notifySubscribers</code> against our mediator, the <code>postbox</code> object. However, whenever I explore integrating a new technique with Knockout, I try to consider how to make it feel as easy and natural as possible.</p>

<h2>Extending Observables</h2>

<p>A typical scenario for this type of functionality would be that we want to synchronize an observable between view models. This might be a one-way or even a two-way conversation. To make this easy, we can look at <a href="http://knockoutjs.com/documentation/fn.html">extending</a> the <code>ko.subscribable</code> type, which would affect <code>observables</code>, <code>observableArrays</code>, and <code>computed observables</code>.</p>

<p>Suppose that we want to setup an observable to automatically publish on a topic whenever it changes. We would want to set up a manual subscription against that observable and then use <code>notifySubscribers</code> on our <code>postbox</code>.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">subscribable</span><span class="p">.</span><span class="nx">fn</span><span class="p">.</span><span class="nx">publishOn</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">topic</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">newValue</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="nx">postbox</span><span class="p">.</span><span class="nx">notifySubscribers</span><span class="p">(</span><span class="nx">newValue</span><span class="p">,</span> <span class="nx">topic</span><span class="p">);</span>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">return</span> <span class="k">this</span><span class="p">;</span> <span class="c1">//support chaining</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//usage of publishOn</span>
</span><span class='line'><span class="k">this</span><span class="p">.</span><span class="nx">myObservable</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">(</span><span class="s2">&quot;myValue&quot;</span><span class="p">).</span><span class="nx">publishOn</span><span class="p">(</span><span class="s2">&quot;myTopic&quot;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now, whenever the observable&rsquo;s value changes, it will publish a message on the topic.</p>

<p>On the other side, we might want to make it easy for an observable to update itself from messages on a topic. We can use this same concept:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">ko</span><span class="p">.</span><span class="nx">subscribable</span><span class="p">.</span><span class="nx">fn</span><span class="p">.</span><span class="nx">subscribeTo</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">topic</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">postbox</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="kc">null</span><span class="p">,</span> <span class="nx">topic</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">return</span> <span class="k">this</span><span class="p">;</span>  <span class="c1">//support chaining</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//usage</span>
</span><span class='line'><span class="k">this</span><span class="p">.</span><span class="nx">observableFromAnotherVM</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">().</span><span class="nx">subscribeTo</span><span class="p">(</span><span class="s2">&quot;myTopic&quot;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Notice that we can just pass <code>this</code> (the observable) in as the callback to the <code>subscribe</code> function. We know that an observable is a function and that it will have its value set when you pass an argument into the function.  So, there is no need to write something like:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="c1">//no need to add an extra anonymous function like:</span>
</span><span class='line'><span class="nx">postbox</span><span class="p">.</span><span class="nx">subscribe</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">newValue</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">this</span><span class="p">(</span><span class="nx">newValue</span><span class="p">);</span>
</span><span class='line'><span class="p">},</span> <span class="k">this</span><span class="p">,</span> <span class="nx">topic</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now, our observables can exchange information without direct references to each other. They do need to agree on a topic, but do not have any knowledge about the internals of the other view model or component. We can even mock or simulate the other components in testing scenarios by firing messages.</p>

<h2>Potential gotcha: publishing objects</h2>

<p>If the new value being published is an object, then we need to be careful, as both sides will have a reference to the same object. If code from multiple view models makes changes to that object, then we are likely no longer as decoupled as we would like. If the object is simply configuration/options passed as an object literal that are not modified, then this seems okay. Otherwise, it is preferable to stick to primitives in the values being published. Another alternative is to use something like <code>ko.toJS</code> to create a deep-copy of the object that is being published, so neither side has the same reference.</p>

<h2>A new library: knockout-postbox</h2>

<p>I created a small <a href="https://github.com/rniemeyer/knockout-postbox">library</a> called <strong>knockout-postbox</strong> to handle this type of communication. It uses the techniques described above and adds a bit of additional functionality:</p>

<ul>
<li>creates a <code>ko.postbox</code> object with clean <code>subscribe</code> and <code>publish</code> methods that take a topic as the first argument.</li>
<li>adds a <code>subscribeTo</code> function to all subscribables (observables, observableArrays, and computed observables). The <code>subscribeTo</code> function also allows you to initialize your observable from the latest published value and allows you to pass a transform function that runs on the incoming values.</li>
<li>adds an <code>unsubcribeFrom</code> function to all subscribables that removes subscriptions created by <code>subscribeTo</code>.</li>
<li>adds a <code>publishOn</code> function to all subscribables that automatically publishes out new values. The <code>publishOn</code> function also allows you to control whether you want to immediately publish the initial value, and lets you supply an override function (<code>equalityComparer</code>) that allows you to compare the old and new values to determine if the new value should really be published.</li>
<li>adds a <code>stopPublishingOn</code> function to all subscribables that removes the subscription that handles the <code>publishOn</code> messages.</li>
<li>adds a <code>syncWith</code> function that does both a <code>subscribeTo</code> and a <code>publishOn</code> on the same topic for two-way synchronization.</li>
</ul>


<p>Project link: <a href="https://github.com/rniemeyer/knockout-postbox">https://github.com/rniemeyer/knockout-postbox</a></p>

<p><em>Basic sample:</em></p>

<iframe style="width: 100%; height: 350px" frameborder="0" seamless="seamless" src="http://jsfiddle.net/mg3hj/embedded/result,js,html,css/light/"></iframe>


<p><a href="http://jsfiddle.net/rniemeyer/mg3hj/">Link to sample on jsFiddle.net</a></p>

<p><em>Next post: using this concept to integrate with client-side routing in a way that is natural to Knockout</em></p>
]]></content>
  </entry>
  
</feed>
