<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>LINQ to Fail</title><link>http://www.aaron-powell.com/blog</link><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/LinqToAaronPowell" /><description>.net, C#, asp.net, umbraco</description><language>en</language><lastBuildDate>Tue, 24 Jan 2012 12:04:36 PST</lastBuildDate><feedburner:info uri="linqtoaaronpowell" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><creativeCommons:license>http://creativecommons.org/licenses/by/2.0/</creativeCommons:license><feedburner:emailServiceId>LinqToAaronPowell</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item><title>Macros in packages</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/zGGLxNp3xz4/macros-in-packages</link><category>umbaco</category><category>umbraco-5</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Tue, 24 Jan 2012 12:04:36 PST</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/umbraco/macros-in-packages</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>So you're working on an Umbraco 5 package and you want to be able to ship your own Macro with it. Seems like a common scenario you want to do yeah? It's something that's possible in v4 right? So how do you go about doing it in v5?</p>

<h2>Some background</h2>

<p>In v4 Macros were a bit of a pain to ship, in case you didn't know they were stored in the database and their data model was... less than ideal mainly as they evolved from being XSLT components to also supporting .NET, Iron* and eventually Razor.</p>

<p>Well here's a fun fact about v5 Macros <strong>they aren't in the database</strong>, Macros in v5 are actually stored in Hive. Out of the box they will be run of the file system Hive provider but since they are in Hive you could (in theory) stick them into the Database, on a FTP or anywhere crazy that you want. But really, them being on the file system is pretty fantastic as it means that it's really easy to include them in Source Control, something that was a huge problem with the Umbraco projects I'd worked with in the past.</p>

<p>You will find your macros (by default) at the location <code>~/App_Data/Umbraco/Macros</code> and this contains a serialized XML version of your macro, which looks a lot like the exported Macro definitions in v4, just not quite as confusing. Also this is a configuration value that comes from the <code>/configuration/umbraco/macros[@rootPath]</code> section of the web.config. Again this is something that you can change but you probably shouldn't :P.</p>

<h2>Installing Macros from your package</h2>

<p>In my <a href="http://www.aaron-powell.com/umbraco/creating-an-installer-task">last post</a> I introduced tasks and again this is what you'll want to use to install your macro with your package.</p>

<p>The first thing you want to do is copy your macro file from the Macros folder into somewhere that'll include it in your package. I use a folder called <strong>Macros</strong> that sites at the root of my package, but it's ultimately a personal preference thing so you can put that folder anywhere inside your package.</p>

<p><em>Side note Matt Brailsford has a great post on <a href="http://blog.mattbrailsford.com/2011/09/30/automating-umbraco-v5-package-creation-using-msbuild/">how to create v5 packages</a>, a must-read until there's a UI to do it.</em></p>

<p>Part of the v5 source includes a task that can help you with this and it's called <code>CopyFileTask</code> and it allows you to copy a single file from one location to another. You'll see this task used as part of the <em>DevDataset</em> that's shipping with the RC builds but what you want to do is something like this:</p>

<pre><code>  &lt;add type="Umbraco.Cms.Web.Tasks.CopyFileTask, Umbraco.Cms.Web.Tasks" trigger="post-package-install"&gt;
    &lt;parameter name="source" value="Macros/MyMacro.macro" /&gt;
    &lt;parameter name="destination" value="~/App_Data/Umbraco/Macros/MyMacro.macro" /&gt;
  &lt;/add&gt;
</code></pre>

<p>Adding that to your web.config in your packages (as described in my last post) will copy the file from the <strong>Macros</strong> folder in your package (or what ever folder you've put them into) to the Umbraco Macros folder.</p>

<h2>Conclusion</h2>

<p><strong>Yes, that's it.</strong></p>

<p>Seriously, it's so much easier to ship Macros in v5 that v4 and the fact that they are running off disk (don't be a dick and use some crazy Hive provider for them like Examine!) makes installing them as simple as copying a file.</p>

<p>But I think there's some room for improvements around this still and as I work on my v5 tasks set I'm going to be doing a simpler task for installing Macros, but in the meantime the above will work nicely <strong>today</strong>.</p>
<img src="http://www.aaron-powell.com/via-feed/umbraco/macros-in-packages" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fumbraco%2fmacros-in-packages&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=zGGLxNp3xz4:XlE7hYKPdgo:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=zGGLxNp3xz4:XlE7hYKPdgo:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=zGGLxNp3xz4:XlE7hYKPdgo:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/zGGLxNp3xz4" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;So you're working on an Umbraco 5 package and you want to be able to ship your own Macro with it. Seems like a common scenario you want to do yeah? It's something that's possible in v4 right? So how do you go about doing it in v5?&lt;/p&gt;

&lt;h2&gt;Some background&lt;/h2&gt;

&lt;p&gt;In v4 Macros were a bit of a pain to ship, in case you didn't know they were stored in the database and their data model was... less than ideal mainly as they evolved from being XSLT components to also supporting .NET, Iron* and eventually Razor.&lt;/p&gt;

&lt;p&gt;Well here's a fun fact about v5 Macros &lt;strong&gt;they aren't in the database&lt;/strong&gt;, Macros in v5 are actually stored in Hive. Out of the box they will be run of the file system Hive provider but since they are in Hive you could (in theory) stick them into the Database, on a FTP or anywhere crazy that you want. But really, them being on the file system is pretty fantastic as it means that it's really easy to include them in Source Control, something that was a huge problem with the Umbraco projects I'd worked with in the past.&lt;/p&gt;

&lt;p&gt;You will find your macros (by default) at the location &lt;code&gt;~/App_Data/Umbraco/Macros&lt;/code&gt; and this contains a serialized XML version of your macro, which looks a lot like the exported Macro definitions in v4, just not quite as confusing. Also this is a configuration value that comes from the &lt;code&gt;/configuration/umbraco/macros[@rootPath]&lt;/code&gt; section of the web.config. Again this is something that you can change but you probably shouldn't :P.&lt;/p&gt;

&lt;h2&gt;Installing Macros from your package&lt;/h2&gt;

&lt;p&gt;In my &lt;a href="http://www.aaron-powell.com/umbraco/creating-an-installer-task"&gt;last post&lt;/a&gt; I introduced tasks and again this is what you'll want to use to install your macro with your package.&lt;/p&gt;

&lt;p&gt;The first thing you want to do is copy your macro file from the Macros folder into somewhere that'll include it in your package. I use a folder called &lt;strong&gt;Macros&lt;/strong&gt; that sites at the root of my package, but it's ultimately a personal preference thing so you can put that folder anywhere inside your package.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Side note Matt Brailsford has a great post on &lt;a href="http://blog.mattbrailsford.com/2011/09/30/automating-umbraco-v5-package-creation-using-msbuild/"&gt;how to create v5 packages&lt;/a&gt;, a must-read until there's a UI to do it.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Part of the v5 source includes a task that can help you with this and it's called &lt;code&gt;CopyFileTask&lt;/code&gt; and it allows you to copy a single file from one location to another. You'll see this task used as part of the &lt;em&gt;DevDataset&lt;/em&gt; that's shipping with the RC builds but what you want to do is something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &amp;lt;add type="Umbraco.Cms.Web.Tasks.CopyFileTask, Umbraco.Cms.Web.Tasks" trigger="post-package-install"&amp;gt;
    &amp;lt;parameter name="source" value="Macros/MyMacro.macro" /&amp;gt;
    &amp;lt;parameter name="destination" value="~/App_Data/Umbraco/Macros/MyMacro.macro" /&amp;gt;
  &amp;lt;/add&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Adding that to your web.config in your packages (as described in my last post) will copy the file from the &lt;strong&gt;Macros&lt;/strong&gt; folder in your package (or what ever folder you've put them into) to the Umbraco Macros folder.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Yes, that's it.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Seriously, it's so much easier to ship Macros in v5 that v4 and the fact that they are running off disk (don't be a dick and use some crazy Hive provider for them like Examine!) makes installing them as simple as copying a file.&lt;/p&gt;

&lt;p&gt;But I think there's some room for improvements around this still and as I work on my v5 tasks set I'm going to be doing a simpler task for installing Macros, but in the meantime the above will work nicely &lt;strong&gt;today&lt;/strong&gt;.&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/umbraco/macros-in-packages" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fumbraco%2fmacros-in-packages&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/umbraco/macros-in-packages</feedburner:origLink></item><item><title>Creating an installer task</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/QCs-JZWvnVE/creating-an-installer-task</link><category>umbraco</category><category>umbraco-5</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Mon, 23 Jan 2012 17:12:46 PST</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/umbraco/creating-an-installer-task</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>As you possibly know I'm working on an extension for Umbraco 5 called <a href="http://stats-it.com">Stats It</a> and I've initially been focusing on making the install process nice and smooth for people who want to get up and running with the package. A good install experience will do wonders for giving your project credibility.</p>

<p>For this I have had to do a bit of digging into the <strong>Task</strong> system which is coming in v5, which is acting as a replacement for the traditional .NET event system, and in this article I'm going to share some tips when building <strong>installer tasks</strong>.</p>

<h2>Right task for the job</h2>

<p>In v5 there are two kinds of tasks available, <strong>Standard Tasks</strong> (my name) and <strong>Configuration Tasks</strong> and depending on what you're wanting to do you'll need to choose the right kind of task. Here's a quick overview of the two task types:</p>

<h3>Standard Task</h3>

<p>This is the most common type of task that you'll be creating; a task inherits from <code>Umbraco.Cms.Web.Tasks.AbstractWebTask</code> and requires a <code>Umbraco.Framework.Tasks.TaskAttribute</code> to be added so that the Umbraco framework layer will be able to find it (and you need to provide the attribute with a Guid for identification). This task type is very basic and can be used for any task that is raised in the system and then execute a piece of code, because of this you can think of it as being very similar to the event handlers that were in the Umbraco 4 system (or that you'll find in any .NET application).</p>

<h3>Configuration Tasks</h3>

<p>This task is primarily used in the install/ uninstall process of Umbraco 5 and inherits from <code>Umbraco.Cms.Web.Tasks.ConfigurationTask</code>. Where the previous task type you require an attribute the Configuration Tasks <strong>don't</strong> and you'll get some very undesired results if you <em>do</em> include the attribute. The power of this task type though is it allows you to specify values in the configuration file for the task, providing static values into the task as it is executed.</p>

<p><em>Side note - there is another task type <code>Umbraco.Framework.Tasks.AbstractTask</code> which is the base class for the <code>AbstractWebTask</code> but instead of relying on the web-side of Umbraco 5 it can be run without any web references. This would what you want if you are using the Umbraco framework outside of a web context, which it can do in-theory, but it's well beyond the scope of this post :P.</em></p>

<h2>Task configuration</h2>

<p>In addition to creating a class you'll also need to add a section in your configuration file that your task definition will reside within. There are two ways to do this:</p>

<ol>
<li>Add to the master web.config file (not recommended as it can have upgrade issues)</li>
<li>Add your own package</li>
</ol>

<p>I'm going to make the assumption that you're creating your own package here and you'll have your own web.config that you want to work against. First off you need to ensure you have the right web.config section:</p>

<pre><code>&lt;configuration&gt;
  &lt;configSections&gt;
    &lt;sectionGroup name="umbraco.cms"&gt;
      &lt;section name="tasks" type="Umbraco.Cms.Web.Configuration.Tasks.TasksConfiguration, Umbraco.Cms.Web" requirePermission="false" /&gt;
    &lt;/sectionGroup&gt;
  &lt;/configSections&gt;
 &lt;/configuration&gt;
</code></pre>

<p>This is the basis of your web.config file (and assuming there's nothing else in it yet) and what we've done is created a new web.config section called <strong>umbraco.cms</strong> and in that included the <strong>tasks</strong> section which uses a type provided by Umbraco.</p>

<p>Next we need to register our tasks:</p>

<pre><code>  &lt;umbraco.cms&gt;
    &lt;tasks&gt;
      &lt;add type="MyPackages.Tasks.MyAwesomeTask, MyPackage" trigger="post-package-install" /&gt;
    &lt;/tasks&gt;
  &lt;/umbraco.cms&gt;
</code></pre>

<p>This section would appear after the <code>&lt;/configSections&gt;</code> node and adds the section which we defined and then within that we add our tasks. There are two pieces of information we have to provide it:</p>

<ol>
<li>The fully qualified type of our task (namespace + classname + assembly)</li>
<li>A trigger for the task, for install tasks there is one called <code>post-package-install</code></li>
</ol>

<p>So that's the setup, now to make a task.</p>

<h2>Creating your first task</h2>

<p>So you're working on the next awesome package for Umbraco 5 and you need some stuff to happen when you install your package, well let's get cracking and make your first task. We'll do a basic task which will email you on package install, kind of a basic pingback to tell you when someone has installed the package. First up we'll make a class:</p>

<pre><code>using System;
using Umbraco.Cms.Web.Context;
using Umbraco.Cms.Web.Tasks;
using Umbraco.Framework;
using Umbraco.Framework.Tasks;

namespace TaskDemo
{
    [Task("{C1C251E1-CACF-447A-9516-694251C16B08}", TaskTriggers.PostPackageInstall)]
    public class EmailOnInstall : AbstractWebTask
    {
        public EmailOnInstall(IUmbracoApplicationContext applicationContext) : base(applicationContext)
        {
        }

        public override void Execute(TaskExecutionContext context)
        {
            throw new NotImplementedException();
        }
    }
}
</code></pre>

<p>This is as empty a file as you can possibly have for an Umbraco 5 task, currently this will just error on install, pretty useful!</p>

<p>The important stuff will be happening within the <code>Execute</code> method, this is the method that is invoked when task is run and obviously where you want to put your logic, so let's build it out:</p>

<pre><code>public override void Execute(TaskExecutionContext context)
{
    var email = new MailMessage
                    {
                        From = new MailAddress("phone-home@demo.com")
                    };
    email.To.Add(new MailAddress("new-install@demo.com"));
    email.Subject = "A new install has happened!";
    email.Body = "Hey dude,\r\nSomeone has installed your awesome package!\r\nH5YR!";

    var smtpClient = new SmtpClient();
    //server config skipped
    smtpClient.Send(email);
}
</code></pre>

<p>There we go, a <em>very</em> basic implementation of a task has been done! Here's the config for this:</p>

<pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;configuration&gt;
  &lt;configSections&gt;
    &lt;sectionGroup name="umbraco.cms"&gt;
      &lt;section name="tasks" type="Umbraco.Cms.Web.Configuration.Tasks.TasksConfiguration, Umbraco.Cms.Web" requirePermission="false" /&gt;
    &lt;/sectionGroup&gt;
  &lt;/configSections&gt;

  &lt;umbraco.cms&gt;
    &lt;tasks&gt;
      &lt;add type="TaskDemo.EmailOnInstall, TaskDemo" trigger="post-package-install" /&gt;
    &lt;/tasks&gt;
  &lt;/umbraco.cms&gt;
&lt;/configuration&gt;
</code></pre>

<p>Something you may notice is that in my config <strong>and</strong> in my class I've had to specify the trigger, this could be a mistake that I've made in my understanding thus-far but it seems to me that that is needed, someone feel free to correct me ;).</p>

<h2>Creating a configuration task</h2>

<p>As stipulated the above task is <strong>very</strong> basic but it does show you how you can work with the basics of a task. Well let's say that you want to create something a bit more advanced, say you want to have a task that will grant permissions to your custom application when the package is installed (this is a common problem solved in the PackageActionContrib in v4). For this we'll leverage the Configuration Task type so that we can make it a reusable task.</p>

<pre><code>using System;
using Umbraco.Cms.Web.Context;
using Umbraco.Cms.Web.Tasks;
using Umbraco.Framework.Tasks;

namespace TaskDemo
{
    public class GrantPermissions : ConfigurationTask
    {
        public GrantPermissions(ConfigurationTaskContext configurationTaskContext) : base(configurationTaskContext)
        {
        }

        public override void Execute(TaskExecutionContext context)
        {
            throw new NotImplementedException();
        }
    }
}
</code></pre>

<p>So again we've got our skeleton class but this time we inherit from <code>ConfigurationTask</code> so that we can provide it with configuration values.</p>

<p>Inside the <code>Execute</code> method we can access the <code>ConfigurationTaskContext.Parameters</code> property which will contain the parameters that are passed in from our configuration file, like so:</p>

<pre><code>public override void Execute(TaskExecutionContext context)
{
    if (!ConfigurationTaskContext.Parameters.ContainsKey("application"))
        throw new ArgumentException("No application supplied");
}
</code></pre>

<p>A simple check to make sure that we did get an application supplied, I want that as a pre-condition so that people don't break things on me!</p>

<p>But let's do something with the application provided:</p>

<p><em>Note: We're diving into the Hive here, I'm going to glance over how Hive works here, that's beyond the scope of this article, just believe me when I say that the code does work :P</em></p>

<pre><code>public override void Execute(TaskExecutionContext context)
{
    if (!ConfigurationTaskContext.Parameters.ContainsKey("application"))
        throw new ArgumentException("No application supplied");

    var controller = (Controller)context.EventSource;
    //Get the ID of the current user
    var id = ((UmbracoBackOfficeIdentity)controller.User.Identity).Id;
    //Access the Hive user store
    using (var uow = ApplicationContext.Hive.OpenWriter&lt;ISecurityStore&gt;())
    {
        //find the current user in Hive
        var entity = uow.Repositories.Get&lt;User&gt;(id);
        //Add the specified app to their permissions
        var apps = new List&lt;string&gt;(entity.Applications)
                        {
                            ConfigurationTaskContext.Parameters["application"]
                        };
        //Update their permissions
        entity.Applications = apps;
        //Tell Hive to update the object -- possibly not needed
        uow.Repositories.AddOrUpdate(entity);
        //tell Hive that we want to save the changes to its store
        uow.Complete();
        controller.HttpContext.CreateUmbracoAuthTicket(entity);
    }
}
</code></pre>

<p>I've put some comments inline to explain the code as it goes but the important part is that we are reading the task parameters out and adding it to the users permissions.</p>

<p>Once this is all updated it amazingly will just give a new icon in the applications tray on the install of the package!</p>

<p>Now let's have a look at the config:</p>

<pre><code>    &lt;tasks&gt;
      &lt;add type="TaskDemo.GrantPermissions, TaskDemo" trigger="post-package-install"&gt;
          &lt;parameter name="application" value="my-awesome-app" /&gt;
      &lt;/add&gt;
    &lt;/tasks&gt;
</code></pre>

<h2>Conclusion</h2>

<p>While the code above may look a little bit scare to begin with it's actually not that bad when it comes to creating tasks. There's a few simple rules which you need to remember:</p>

<ol>
<li>Pick the right type of task for your work, do you want to pass in config values or can you compile everything together?</li>
<li>Do you need to work with anything web specific or is just the base FrameworkContext going to be enough?</li>
<li>Make sure you subscribe to the right event!</li>
</ol>

<p>There's a few tasks built into the core of Umbraco 5 for copying files so that can also provide a good reference source.</p>
<img src="http://www.aaron-powell.com/via-feed/umbraco/creating-an-installer-task" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fumbraco%2fcreating-an-installer-task&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=QCs-JZWvnVE:AMuY0XdeSKE:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=QCs-JZWvnVE:AMuY0XdeSKE:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=QCs-JZWvnVE:AMuY0XdeSKE:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/QCs-JZWvnVE" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;As you possibly know I'm working on an extension for Umbraco 5 called &lt;a href="http://stats-it.com"&gt;Stats It&lt;/a&gt; and I've initially been focusing on making the install process nice and smooth for people who want to get up and running with the package. A good install experience will do wonders for giving your project credibility.&lt;/p&gt;

&lt;p&gt;For this I have had to do a bit of digging into the &lt;strong&gt;Task&lt;/strong&gt; system which is coming in v5, which is acting as a replacement for the traditional .NET event system, and in this article I'm going to share some tips when building &lt;strong&gt;installer tasks&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;Right task for the job&lt;/h2&gt;

&lt;p&gt;In v5 there are two kinds of tasks available, &lt;strong&gt;Standard Tasks&lt;/strong&gt; (my name) and &lt;strong&gt;Configuration Tasks&lt;/strong&gt; and depending on what you're wanting to do you'll need to choose the right kind of task. Here's a quick overview of the two task types:&lt;/p&gt;

&lt;h3&gt;Standard Task&lt;/h3&gt;

&lt;p&gt;This is the most common type of task that you'll be creating; a task inherits from &lt;code&gt;Umbraco.Cms.Web.Tasks.AbstractWebTask&lt;/code&gt; and requires a &lt;code&gt;Umbraco.Framework.Tasks.TaskAttribute&lt;/code&gt; to be added so that the Umbraco framework layer will be able to find it (and you need to provide the attribute with a Guid for identification). This task type is very basic and can be used for any task that is raised in the system and then execute a piece of code, because of this you can think of it as being very similar to the event handlers that were in the Umbraco 4 system (or that you'll find in any .NET application).&lt;/p&gt;

&lt;h3&gt;Configuration Tasks&lt;/h3&gt;

&lt;p&gt;This task is primarily used in the install/ uninstall process of Umbraco 5 and inherits from &lt;code&gt;Umbraco.Cms.Web.Tasks.ConfigurationTask&lt;/code&gt;. Where the previous task type you require an attribute the Configuration Tasks &lt;strong&gt;don't&lt;/strong&gt; and you'll get some very undesired results if you &lt;em&gt;do&lt;/em&gt; include the attribute. The power of this task type though is it allows you to specify values in the configuration file for the task, providing static values into the task as it is executed.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Side note - there is another task type &lt;code&gt;Umbraco.Framework.Tasks.AbstractTask&lt;/code&gt; which is the base class for the &lt;code&gt;AbstractWebTask&lt;/code&gt; but instead of relying on the web-side of Umbraco 5 it can be run without any web references. This would what you want if you are using the Umbraco framework outside of a web context, which it can do in-theory, but it's well beyond the scope of this post :P.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;Task configuration&lt;/h2&gt;

&lt;p&gt;In addition to creating a class you'll also need to add a section in your configuration file that your task definition will reside within. There are two ways to do this:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Add to the master web.config file (not recommended as it can have upgrade issues)&lt;/li&gt;
&lt;li&gt;Add your own package&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I'm going to make the assumption that you're creating your own package here and you'll have your own web.config that you want to work against. First off you need to ensure you have the right web.config section:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;configuration&amp;gt;
  &amp;lt;configSections&amp;gt;
    &amp;lt;sectionGroup name="umbraco.cms"&amp;gt;
      &amp;lt;section name="tasks" type="Umbraco.Cms.Web.Configuration.Tasks.TasksConfiguration, Umbraco.Cms.Web" requirePermission="false" /&amp;gt;
    &amp;lt;/sectionGroup&amp;gt;
  &amp;lt;/configSections&amp;gt;
 &amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is the basis of your web.config file (and assuming there's nothing else in it yet) and what we've done is created a new web.config section called &lt;strong&gt;umbraco.cms&lt;/strong&gt; and in that included the &lt;strong&gt;tasks&lt;/strong&gt; section which uses a type provided by Umbraco.&lt;/p&gt;

&lt;p&gt;Next we need to register our tasks:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  &amp;lt;umbraco.cms&amp;gt;
    &amp;lt;tasks&amp;gt;
      &amp;lt;add type="MyPackages.Tasks.MyAwesomeTask, MyPackage" trigger="post-package-install" /&amp;gt;
    &amp;lt;/tasks&amp;gt;
  &amp;lt;/umbraco.cms&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This section would appear after the &lt;code&gt;&amp;lt;/configSections&amp;gt;&lt;/code&gt; node and adds the section which we defined and then within that we add our tasks. There are two pieces of information we have to provide it:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The fully qualified type of our task (namespace + classname + assembly)&lt;/li&gt;
&lt;li&gt;A trigger for the task, for install tasks there is one called &lt;code&gt;post-package-install&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So that's the setup, now to make a task.&lt;/p&gt;

&lt;h2&gt;Creating your first task&lt;/h2&gt;

&lt;p&gt;So you're working on the next awesome package for Umbraco 5 and you need some stuff to happen when you install your package, well let's get cracking and make your first task. We'll do a basic task which will email you on package install, kind of a basic pingback to tell you when someone has installed the package. First up we'll make a class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using Umbraco.Cms.Web.Context;
using Umbraco.Cms.Web.Tasks;
using Umbraco.Framework;
using Umbraco.Framework.Tasks;

namespace TaskDemo
{
    [Task("{C1C251E1-CACF-447A-9516-694251C16B08}", TaskTriggers.PostPackageInstall)]
    public class EmailOnInstall : AbstractWebTask
    {
        public EmailOnInstall(IUmbracoApplicationContext applicationContext) : base(applicationContext)
        {
        }

        public override void Execute(TaskExecutionContext context)
        {
            throw new NotImplementedException();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is as empty a file as you can possibly have for an Umbraco 5 task, currently this will just error on install, pretty useful!&lt;/p&gt;

&lt;p&gt;The important stuff will be happening within the &lt;code&gt;Execute&lt;/code&gt; method, this is the method that is invoked when task is run and obviously where you want to put your logic, so let's build it out:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public override void Execute(TaskExecutionContext context)
{
    var email = new MailMessage
                    {
                        From = new MailAddress("phone-home@demo.com")
                    };
    email.To.Add(new MailAddress("new-install@demo.com"));
    email.Subject = "A new install has happened!";
    email.Body = "Hey dude,\r\nSomeone has installed your awesome package!\r\nH5YR!";

    var smtpClient = new SmtpClient();
    //server config skipped
    smtpClient.Send(email);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There we go, a &lt;em&gt;very&lt;/em&gt; basic implementation of a task has been done! Here's the config for this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;?xml version="1.0" encoding="utf-8" ?&amp;gt;
&amp;lt;configuration&amp;gt;
  &amp;lt;configSections&amp;gt;
    &amp;lt;sectionGroup name="umbraco.cms"&amp;gt;
      &amp;lt;section name="tasks" type="Umbraco.Cms.Web.Configuration.Tasks.TasksConfiguration, Umbraco.Cms.Web" requirePermission="false" /&amp;gt;
    &amp;lt;/sectionGroup&amp;gt;
  &amp;lt;/configSections&amp;gt;

  &amp;lt;umbraco.cms&amp;gt;
    &amp;lt;tasks&amp;gt;
      &amp;lt;add type="TaskDemo.EmailOnInstall, TaskDemo" trigger="post-package-install" /&amp;gt;
    &amp;lt;/tasks&amp;gt;
  &amp;lt;/umbraco.cms&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Something you may notice is that in my config &lt;strong&gt;and&lt;/strong&gt; in my class I've had to specify the trigger, this could be a mistake that I've made in my understanding thus-far but it seems to me that that is needed, someone feel free to correct me ;).&lt;/p&gt;

&lt;h2&gt;Creating a configuration task&lt;/h2&gt;

&lt;p&gt;As stipulated the above task is &lt;strong&gt;very&lt;/strong&gt; basic but it does show you how you can work with the basics of a task. Well let's say that you want to create something a bit more advanced, say you want to have a task that will grant permissions to your custom application when the package is installed (this is a common problem solved in the PackageActionContrib in v4). For this we'll leverage the Configuration Task type so that we can make it a reusable task.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using Umbraco.Cms.Web.Context;
using Umbraco.Cms.Web.Tasks;
using Umbraco.Framework.Tasks;

namespace TaskDemo
{
    public class GrantPermissions : ConfigurationTask
    {
        public GrantPermissions(ConfigurationTaskContext configurationTaskContext) : base(configurationTaskContext)
        {
        }

        public override void Execute(TaskExecutionContext context)
        {
            throw new NotImplementedException();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So again we've got our skeleton class but this time we inherit from &lt;code&gt;ConfigurationTask&lt;/code&gt; so that we can provide it with configuration values.&lt;/p&gt;

&lt;p&gt;Inside the &lt;code&gt;Execute&lt;/code&gt; method we can access the &lt;code&gt;ConfigurationTaskContext.Parameters&lt;/code&gt; property which will contain the parameters that are passed in from our configuration file, like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public override void Execute(TaskExecutionContext context)
{
    if (!ConfigurationTaskContext.Parameters.ContainsKey("application"))
        throw new ArgumentException("No application supplied");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A simple check to make sure that we did get an application supplied, I want that as a pre-condition so that people don't break things on me!&lt;/p&gt;

&lt;p&gt;But let's do something with the application provided:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: We're diving into the Hive here, I'm going to glance over how Hive works here, that's beyond the scope of this article, just believe me when I say that the code does work :P&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public override void Execute(TaskExecutionContext context)
{
    if (!ConfigurationTaskContext.Parameters.ContainsKey("application"))
        throw new ArgumentException("No application supplied");

    var controller = (Controller)context.EventSource;
    //Get the ID of the current user
    var id = ((UmbracoBackOfficeIdentity)controller.User.Identity).Id;
    //Access the Hive user store
    using (var uow = ApplicationContext.Hive.OpenWriter&amp;lt;ISecurityStore&amp;gt;())
    {
        //find the current user in Hive
        var entity = uow.Repositories.Get&amp;lt;User&amp;gt;(id);
        //Add the specified app to their permissions
        var apps = new List&amp;lt;string&amp;gt;(entity.Applications)
                        {
                            ConfigurationTaskContext.Parameters["application"]
                        };
        //Update their permissions
        entity.Applications = apps;
        //Tell Hive to update the object -- possibly not needed
        uow.Repositories.AddOrUpdate(entity);
        //tell Hive that we want to save the changes to its store
        uow.Complete();
        controller.HttpContext.CreateUmbracoAuthTicket(entity);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I've put some comments inline to explain the code as it goes but the important part is that we are reading the task parameters out and adding it to the users permissions.&lt;/p&gt;

&lt;p&gt;Once this is all updated it amazingly will just give a new icon in the applications tray on the install of the package!&lt;/p&gt;

&lt;p&gt;Now let's have a look at the config:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    &amp;lt;tasks&amp;gt;
      &amp;lt;add type="TaskDemo.GrantPermissions, TaskDemo" trigger="post-package-install"&amp;gt;
          &amp;lt;parameter name="application" value="my-awesome-app" /&amp;gt;
      &amp;lt;/add&amp;gt;
    &amp;lt;/tasks&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;While the code above may look a little bit scare to begin with it's actually not that bad when it comes to creating tasks. There's a few simple rules which you need to remember:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Pick the right type of task for your work, do you want to pass in config values or can you compile everything together?&lt;/li&gt;
&lt;li&gt;Do you need to work with anything web specific or is just the base FrameworkContext going to be enough?&lt;/li&gt;
&lt;li&gt;Make sure you subscribe to the right event!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;There's a few tasks built into the core of Umbraco 5 for copying files so that can also provide a good reference source.&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/umbraco/creating-an-installer-task" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fumbraco%2fcreating-an-installer-task&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/umbraco/creating-an-installer-task</feedburner:origLink></item><item><title>Heroku, SendGrid and NodeJS</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/ZVxjm61zfro/heroku-sendgrid-nodejs</link><category>nodejs</category><category>heroku</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Thu, 05 Jan 2012 05:51:50 PST</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/nodejs/heroku-sendgrid-nodejs</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Last night I launched the registration site for <a href="http://stats-it.com">Stats It</a>, and Umbraco 5 add-on I'm working on and I wanted to get the site out quickly and well... cheaply so I decided that I'd just do a 1 page site in NodeJS.</p>

<p>For hosting I wanted to go with <a href="http://heroku.com">Heroku</a> as I just love how simply I can get a site from my local machine to deployed with the platform and I also love how many <a href="http://addons.heroku.com/">add-ons</a> there are available.</p>

<p>To send emails there's a couple of choices, I decided to go with <a href="http://addons.heroku.com/sendgrid">SendGrid</a> for no reason other than they were the first that I saw :P.</p>

<p>So install SendGrid into your heroku app (I'm using the free version):</p>

<pre><code>heroku addons:add sendgrid:starter
</code></pre>

<p>And now you need something to send emails from NodeJS, for this I've gone with <a href="https://github.com/Marak/node_mailer">node_mailer</a> as it was the first in my search results and it's got a dead simple API. What's really cool about Heroku is that when you have add-ons such as SendGrid installed you get the config options injected, meaning sending an email is as simple as this:</p>

<pre><code>var email = require('mailer');

email.send({
	host: 'smtp.sendgrid.net',
	port: '587',
	authentication: 'plain',
	username: process.env.SENDGRID_USERNAME,
	password: process.env.SENDGRID_PASSWORD,
	domain: 'heroku.com',
	to: 'someone@somewhere.com',
	from: 'someone@somewhere-else.com',
	subject: 'You sent an email',
	body: 'Hey look at that!'
}, function (err, result) {
	//Do your error handling
});
</code></pre>

<p>You have to hard-code these settings:</p>

<ul>
<li><code>host: 'smtp.sendgrid.net'</code></li>
<li><code>port: '587'</code></li>
<li><code>authentication: 'plain'</code></li>
</ul>

<p>But Heroku will inject the username &amp; password for you, both of which will be on the <code>process.env</code> object, like so:</p>

<ul>
<li><code>process.env.SENDGRID_USERNAME</code></li>
<li><code>process.env.SENDGRID_PASSWORD</code></li>
</ul>

<p>And there you have it, you're now ready to send emails from NodeJS on Heroku.</p>
<img src="http://www.aaron-powell.com/via-feed/nodejs/heroku-sendgrid-nodejs" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fnodejs%2fheroku-sendgrid-nodejs&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=ZVxjm61zfro:KGiCBHhDVAQ:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=ZVxjm61zfro:KGiCBHhDVAQ:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=ZVxjm61zfro:KGiCBHhDVAQ:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/ZVxjm61zfro" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Last night I launched the registration site for &lt;a href="http://stats-it.com"&gt;Stats It&lt;/a&gt;, and Umbraco 5 add-on I'm working on and I wanted to get the site out quickly and well... cheaply so I decided that I'd just do a 1 page site in NodeJS.&lt;/p&gt;

&lt;p&gt;For hosting I wanted to go with &lt;a href="http://heroku.com"&gt;Heroku&lt;/a&gt; as I just love how simply I can get a site from my local machine to deployed with the platform and I also love how many &lt;a href="http://addons.heroku.com/"&gt;add-ons&lt;/a&gt; there are available.&lt;/p&gt;

&lt;p&gt;To send emails there's a couple of choices, I decided to go with &lt;a href="http://addons.heroku.com/sendgrid"&gt;SendGrid&lt;/a&gt; for no reason other than they were the first that I saw :P.&lt;/p&gt;

&lt;p&gt;So install SendGrid into your heroku app (I'm using the free version):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;heroku addons:add sendgrid:starter
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And now you need something to send emails from NodeJS, for this I've gone with &lt;a href="https://github.com/Marak/node_mailer"&gt;node_mailer&lt;/a&gt; as it was the first in my search results and it's got a dead simple API. What's really cool about Heroku is that when you have add-ons such as SendGrid installed you get the config options injected, meaning sending an email is as simple as this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var email = require('mailer');

email.send({
	host: 'smtp.sendgrid.net',
	port: '587',
	authentication: 'plain',
	username: process.env.SENDGRID_USERNAME,
	password: process.env.SENDGRID_PASSWORD,
	domain: 'heroku.com',
	to: 'someone@somewhere.com',
	from: 'someone@somewhere-else.com',
	subject: 'You sent an email',
	body: 'Hey look at that!'
}, function (err, result) {
	//Do your error handling
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You have to hard-code these settings:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;host: 'smtp.sendgrid.net'&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;port: '587'&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;authentication: 'plain'&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But Heroku will inject the username &amp;amp; password for you, both of which will be on the &lt;code&gt;process.env&lt;/code&gt; object, like so:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;process.env.SENDGRID_USERNAME&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;process.env.SENDGRID_PASSWORD&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And there you have it, you're now ready to send emails from NodeJS on Heroku.&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/nodejs/heroku-sendgrid-nodejs" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fnodejs%2fheroku-sendgrid-nodejs&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/nodejs/heroku-sendgrid-nodejs</feedburner:origLink></item><item><title>Stubbing AJAX responses with tbd and AmpliyJS</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/UsM23CYxVAg/stubbing-ajax-responses-with-tbd</link><category>javascript</category><category>amplifyjs</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Wed, 28 Dec 2011 19:25:07 PST</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/javascript/stubbing-ajax-responses-with-tbd</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>A project which I'm working on at the moment I'm using <a href="http://amplifyjs.com/">AmplifyJS</a> to simplify my front-end routing through to my underlying data service calls. The problem is that I haven't got the backend services ready yet (there's some outstanding blockers in the API I'm working against) so I'm focusing my work on the front end.</p>

<p>But there's the obvious problem, I want to push data to the UI but I don't have any way to get the data.</p>

<p>Luckily I wrote <a href="http://www.aaron-powell.com/javascript/building-data-with-tbd">tbd recently</a> which can solve one of the problems, it can generate data to pump into my new UI and this is where AmplifyJS really comes to shine.</p>

<h2>Introduction to faking data with amplify.request</h2>

<p>To simplify my front-end routing I'm going to be using the <a href="http://amplifyjs.com/api/request/">Request API</a> from AmplifyJS and if you're not familiar with it check out the <a href="http://amplifyjs.com/api/request/">docs</a> before going further as I only plan to cover the testing side of it.</p>

<p>Let's say I have a route defined like so:</p>

<pre><code>amplify.request.define('get-data', 'ajax', {
	url: '/data-service',
	dataType: 'json',
	type: 'GET'
});
</code></pre>

<p>And later in my app I'm accessing it:</p>

<pre><code>amplify.request('get-data', function (data) {
	//using templating pump out the UI from the data
});
</code></pre>

<p>So where does the faking data come in? Well the cool thing about how Amplify is designed means that you can <em>replace a defined request</em>!</p>

<p>Say what?!</p>

<p>First thing we need to understand is the <a href="http://amplifyjs.com/api/request/#request_types">request types</a>. When you define your request in AmplifyJS the 2nd argument you pass in is the <code>request type</code>, generally speaking this will be <code>ajax</code> as that is the provided request type in the API. You can define your own types so if you were wanting to pull in from an OData service you can setup that, add a new key to the <code>request types</code> and then it's all sweet (sorry how to do that is beyond this articles scope).</p>

<p>Where it gets really interesting is that if your provide only two arguments to the <code>define</code> method, a key and a <strong>function</strong> this works as well. In this case <strong>your function is executed when you invoke the request</strong>. Now let's add this code:</p>

<pre><code>amplify.request.define('my-data', function (settings) {
	settings.success({
		status: 'success',
		items: { }
	});
});
</code></pre>

<p>This will make it so that whenever I call my request I will get a successful response with no data. There are properties which you need to set, first is the <code>status</code> to <code>success</code> so that AmplifyJS knows the response was successful, second is the <code>items</code> property which will contain any data you want returned to the method.</p>

<h3>Setting up your project</h3>

<p>Now you've got the basics down I thought I'd just give a bit of an insight into how I go about including this into a project. As mentioned you can override a defined request as many times as you want:</p>

<pre><code>amplify.request.define('my-data', 'ajax', { ... });
amplify.request.define('my-data', 'odata', { ... });
amplify.request.define('my-data', function (settings) { ... });
</code></pre>

<p>Here I've setup the request three times but the last one to be executed is the one included.</p>

<p>The way I setup my project is that I have a file which I define my requests in, all of them together (or at least logically broken down into groups of common requests). For when I'm wanting to stub out my requests I create a secondary file and include the stubbed out requests in there and then include it <em>directly after the main file</em>. This means that once the real request is created it's immediately replaced with fake out.</p>

<p>With the fake requests in a separate file I can include or exclude them as I please, as my services come online or even use them in unit tests.</p>

<h2>Building your data</h2>

<p>The idea of doing this all with AmplifyJS was shown to me by <a href="http://twitter.com/elijahmanor">Elijah Manor</a>. He sent me this <a href="http://jsfiddle.net/slace/ubeeK/">jsfiddle</a> which shows it all setup.</p>

<p>The problem with examples like this is that they are using fixed data, every reload of that page will show you exactly the same thing and clicking the refresh button on the UI will reload the data with exactly the same data. Now in this demo it's not really that bit a deal, the data doesn't really need to look different each time it's not going to make much difference. But what if you are doing something that will look different based on the data, say you're doing some charting?</p>

<p>I've created a <a href="http://jsfiddle.net/slace/8tBYt/">jsfiddle</a> to demonstrate this, when you click the button the chart will be rebuilt with different data.</p>

<p>Now here's my mock request:</p>

<pre><code>amplify.request.define('get-data', function (settings) {
    var data = tbd.from({})
                .prop('category').use(tbd.utils.random('a', 'b', 'c', 'd', 'e')).done()
                .prop('value').use(tbd.utils.range(10, 100)).done()
                .make(tbd.utils.range(3, 8)());

    settings.success({
        status: 'success',
        items: data
    });
});
</code></pre>

<p>With <code>tbd</code> I'm scaffolding out a data series for my charting API, using the alphabet as the <em>label</em> and then a randomly chosen number between 10 and 100 for the value. This means that as I generate new data my UI will change (I'm leveraging one of <code>tbd</code>'s util methods to generate a random number of results as well (I might clean up the API to make that simpler in the future).</p>

<h2>Conclusion</h2>

<p>And there we have it an example of how we can combine a couple of helpful JavaScript libraries to make it easier to:</p>

<ul>
<li>Simplify out UI request layer</li>
<li>Make sure our development isn't halted while data services are under development</li>
<li>Have less hard coded data responses</li>
</ul>
<img src="http://www.aaron-powell.com/via-feed/javascript/stubbing-ajax-responses-with-tbd" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fstubbing-ajax-responses-with-tbd&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=UsM23CYxVAg:b7Wck4VW0JI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=UsM23CYxVAg:b7Wck4VW0JI:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=UsM23CYxVAg:b7Wck4VW0JI:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/UsM23CYxVAg" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;A project which I'm working on at the moment I'm using &lt;a href="http://amplifyjs.com/"&gt;AmplifyJS&lt;/a&gt; to simplify my front-end routing through to my underlying data service calls. The problem is that I haven't got the backend services ready yet (there's some outstanding blockers in the API I'm working against) so I'm focusing my work on the front end.&lt;/p&gt;

&lt;p&gt;But there's the obvious problem, I want to push data to the UI but I don't have any way to get the data.&lt;/p&gt;

&lt;p&gt;Luckily I wrote &lt;a href="http://www.aaron-powell.com/javascript/building-data-with-tbd"&gt;tbd recently&lt;/a&gt; which can solve one of the problems, it can generate data to pump into my new UI and this is where AmplifyJS really comes to shine.&lt;/p&gt;

&lt;h2&gt;Introduction to faking data with amplify.request&lt;/h2&gt;

&lt;p&gt;To simplify my front-end routing I'm going to be using the &lt;a href="http://amplifyjs.com/api/request/"&gt;Request API&lt;/a&gt; from AmplifyJS and if you're not familiar with it check out the &lt;a href="http://amplifyjs.com/api/request/"&gt;docs&lt;/a&gt; before going further as I only plan to cover the testing side of it.&lt;/p&gt;

&lt;p&gt;Let's say I have a route defined like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;amplify.request.define('get-data', 'ajax', {
	url: '/data-service',
	dataType: 'json',
	type: 'GET'
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And later in my app I'm accessing it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;amplify.request('get-data', function (data) {
	//using templating pump out the UI from the data
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So where does the faking data come in? Well the cool thing about how Amplify is designed means that you can &lt;em&gt;replace a defined request&lt;/em&gt;!&lt;/p&gt;

&lt;p&gt;Say what?!&lt;/p&gt;

&lt;p&gt;First thing we need to understand is the &lt;a href="http://amplifyjs.com/api/request/#request_types"&gt;request types&lt;/a&gt;. When you define your request in AmplifyJS the 2nd argument you pass in is the &lt;code&gt;request type&lt;/code&gt;, generally speaking this will be &lt;code&gt;ajax&lt;/code&gt; as that is the provided request type in the API. You can define your own types so if you were wanting to pull in from an OData service you can setup that, add a new key to the &lt;code&gt;request types&lt;/code&gt; and then it's all sweet (sorry how to do that is beyond this articles scope).&lt;/p&gt;

&lt;p&gt;Where it gets really interesting is that if your provide only two arguments to the &lt;code&gt;define&lt;/code&gt; method, a key and a &lt;strong&gt;function&lt;/strong&gt; this works as well. In this case &lt;strong&gt;your function is executed when you invoke the request&lt;/strong&gt;. Now let's add this code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;amplify.request.define('my-data', function (settings) {
	settings.success({
		status: 'success',
		items: { }
	});
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will make it so that whenever I call my request I will get a successful response with no data. There are properties which you need to set, first is the &lt;code&gt;status&lt;/code&gt; to &lt;code&gt;success&lt;/code&gt; so that AmplifyJS knows the response was successful, second is the &lt;code&gt;items&lt;/code&gt; property which will contain any data you want returned to the method.&lt;/p&gt;

&lt;h3&gt;Setting up your project&lt;/h3&gt;

&lt;p&gt;Now you've got the basics down I thought I'd just give a bit of an insight into how I go about including this into a project. As mentioned you can override a defined request as many times as you want:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;amplify.request.define('my-data', 'ajax', { ... });
amplify.request.define('my-data', 'odata', { ... });
amplify.request.define('my-data', function (settings) { ... });
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here I've setup the request three times but the last one to be executed is the one included.&lt;/p&gt;

&lt;p&gt;The way I setup my project is that I have a file which I define my requests in, all of them together (or at least logically broken down into groups of common requests). For when I'm wanting to stub out my requests I create a secondary file and include the stubbed out requests in there and then include it &lt;em&gt;directly after the main file&lt;/em&gt;. This means that once the real request is created it's immediately replaced with fake out.&lt;/p&gt;

&lt;p&gt;With the fake requests in a separate file I can include or exclude them as I please, as my services come online or even use them in unit tests.&lt;/p&gt;

&lt;h2&gt;Building your data&lt;/h2&gt;

&lt;p&gt;The idea of doing this all with AmplifyJS was shown to me by &lt;a href="http://twitter.com/elijahmanor"&gt;Elijah Manor&lt;/a&gt;. He sent me this &lt;a href="http://jsfiddle.net/slace/ubeeK/"&gt;jsfiddle&lt;/a&gt; which shows it all setup.&lt;/p&gt;

&lt;p&gt;The problem with examples like this is that they are using fixed data, every reload of that page will show you exactly the same thing and clicking the refresh button on the UI will reload the data with exactly the same data. Now in this demo it's not really that bit a deal, the data doesn't really need to look different each time it's not going to make much difference. But what if you are doing something that will look different based on the data, say you're doing some charting?&lt;/p&gt;

&lt;p&gt;I've created a &lt;a href="http://jsfiddle.net/slace/8tBYt/"&gt;jsfiddle&lt;/a&gt; to demonstrate this, when you click the button the chart will be rebuilt with different data.&lt;/p&gt;

&lt;p&gt;Now here's my mock request:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;amplify.request.define('get-data', function (settings) {
    var data = tbd.from({})
                .prop('category').use(tbd.utils.random('a', 'b', 'c', 'd', 'e')).done()
                .prop('value').use(tbd.utils.range(10, 100)).done()
                .make(tbd.utils.range(3, 8)());

    settings.success({
        status: 'success',
        items: data
    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With &lt;code&gt;tbd&lt;/code&gt; I'm scaffolding out a data series for my charting API, using the alphabet as the &lt;em&gt;label&lt;/em&gt; and then a randomly chosen number between 10 and 100 for the value. This means that as I generate new data my UI will change (I'm leveraging one of &lt;code&gt;tbd&lt;/code&gt;'s util methods to generate a random number of results as well (I might clean up the API to make that simpler in the future).&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;And there we have it an example of how we can combine a couple of helpful JavaScript libraries to make it easier to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Simplify out UI request layer&lt;/li&gt;
&lt;li&gt;Make sure our development isn't halted while data services are under development&lt;/li&gt;
&lt;li&gt;Have less hard coded data responses&lt;/li&gt;
&lt;/ul&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/javascript/stubbing-ajax-responses-with-tbd" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fstubbing-ajax-responses-with-tbd&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/javascript/stubbing-ajax-responses-with-tbd</feedburner:origLink></item><item><title>Some useful Jasmine extensions</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/ZAJ7i5X7kH8/useful-jasmine-extensions</link><category>javascript</category><category>jasmine</category><category>testing</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Thu, 22 Dec 2011 08:07:56 PST</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/javascript/useful-jasmine-extensions</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>For <a href="http://www.aaron-powell.com/javascript/building-data-with-tbd">tbd, a JavaScript helper I've written</a> I've been using <a href="http://pivotal.github.com/jasmine/">Jasmine</a> for my testing.</p>

<p>Some of the tests I've had to go beyond what <a href="http://pivotal.github.com/jasmine/jsdoc/symbols/jasmine.Matchers.html">matchers</a> are available out of the box so I thought I'd share them here (mostly so I've got an easy point for myself to find them again :P).</p>

<h2>A quick into to adding your own matcher</h2>

<p>I've you're new to Jasmine and haven't added your own matchers here's a quick tutorial.</p>

<p>You need to use the <a href="http://pivotal.github.com/jasmine/jsdoc/symbols/jasmine.Suite.html#beforeEach">beforeEach</a> and call <a href="http://pivotal.github.com/jasmine/jsdoc/symbols/jasmine.Spec.html#addMatchers">addMatchers</a>, like so:</p>

<pre><code>beforeEach(function() {
   this.addMatchers({
       alwaysTrue: function(){
           //put your logic in here to determine truthy results
           return true;
       }
   });
});
</code></pre>

<p>Now you can call it like so:</p>

<pre><code>expect('something').alwaysTrue();
</code></pre>

<p>This test extension that I've created isn't really useful as it will always return true but you can put in any logic you want.</p>

<p>The <code>this</code> object has an <code>actual</code> property, which is the value from your <code>expect</code> method and the arguments passed to the call are passed in.</p>

<h2>My matchers</h2>

<pre><code>beforeEach(function() {
    this.addMatchers({
        toBeInArray: function() {
            return ~[].slice.call(arguments).indexOf(this.actual);
        },
        toBeInDateRange: function(min, max) {
            var actual = this.actual.getTime();
            return actual &lt;= max.getTime() &amp;&amp; actual &gt;= min.getTime();
        },
        toBeInNumericalRange: function (min, max) {
            var actual = this.actual;
            return actual &lt;= max &amp;&amp; actual &gt;= min;
        }
    });
});
</code></pre>

<p>Here's how you use them:</p>

<pre><code>expect('a').toByInArray('a', 'b', 'c');
expect(3).toBeInNumericalRange(0, 10);
expect(new Date(2011, 11, 01)).toBeInDateRange(new Date(2011, 10, 01), new Date(2011, 11, 30));
</code></pre>

<p>Hopefully this is helpful to someone else :)</p>
<img src="http://www.aaron-powell.com/via-feed/javascript/useful-jasmine-extensions" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fuseful-jasmine-extensions&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=ZAJ7i5X7kH8:l_dSECEmt9E:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=ZAJ7i5X7kH8:l_dSECEmt9E:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=ZAJ7i5X7kH8:l_dSECEmt9E:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/ZAJ7i5X7kH8" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;For &lt;a href="http://www.aaron-powell.com/javascript/building-data-with-tbd"&gt;tbd, a JavaScript helper I've written&lt;/a&gt; I've been using &lt;a href="http://pivotal.github.com/jasmine/"&gt;Jasmine&lt;/a&gt; for my testing.&lt;/p&gt;

&lt;p&gt;Some of the tests I've had to go beyond what &lt;a href="http://pivotal.github.com/jasmine/jsdoc/symbols/jasmine.Matchers.html"&gt;matchers&lt;/a&gt; are available out of the box so I thought I'd share them here (mostly so I've got an easy point for myself to find them again :P).&lt;/p&gt;

&lt;h2&gt;A quick into to adding your own matcher&lt;/h2&gt;

&lt;p&gt;I've you're new to Jasmine and haven't added your own matchers here's a quick tutorial.&lt;/p&gt;

&lt;p&gt;You need to use the &lt;a href="http://pivotal.github.com/jasmine/jsdoc/symbols/jasmine.Suite.html#beforeEach"&gt;beforeEach&lt;/a&gt; and call &lt;a href="http://pivotal.github.com/jasmine/jsdoc/symbols/jasmine.Spec.html#addMatchers"&gt;addMatchers&lt;/a&gt;, like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;beforeEach(function() {
   this.addMatchers({
       alwaysTrue: function(){
           //put your logic in here to determine truthy results
           return true;
       }
   });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you can call it like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;expect('something').alwaysTrue();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This test extension that I've created isn't really useful as it will always return true but you can put in any logic you want.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;this&lt;/code&gt; object has an &lt;code&gt;actual&lt;/code&gt; property, which is the value from your &lt;code&gt;expect&lt;/code&gt; method and the arguments passed to the call are passed in.&lt;/p&gt;

&lt;h2&gt;My matchers&lt;/h2&gt;

&lt;pre&gt;&lt;code&gt;beforeEach(function() {
    this.addMatchers({
        toBeInArray: function() {
            return ~[].slice.call(arguments).indexOf(this.actual);
        },
        toBeInDateRange: function(min, max) {
            var actual = this.actual.getTime();
            return actual &amp;lt;= max.getTime() &amp;amp;&amp;amp; actual &amp;gt;= min.getTime();
        },
        toBeInNumericalRange: function (min, max) {
            var actual = this.actual;
            return actual &amp;lt;= max &amp;amp;&amp;amp; actual &amp;gt;= min;
        }
    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here's how you use them:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;expect('a').toByInArray('a', 'b', 'c');
expect(3).toBeInNumericalRange(0, 10);
expect(new Date(2011, 11, 01)).toBeInDateRange(new Date(2011, 10, 01), new Date(2011, 11, 30));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hopefully this is helpful to someone else :)&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/javascript/useful-jasmine-extensions" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fuseful-jasmine-extensions&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/javascript/useful-jasmine-extensions</feedburner:origLink></item><item><title>2011, a year in review</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/47XMfJR1t2w/2011-a-year-in-review</link><category>random</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Wed, 21 Dec 2011 16:06:56 PST</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/2011-a-year-in-review</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>As the year wraps up it brings time for the atypical year in review post!</p>

<p>While <a href="http://www.aaron-powell.com/2010-a-year-in-review">last year</a> I declared to be the year of the conferences but of course this year was just as crazy with conferences.</p>

<p>I...</p>

<ul>
<li>Got a <a href="http://www.aaron-powell.com/mvp11">Microsoft MVP award</a>!</li>
<li>Went to the USA for my first time to go to MIX11 and talked FunnelWeb at the Open Source Fest
<ul>
<li>Vegas is <strong>insane</strong> and I don't think I've ever been as hung over in my life as I'd been</li>
<li>Hanging out with <a href="http://twitter.com/#!/gblock">Glenn Block</a> was heaps of fun, he's such a top guy</li>
<li>I got to have lunch with <a href="http://twitter.com/#!/shanselman">Scott Hanselman</a>, <a href="http://twitter.com/#!/haacked">Phil Haack</a> and <a href="http://twitter.com/#!/robconery">Rob Conery</a> which was pretty awesome from a nerd point of view</li>
<li>The pre-party also allowed me to meet some of my idols in Douglas Crockford, <a href="http://twitter.com/#!/Encosia">Dave Ward</a> and <a href="http://twitter.com/#!/elijahmanor">Elijah Manor</a></li>
</ul></li>
<li>Next stop was Melbourne and DDD Melbourne where I got to present on JavaScript craziness
<ul>
<li>And watching <a href="http://twitter.com/#!/stevegodbold">Steve Godbold</a> rap was just hilarious</li>
</ul></li>
<li>Next up was <a href="http://www.aaron-powell.com/remix11">REMIX</a> where I spoke on being a web developer and had to do an impromptu session where I talked about JavaScript again (although admittedly I lost the audience on the second talk :P)</li>
<li>It wasn't long until I was back on a plane to get to Denmark for CodeGarden 11 where I talked about everything from ASP.NET MVC to what is interesting in Umbraco 5
<ul>
<li>I have since been removed from the <a href="http://www.aaron-powell.com/umbraco/so-long-and-thanks-for-all-the-fish">Umbraco project</a> but I stand by what got me removed, instead I am trying to get people <a href="http://www.aaron-powell.com/umbraco/i-want-you">involved from the outside</a></li>
</ul></li>
<li>Back in Australia and it was time for DDD Sydney and a revisit my DDD Melbourne talk about getting freaky with JavaScript and talk about Open Source in the panel session run by Nick Hodge</li>
<li>But no rest for wicked it was time for <a href="http://www.aaron-powell.com/speaking/teched-nz-2011">Teched NZ</a> (<a href="http://www.aaron-powell.com/speaking/teched-nz-2011/slides">slides</a>) and then <a href="http://www.aaron-powell.com/speaking/teched-au-2011">Teched AU</a> (<a href="http://www.aaron-powell.com/speaking/teched-au-2011/slides">slides &amp; video</a>) 
<ul>
<li>I got voted one of the top sessions in the web track which was pretty exciting!</li>
</ul></li>
</ul>

<p><strong>Phew!</strong></p>

<p>For the first time in 2 years though I <em>didn't</em> resign from my job, I know, shockingly I'm still working at the same company I was working for this time last year.</p>

<p>Generally speaking I've scaled back my Open Source work, I've still tried to be active in the various communities but instead of actively developing I've tried to be more of a voice of reason. I've release a few small things such as:</p>

<ul>
<li>Another <a href="http://www.aaron-powell.com/javascript/postman">pub/sub library</a> in JavaScript</li>
<li>A <a href="http://www.aaron-powell.com/javascript/javascript-quiz">JavaScript quiz</a> website
<ul>
<li><a href="http://www.aaron-powell.com/javascript/rebuilding-javascript-quiz-in-nodejs">Which I then rewrite in NodeJS</a></li>
<li>But admittedly it's not been getting a lot of love these days from myself or the community</li>
</ul></li>
<li>A library to <a href="http://www.aaron-powell.com/javascript/building-data-with-tbd">building test data</a> in JavaScript</li>
</ul>

<p>So here's to a more JavaScript filled 2012!</p>
<img src="http://www.aaron-powell.com/via-feed/2011-a-year-in-review" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2f2011-a-year-in-review&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=47XMfJR1t2w:4nilyOyqUUg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=47XMfJR1t2w:4nilyOyqUUg:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=47XMfJR1t2w:4nilyOyqUUg:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/47XMfJR1t2w" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;As the year wraps up it brings time for the atypical year in review post!&lt;/p&gt;

&lt;p&gt;While &lt;a href="http://www.aaron-powell.com/2010-a-year-in-review"&gt;last year&lt;/a&gt; I declared to be the year of the conferences but of course this year was just as crazy with conferences.&lt;/p&gt;

&lt;p&gt;I...&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Got a &lt;a href="http://www.aaron-powell.com/mvp11"&gt;Microsoft MVP award&lt;/a&gt;!&lt;/li&gt;
&lt;li&gt;Went to the USA for my first time to go to MIX11 and talked FunnelWeb at the Open Source Fest
&lt;ul&gt;
&lt;li&gt;Vegas is &lt;strong&gt;insane&lt;/strong&gt; and I don't think I've ever been as hung over in my life as I'd been&lt;/li&gt;
&lt;li&gt;Hanging out with &lt;a href="http://twitter.com/#!/gblock"&gt;Glenn Block&lt;/a&gt; was heaps of fun, he's such a top guy&lt;/li&gt;
&lt;li&gt;I got to have lunch with &lt;a href="http://twitter.com/#!/shanselman"&gt;Scott Hanselman&lt;/a&gt;, &lt;a href="http://twitter.com/#!/haacked"&gt;Phil Haack&lt;/a&gt; and &lt;a href="http://twitter.com/#!/robconery"&gt;Rob Conery&lt;/a&gt; which was pretty awesome from a nerd point of view&lt;/li&gt;
&lt;li&gt;The pre-party also allowed me to meet some of my idols in Douglas Crockford, &lt;a href="http://twitter.com/#!/Encosia"&gt;Dave Ward&lt;/a&gt; and &lt;a href="http://twitter.com/#!/elijahmanor"&gt;Elijah Manor&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Next stop was Melbourne and DDD Melbourne where I got to present on JavaScript craziness
&lt;ul&gt;
&lt;li&gt;And watching &lt;a href="http://twitter.com/#!/stevegodbold"&gt;Steve Godbold&lt;/a&gt; rap was just hilarious&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Next up was &lt;a href="http://www.aaron-powell.com/remix11"&gt;REMIX&lt;/a&gt; where I spoke on being a web developer and had to do an impromptu session where I talked about JavaScript again (although admittedly I lost the audience on the second talk :P)&lt;/li&gt;
&lt;li&gt;It wasn't long until I was back on a plane to get to Denmark for CodeGarden 11 where I talked about everything from ASP.NET MVC to what is interesting in Umbraco 5
&lt;ul&gt;
&lt;li&gt;I have since been removed from the &lt;a href="http://www.aaron-powell.com/umbraco/so-long-and-thanks-for-all-the-fish"&gt;Umbraco project&lt;/a&gt; but I stand by what got me removed, instead I am trying to get people &lt;a href="http://www.aaron-powell.com/umbraco/i-want-you"&gt;involved from the outside&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Back in Australia and it was time for DDD Sydney and a revisit my DDD Melbourne talk about getting freaky with JavaScript and talk about Open Source in the panel session run by Nick Hodge&lt;/li&gt;
&lt;li&gt;But no rest for wicked it was time for &lt;a href="http://www.aaron-powell.com/speaking/teched-nz-2011"&gt;Teched NZ&lt;/a&gt; (&lt;a href="http://www.aaron-powell.com/speaking/teched-nz-2011/slides"&gt;slides&lt;/a&gt;) and then &lt;a href="http://www.aaron-powell.com/speaking/teched-au-2011"&gt;Teched AU&lt;/a&gt; (&lt;a href="http://www.aaron-powell.com/speaking/teched-au-2011/slides"&gt;slides &amp;amp; video&lt;/a&gt;) 
&lt;ul&gt;
&lt;li&gt;I got voted one of the top sessions in the web track which was pretty exciting!&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phew!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For the first time in 2 years though I &lt;em&gt;didn't&lt;/em&gt; resign from my job, I know, shockingly I'm still working at the same company I was working for this time last year.&lt;/p&gt;

&lt;p&gt;Generally speaking I've scaled back my Open Source work, I've still tried to be active in the various communities but instead of actively developing I've tried to be more of a voice of reason. I've release a few small things such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Another &lt;a href="http://www.aaron-powell.com/javascript/postman"&gt;pub/sub library&lt;/a&gt; in JavaScript&lt;/li&gt;
&lt;li&gt;A &lt;a href="http://www.aaron-powell.com/javascript/javascript-quiz"&gt;JavaScript quiz&lt;/a&gt; website
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.aaron-powell.com/javascript/rebuilding-javascript-quiz-in-nodejs"&gt;Which I then rewrite in NodeJS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;But admittedly it's not been getting a lot of love these days from myself or the community&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;A library to &lt;a href="http://www.aaron-powell.com/javascript/building-data-with-tbd"&gt;building test data&lt;/a&gt; in JavaScript&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So here's to a more JavaScript filled 2012!&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/2011-a-year-in-review" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2f2011-a-year-in-review&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/2011-a-year-in-review</feedburner:origLink></item><item><title>I want you</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/8Ce7doFO-JM/i-want-you</link><category>umbraco</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Sun, 18 Dec 2011 17:19:36 PST</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/umbraco/i-want-you</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p><img src="http://www.aaron-powell.com/get/i-want-you.jpg" alt="alt text" title="I want you" /></p>

<p>Hi, my name's Aaron and I'm a former member of the Umbraco core team. Before I <a href="http://www.aaron-powell.com/umbraco/so-long-and-thanks-for-all-the-fish">departed</a> the core team something I was pushing for was greater involvement between the core (and HQ) and the Umbraco <strong>developer</strong> community.</p>

<p>Let me make sure I clear one thing up first, Umbraco has a great user community, our.umbraco thrives with huge number of contributors helping everyone out from the beginner to the advanced. The extensions community is also a hive (sic) of activity.</p>

<p>The community that I'm talking about is the one around developing <em>Umbraco as a product</em>.</p>

<p>If you're reading this you most likely have some vested interest in Umbraco, you're  doing freelancing and implementing it, your company sells solutions based around it or you are like me and just find CMSs sexy (well let's hope that's not the case :P). Whatever the case may be the direction of the product does have an impact on you so you should make sure your voice is heard. Even if you're not a developer your voice is important, feedback about things you/ your clients find challenging, features you'd like to see, testing alpha/ beta/ RC released or even just questioning why something was done a particular way.</p>

<h3>How do I get involved?</h3>

<p>This all sounds well and good but <em>what</em> should you do?</p>

<p>A few months ago the <a href="http://umbraco5contrib.codeplex.com/">Umbraco 5 contrib</a> was opened up and it's already starting to get some stuff around this up there.</p>

<p><a href="http://umbraco5contrib.codeplex.com/discussions/279569">There's a post on contributing</a> and then there's the <a href="http://umbraco5contrib.codeplex.com/discussions/279728">discussion around automated UI testing</a> which <a href="http://blog.mattbrailsford.com/">Matt Braildsford</a> took into a larger discussion last week.</p>

<p>Lastly there's a room on <a href="http://uchat.mattbrailsford.com/">JabbR</a> but it's a little quiet still these days.</p>

<p>Keep an eye on the <a href="http://twitter.com/#!/search/%23Umbraco">Umbraco twitter stream</a> and grab <a href="http://nightly.umbraco.org/">nightly Umbraco builds</a>.</p>

<p>Raise a <a href="http://umbraco5contrib.codeplex.com/discussions">discussion</a> if you don't understand why something was implemented some way (<a href="http://our.umbraco.org/">but keep implementation discussions to our.umbraco</a>).</p>

<p><a href="http://umbraco.codeplex.com/SourceControl/list/changesets">Monitor change set commits</a> and make sure they are still conforming to what standards there are.</p>

<h2>So c'mon, get involved!</h2>
<img src="http://www.aaron-powell.com/via-feed/umbraco/i-want-you" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fumbraco%2fi-want-you&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=8Ce7doFO-JM:rC8vcDiDRf8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=8Ce7doFO-JM:rC8vcDiDRf8:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=8Ce7doFO-JM:rC8vcDiDRf8:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/8Ce7doFO-JM" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;&lt;img src="http://www.aaron-powell.com/get/i-want-you.jpg" alt="alt text" title="I want you" /&gt;&lt;/p&gt;

&lt;p&gt;Hi, my name's Aaron and I'm a former member of the Umbraco core team. Before I &lt;a href="http://www.aaron-powell.com/umbraco/so-long-and-thanks-for-all-the-fish"&gt;departed&lt;/a&gt; the core team something I was pushing for was greater involvement between the core (and HQ) and the Umbraco &lt;strong&gt;developer&lt;/strong&gt; community.&lt;/p&gt;

&lt;p&gt;Let me make sure I clear one thing up first, Umbraco has a great user community, our.umbraco thrives with huge number of contributors helping everyone out from the beginner to the advanced. The extensions community is also a hive (sic) of activity.&lt;/p&gt;

&lt;p&gt;The community that I'm talking about is the one around developing &lt;em&gt;Umbraco as a product&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;If you're reading this you most likely have some vested interest in Umbraco, you're  doing freelancing and implementing it, your company sells solutions based around it or you are like me and just find CMSs sexy (well let's hope that's not the case :P). Whatever the case may be the direction of the product does have an impact on you so you should make sure your voice is heard. Even if you're not a developer your voice is important, feedback about things you/ your clients find challenging, features you'd like to see, testing alpha/ beta/ RC released or even just questioning why something was done a particular way.&lt;/p&gt;

&lt;h3&gt;How do I get involved?&lt;/h3&gt;

&lt;p&gt;This all sounds well and good but &lt;em&gt;what&lt;/em&gt; should you do?&lt;/p&gt;

&lt;p&gt;A few months ago the &lt;a href="http://umbraco5contrib.codeplex.com/"&gt;Umbraco 5 contrib&lt;/a&gt; was opened up and it's already starting to get some stuff around this up there.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://umbraco5contrib.codeplex.com/discussions/279569"&gt;There's a post on contributing&lt;/a&gt; and then there's the &lt;a href="http://umbraco5contrib.codeplex.com/discussions/279728"&gt;discussion around automated UI testing&lt;/a&gt; which &lt;a href="http://blog.mattbrailsford.com/"&gt;Matt Braildsford&lt;/a&gt; took into a larger discussion last week.&lt;/p&gt;

&lt;p&gt;Lastly there's a room on &lt;a href="http://uchat.mattbrailsford.com/"&gt;JabbR&lt;/a&gt; but it's a little quiet still these days.&lt;/p&gt;

&lt;p&gt;Keep an eye on the &lt;a href="http://twitter.com/#!/search/%23Umbraco"&gt;Umbraco twitter stream&lt;/a&gt; and grab &lt;a href="http://nightly.umbraco.org/"&gt;nightly Umbraco builds&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Raise a &lt;a href="http://umbraco5contrib.codeplex.com/discussions"&gt;discussion&lt;/a&gt; if you don't understand why something was implemented some way (&lt;a href="http://our.umbraco.org/"&gt;but keep implementation discussions to our.umbraco&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;a href="http://umbraco.codeplex.com/SourceControl/list/changesets"&gt;Monitor change set commits&lt;/a&gt; and make sure they are still conforming to what standards there are.&lt;/p&gt;

&lt;h2&gt;So c'mon, get involved!&lt;/h2&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/umbraco/i-want-you" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fumbraco%2fi-want-you&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/umbraco/i-want-you</feedburner:origLink></item><item><title>Building data with tbd</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/JjtpCdNB3aE/building-data-with-tbd</link><category>javascript</category><category>nodejs</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Tue, 13 Dec 2011 04:57:37 PST</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/javascript/building-data-with-tbd</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>When building a UI that is driven by JavaScript one of the most tedious tasks is ensuring that you have data which you can populate into the UI to develop against. If you're like me you probably prefer to do the UI component before the server component. Alternatively you could be working in a team where someone else is responsible for developing the server component at the same time as you're developing the UI. Which ever the case is you'll find yourself in a situation where you don't have the data to build out your UI.</p>

<p>This is a situation that I find myself in quite often and it always left me thinking about how I would throw together some data to do the UI. Generally speaking it'd involve a bunch of copy and pasted lines of JavaScript which builds up an object graph. This <em>does work</em> but it's not a great way to simulate data, especially if you want to change the data volumes and see how the UI will react.</p>

<p>Coming from a .NET background I've used libraries like <a href="http://nbuilder.org/">NBuilder</a> and <a href="http://fabricator.codeplex.com/">Fabricator</a> in the past. These libraries take an input object and will generate a series of fake data from it.</p>

<p>So I thought "hey, why not create that in JavaScript" and from there <strong>tbd</strong> was born!</p>

<h2>tbd - Test Data Builder</h2>

<p><a href="https://github.com/aaronpowell/tbd">tbd</a>, or Test Data Builder is a project I started to create (fake) data using JavaScript. There's a bit of a joke in the name, when I was trying to pick a name I was thinking "what'd be quirky, it's for building test data, oh sweet, <strong>tbd</strong> since it can be Test Data Builder or <em>To Be Defined</em>, which makes for a good play on words". Now the astute reader will notice the mistake immediately but for those with reading problems like me you'll need a hint, Test Data Builder is actually <strong>tdb</strong>.</p>

<p>The idea behind tbd was to be able to take a JavaScript object and create a bunch more of them, as many as you want! I also wanted it to be disconnected to the browser so you could run it in both Node.js and the browser. For running it in the browser you need to add a reference to the file and with Node.js it's up on <a href="http://search.npmjs.org/#/tbd">npm</a>.</p>

<p>Here's a basic example of how to use it:</p>

<pre><code>var data = tbd.from({ hello: 'world' }).make(10);
</code></pre>

<p>This will create an array of 10 objects all which are identical. Since JavaScript doesn't have reflection like .NET there isn't a way to get an inferred type of a property, instead you have to assign it a 'default' value. This can have an advantage though as it means you can also only have tbd generate values for properties you actually want random data for. So how do you do values?</p>

<pre><code>var data = tbd.from({ foo: 1 })
            .prop('foo').use(function() { return Math.random(); }).done()
            .make(10);
</code></pre>

<p>This will create an array of 10 items which have a unique random number (well as unique as a random number can be :P) for the property <code>foo</code>. To break down the way it works you need to understand the fluent API for properties.</p>

<ol>
<li>Pass the property name to the <code>prop</code> method as a string
<ol>
<li><em>Pro tip - if the property name doesn't exist on the source object it'll still be added!</em></li>
</ol></li>
<li>Pass a value or function into the <code>use</code> method
<ul>
<li>If you pass a value that will be used for each object</li>
<li>If you pass a function it'll be invoked for each object</li>
<li>There's some helper methods we'll look at later</li>
</ul></li>
<li>Call <code>done</code> to signify you've finished with that property so you're back to the root API and allow you to modify more properties</li>
</ol>

<p>The last thing you always call is <code>make</code> and specify the number of objects you want.</p>

<p>And that's it, you can go off and create all the data you could ever want.</p>

<h2>Making better fake data</h2>

<p>Since tbd is a really dumb API if you don't tell it what to do with a property it wont do anything. So how do you produce <em>better fake data</em>? That might sound like a silly question but say you're trying to build some graphs, you don't want all the data to be the same do you?</p>

<p>Well to simplify this tbd ships with a number of useful utilities for generating better fake data. The full list you can get off the <a href="https://github.com/aaronpowell/tbd/blob/master/README.md">readme</a> but are some of the most useful IMO. All of these reside in the <code>tbd.utils</code> namespace.</p>

<h3>Pick a random value</h3>

<p>Say you want to randomly choose a value from a set of values, say a bunch of different word, there's a handy method that'll do that called <code>random</code> and you use it like so:</p>

<pre><code>var data = tbd.from({ hello: 'world' })
            .prop('hello').use(tbd.utils.random('me', 'no me', 'why not me!')).done()
            .make(10);
</code></pre>

<p>This method takes <em>n number of arguments</em> and it will randomly choose one of them for each object. You can pass in any data type that you want to this and it'll take a random from the list so you're not just restricted to strings.</p>

<h3>Better random numbers and dates</h3>

<p>While the <code>random</code> method is great if you have a small set of data to go through but what if you don't? What if you want a random number between 1 and 1000? Typing that out would <strong>suck</strong>. Well luckily there is the <code>range</code> method:</p>

<pre><code>var data = tbd.from({ hello: 'world' })
            .prop('hello').use(tbd.utils.range(1, 1000)).done()
            .make(10);
</code></pre>

<p>For <code>range</code> you pass in a min and max value and something from in there will be used. This method also supports dates so you can randomly choose a date from within a range.</p>

<h3>Sequences</h3>

<p>Sometimes you just want an ordered list of values and that's where <code>sequential</code> comes in. Sequential you provide a start point and you'll get a value incremented by one each time from there:</p>

<pre><code>var data = tbd.from({ hello: 'world' })
            .prop('hello').use(tbd.utils.sequential(1)).done()
            .make(10);
</code></pre>

<p><em>Note: I had a mistake in the initial post, the method is <code>sequential</code> not <code>sequence</code>.</em></p>

<h4>Date sequences</h4>

<p>One cool thing about the <code>sequential</code> api is that you can provide it a date and it will increment that. By default the dates will shift one day at a time to get you to your new date:</p>

<pre><code>tbd.from({ date: new Date })
    .prop('foo').use(tbd.utils.sequential(new Date() /* optional parameter for date property the increment, default is 'd' */)
    .make(10);
//the 'day' property will be incremented by 1 from the starting value
</code></pre>

<p>But you can overload this to increment by other date parts:</p>

<ul>
<li>y -> Year</li>
<li>M -> Month</li>
<li>d -> Day (default)</li>
<li>h -> Hour</li>
<li>m -> Minutes</li>
<li>s -> Seconds</li>
</ul>

<h2>Conclusion</h2>

<p>So this wraps up our look at <code>tbd</code>, a useful little tool I wrote to make it easier to build out some fake data for when you're mocking a UI or to pump into a test.</p>

<p><a href="https://github.com/aaronpowell/tbd">Grab it today!</a></p>
<img src="http://www.aaron-powell.com/via-feed/javascript/building-data-with-tbd" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fbuilding-data-with-tbd&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=JjtpCdNB3aE:EhNa3Rs6DK8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=JjtpCdNB3aE:EhNa3Rs6DK8:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=JjtpCdNB3aE:EhNa3Rs6DK8:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/JjtpCdNB3aE" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;When building a UI that is driven by JavaScript one of the most tedious tasks is ensuring that you have data which you can populate into the UI to develop against. If you're like me you probably prefer to do the UI component before the server component. Alternatively you could be working in a team where someone else is responsible for developing the server component at the same time as you're developing the UI. Which ever the case is you'll find yourself in a situation where you don't have the data to build out your UI.&lt;/p&gt;

&lt;p&gt;This is a situation that I find myself in quite often and it always left me thinking about how I would throw together some data to do the UI. Generally speaking it'd involve a bunch of copy and pasted lines of JavaScript which builds up an object graph. This &lt;em&gt;does work&lt;/em&gt; but it's not a great way to simulate data, especially if you want to change the data volumes and see how the UI will react.&lt;/p&gt;

&lt;p&gt;Coming from a .NET background I've used libraries like &lt;a href="http://nbuilder.org/"&gt;NBuilder&lt;/a&gt; and &lt;a href="http://fabricator.codeplex.com/"&gt;Fabricator&lt;/a&gt; in the past. These libraries take an input object and will generate a series of fake data from it.&lt;/p&gt;

&lt;p&gt;So I thought "hey, why not create that in JavaScript" and from there &lt;strong&gt;tbd&lt;/strong&gt; was born!&lt;/p&gt;

&lt;h2&gt;tbd - Test Data Builder&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://github.com/aaronpowell/tbd"&gt;tbd&lt;/a&gt;, or Test Data Builder is a project I started to create (fake) data using JavaScript. There's a bit of a joke in the name, when I was trying to pick a name I was thinking "what'd be quirky, it's for building test data, oh sweet, &lt;strong&gt;tbd&lt;/strong&gt; since it can be Test Data Builder or &lt;em&gt;To Be Defined&lt;/em&gt;, which makes for a good play on words". Now the astute reader will notice the mistake immediately but for those with reading problems like me you'll need a hint, Test Data Builder is actually &lt;strong&gt;tdb&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The idea behind tbd was to be able to take a JavaScript object and create a bunch more of them, as many as you want! I also wanted it to be disconnected to the browser so you could run it in both Node.js and the browser. For running it in the browser you need to add a reference to the file and with Node.js it's up on &lt;a href="http://search.npmjs.org/#/tbd"&gt;npm&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Here's a basic example of how to use it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var data = tbd.from({ hello: 'world' }).make(10);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will create an array of 10 objects all which are identical. Since JavaScript doesn't have reflection like .NET there isn't a way to get an inferred type of a property, instead you have to assign it a 'default' value. This can have an advantage though as it means you can also only have tbd generate values for properties you actually want random data for. So how do you do values?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var data = tbd.from({ foo: 1 })
            .prop('foo').use(function() { return Math.random(); }).done()
            .make(10);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will create an array of 10 items which have a unique random number (well as unique as a random number can be :P) for the property &lt;code&gt;foo&lt;/code&gt;. To break down the way it works you need to understand the fluent API for properties.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Pass the property name to the &lt;code&gt;prop&lt;/code&gt; method as a string
&lt;ol&gt;
&lt;li&gt;&lt;em&gt;Pro tip - if the property name doesn't exist on the source object it'll still be added!&lt;/em&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;/li&gt;
&lt;li&gt;Pass a value or function into the &lt;code&gt;use&lt;/code&gt; method
&lt;ul&gt;
&lt;li&gt;If you pass a value that will be used for each object&lt;/li&gt;
&lt;li&gt;If you pass a function it'll be invoked for each object&lt;/li&gt;
&lt;li&gt;There's some helper methods we'll look at later&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;Call &lt;code&gt;done&lt;/code&gt; to signify you've finished with that property so you're back to the root API and allow you to modify more properties&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The last thing you always call is &lt;code&gt;make&lt;/code&gt; and specify the number of objects you want.&lt;/p&gt;

&lt;p&gt;And that's it, you can go off and create all the data you could ever want.&lt;/p&gt;

&lt;h2&gt;Making better fake data&lt;/h2&gt;

&lt;p&gt;Since tbd is a really dumb API if you don't tell it what to do with a property it wont do anything. So how do you produce &lt;em&gt;better fake data&lt;/em&gt;? That might sound like a silly question but say you're trying to build some graphs, you don't want all the data to be the same do you?&lt;/p&gt;

&lt;p&gt;Well to simplify this tbd ships with a number of useful utilities for generating better fake data. The full list you can get off the &lt;a href="https://github.com/aaronpowell/tbd/blob/master/README.md"&gt;readme&lt;/a&gt; but are some of the most useful IMO. All of these reside in the &lt;code&gt;tbd.utils&lt;/code&gt; namespace.&lt;/p&gt;

&lt;h3&gt;Pick a random value&lt;/h3&gt;

&lt;p&gt;Say you want to randomly choose a value from a set of values, say a bunch of different word, there's a handy method that'll do that called &lt;code&gt;random&lt;/code&gt; and you use it like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var data = tbd.from({ hello: 'world' })
            .prop('hello').use(tbd.utils.random('me', 'no me', 'why not me!')).done()
            .make(10);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This method takes &lt;em&gt;n number of arguments&lt;/em&gt; and it will randomly choose one of them for each object. You can pass in any data type that you want to this and it'll take a random from the list so you're not just restricted to strings.&lt;/p&gt;

&lt;h3&gt;Better random numbers and dates&lt;/h3&gt;

&lt;p&gt;While the &lt;code&gt;random&lt;/code&gt; method is great if you have a small set of data to go through but what if you don't? What if you want a random number between 1 and 1000? Typing that out would &lt;strong&gt;suck&lt;/strong&gt;. Well luckily there is the &lt;code&gt;range&lt;/code&gt; method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var data = tbd.from({ hello: 'world' })
            .prop('hello').use(tbd.utils.range(1, 1000)).done()
            .make(10);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For &lt;code&gt;range&lt;/code&gt; you pass in a min and max value and something from in there will be used. This method also supports dates so you can randomly choose a date from within a range.&lt;/p&gt;

&lt;h3&gt;Sequences&lt;/h3&gt;

&lt;p&gt;Sometimes you just want an ordered list of values and that's where &lt;code&gt;sequential&lt;/code&gt; comes in. Sequential you provide a start point and you'll get a value incremented by one each time from there:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var data = tbd.from({ hello: 'world' })
            .prop('hello').use(tbd.utils.sequential(1)).done()
            .make(10);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Note: I had a mistake in the initial post, the method is &lt;code&gt;sequential&lt;/code&gt; not &lt;code&gt;sequence&lt;/code&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h4&gt;Date sequences&lt;/h4&gt;

&lt;p&gt;One cool thing about the &lt;code&gt;sequential&lt;/code&gt; api is that you can provide it a date and it will increment that. By default the dates will shift one day at a time to get you to your new date:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;tbd.from({ date: new Date })
    .prop('foo').use(tbd.utils.sequential(new Date() /* optional parameter for date property the increment, default is 'd' */)
    .make(10);
//the 'day' property will be incremented by 1 from the starting value
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But you can overload this to increment by other date parts:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;y -&gt; Year&lt;/li&gt;
&lt;li&gt;M -&gt; Month&lt;/li&gt;
&lt;li&gt;d -&gt; Day (default)&lt;/li&gt;
&lt;li&gt;h -&gt; Hour&lt;/li&gt;
&lt;li&gt;m -&gt; Minutes&lt;/li&gt;
&lt;li&gt;s -&gt; Seconds&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;So this wraps up our look at &lt;code&gt;tbd&lt;/code&gt;, a useful little tool I wrote to make it easier to build out some fake data for when you're mocking a UI or to pump into a test.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/aaronpowell/tbd"&gt;Grab it today!&lt;/a&gt;&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/javascript/building-data-with-tbd" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fbuilding-data-with-tbd&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/javascript/building-data-with-tbd</feedburner:origLink></item><item><title>You don't need to use $.proxy</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/nO7wuNsnBsk/you-dont-need-jquery-proxy</link><category>jquery</category><category>javascript</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Sun, 11 Dec 2011 15:55:09 PST</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/javascript/you-dont-need-jquery-proxy</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>I've been recently going through some extending of a jQuery UI widget which a colleague had written when I came across quite a number of statements that were using the <a href="http://api.jquery.com/jQuery.proxy/">proxy</a> method from jQuery.</p>

<p>For anyone who's not familiar with the <code>proxy</code> method is allows you to take a function and specify a context (the <code>this</code> value) so when you pass it around for execution you always know what you're going to have as the context.</p>

<p>The method has been around for a while and it did serve a good purpose but these days its usefulness is becoming limited and I'm going to look at a few reasons as to why you shouldn't be using it.</p>

<h2>Understand this</h2>

<p>The most common reason I see that people will use <code>proxy</code> is because they don't understand how <code>this</code> works in JavaScript. While there are dozens of articles through your favourite search engine explaining <code>this</code> (<a href="http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/">here's a good start</a>) I'll do my best to give a quick overview.</p>

<p>When people come from C# they already have a notion of <code>this</code> and what it represents, unfortunately this is a broken assumption when moving to JavaScript. In C# <code>this</code> represents the current class which you're working within but since JavaScript <em>isn't</em> a classical language there isn't the concept of a <em>class</em> so you couldn't really associate it to one could you?</p>

<p>Instead <code>this</code> represents the context for which a function is executed for and different kinds of execution result in different contexts. Here's a few examples:</p>

<ul>
<li>Invoking a function from an object will set the context to the owner object</li>
<li>Invoking a function literal will set the context to the global object (<code>window</code> in a browser)</li>
<li>Invoking a function with apply/ call allows it to be controlled</li>
</ul>

<p>And this is why a lot of people get utterly confused with <code>this</code> in JavaScript.</p>

<p>But what does this have to do with the <code>$.proxy</code> method? As I said one of the most common reasons I see people using it is because they want to be able to access members of a particular object within a callback (such as a function called from an AJAX success). Because they are aware that in their outer function they can go <code>this.foo</code> they expect it to be available within the callback (after all isn't the callback in the same class?) but it will fail so they use <code>$.proxy</code> to ensure that they can access the member(s) they require.</p>

<p>So why is it a poor choice in this scenario? Well the reason is  that you can solve the problem in a much simpler fashion, by understanding JavaScript closures. You can draw a lot of similarities between JavaScript closures and C# closures, but the simplest explanation is that a variable will be within scope until all functions that require it have been descoped. But with the case of <code>this</code>, since it changes between function scopes the <code>var that = this</code> pattern emerged in JavaScript.</p>

<p>Let's have a look at some code:</p>

<pre><code>var foo = {
    makeRequest: function () {
        $.get('/foo', $.proxy(function (result) {
                this.update(result);
            }, this)
        );
    },

    update: function (data) { /* ... */ }
};

//somewhere later in the code
foo.makeRequest();
</code></pre>

<p>Here we're using the <code>proxy</code> method to make it possible to access the <code>update</code> method, since when we called the <code>makeRequest</code> method its <code>this</code> is a reference to <code>foo</code> (we're assuming that the assignment of <code>foo</code> is out of scope for the <code>makeRequest</code> method). So let's update it to use variable closures:</p>

<pre><code>var foo = {
    makeRequest: function () {
        var that = this;
        $.get('/foo',function (result) {
            that.update(result);
        });
    },

    update: function (data) { /* ... */ }
};

foo.makeRequest();
</code></pre>

<p>The difference here is that I'm assigning the value of <code>this</code> to a variable before the callback is created and inside the callback I refer back to the variable.</p>

<p>So why is this better than using <code>proxy</code>? The primary reason is readability, if you look at the first snippet you're intention is obscured by the use of <code>proxy</code> to change the scope. When someone who understands JavaScript comes to that snippet they have to know what the use of <code>proxy</code> is and why the <code>this</code> context needs to be controlled. With the second snippet it's clearer to see that you want to call the <code>update</code> method on the same object which <code>makeRequest</code> was invoked from.</p>

<h2>Use built-in methods</h2>

<p>An often missed note of JavaScript (well ECMAScript really) is that the functionality that is provided by <code>proxy</code> (and the similar methods in the other libraries) is built into the language, through the <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind">bind</a> method. The <code>bind</code> method was added as part of ECMAScript 5 and</p>

<blockquote>
  <p>Creates a new function that, when called, itself calls this function in the context of the provided this value, with a given sequence of arguments preceding any provided when the new function was called.</p>
</blockquote>

<p>Hmm that sounds pretty much like what you get from the <code>proxy</code> method yet it's built into the language.</p>

<p>This means that you can (potentially) get a performance boost (<a href="http://jsperf.com/bind-vs-jquery-proxy">check it out on JSPerf</a>) by using a native browser API rather than the wrapper. Also at the time of writing jQuery (1.7.1) doesn't use the native browser method it does the code itself.</p>

<p>Performance aside the main difference between the jQuery implementation and the ECMASCript 5 specification is the jQuery <code>proxy</code> method <em>does not throw a type error if the first argument is not a function</em> which the <a href="http://es5.github.com/#x15.3.4.5">spec states</a> <code>bind</code> will do. So although they are named differently they are providing the same functionality except for a critical check.</p>

<p>The take away from this point is that it's built into the language so using it makes a lot of sense and when you're in browsers that don't support it it's easy to polyfil the missing API (the mdn docs include the polyfil).</p>

<h2>Conclusion</h2>

<p>That wraps up my "rant" against using the <code>proxy</code> method in jQuery. The goal of this article was to teach you a bit more about the JavaScript language and that things people commonly try and work around have simpler solutions.</p>

<p>By understanding language concepts such as <code>this</code> and closures you can avoid manipulating scope.</p>

<p>By knowing what's new in the language you can use built-in APIs and make faster and more portable code.</p>
<img src="http://www.aaron-powell.com/via-feed/javascript/you-dont-need-jquery-proxy" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fyou-dont-need-jquery-proxy&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=nO7wuNsnBsk:qCP2-2LTBcM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=nO7wuNsnBsk:qCP2-2LTBcM:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=nO7wuNsnBsk:qCP2-2LTBcM:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/nO7wuNsnBsk" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;I've been recently going through some extending of a jQuery UI widget which a colleague had written when I came across quite a number of statements that were using the &lt;a href="http://api.jquery.com/jQuery.proxy/"&gt;proxy&lt;/a&gt; method from jQuery.&lt;/p&gt;

&lt;p&gt;For anyone who's not familiar with the &lt;code&gt;proxy&lt;/code&gt; method is allows you to take a function and specify a context (the &lt;code&gt;this&lt;/code&gt; value) so when you pass it around for execution you always know what you're going to have as the context.&lt;/p&gt;

&lt;p&gt;The method has been around for a while and it did serve a good purpose but these days its usefulness is becoming limited and I'm going to look at a few reasons as to why you shouldn't be using it.&lt;/p&gt;

&lt;h2&gt;Understand this&lt;/h2&gt;

&lt;p&gt;The most common reason I see that people will use &lt;code&gt;proxy&lt;/code&gt; is because they don't understand how &lt;code&gt;this&lt;/code&gt; works in JavaScript. While there are dozens of articles through your favourite search engine explaining &lt;code&gt;this&lt;/code&gt; (&lt;a href="http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/"&gt;here's a good start&lt;/a&gt;) I'll do my best to give a quick overview.&lt;/p&gt;

&lt;p&gt;When people come from C# they already have a notion of &lt;code&gt;this&lt;/code&gt; and what it represents, unfortunately this is a broken assumption when moving to JavaScript. In C# &lt;code&gt;this&lt;/code&gt; represents the current class which you're working within but since JavaScript &lt;em&gt;isn't&lt;/em&gt; a classical language there isn't the concept of a &lt;em&gt;class&lt;/em&gt; so you couldn't really associate it to one could you?&lt;/p&gt;

&lt;p&gt;Instead &lt;code&gt;this&lt;/code&gt; represents the context for which a function is executed for and different kinds of execution result in different contexts. Here's a few examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Invoking a function from an object will set the context to the owner object&lt;/li&gt;
&lt;li&gt;Invoking a function literal will set the context to the global object (&lt;code&gt;window&lt;/code&gt; in a browser)&lt;/li&gt;
&lt;li&gt;Invoking a function with apply/ call allows it to be controlled&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And this is why a lot of people get utterly confused with &lt;code&gt;this&lt;/code&gt; in JavaScript.&lt;/p&gt;

&lt;p&gt;But what does this have to do with the &lt;code&gt;$.proxy&lt;/code&gt; method? As I said one of the most common reasons I see people using it is because they want to be able to access members of a particular object within a callback (such as a function called from an AJAX success). Because they are aware that in their outer function they can go &lt;code&gt;this.foo&lt;/code&gt; they expect it to be available within the callback (after all isn't the callback in the same class?) but it will fail so they use &lt;code&gt;$.proxy&lt;/code&gt; to ensure that they can access the member(s) they require.&lt;/p&gt;

&lt;p&gt;So why is it a poor choice in this scenario? Well the reason is  that you can solve the problem in a much simpler fashion, by understanding JavaScript closures. You can draw a lot of similarities between JavaScript closures and C# closures, but the simplest explanation is that a variable will be within scope until all functions that require it have been descoped. But with the case of &lt;code&gt;this&lt;/code&gt;, since it changes between function scopes the &lt;code&gt;var that = this&lt;/code&gt; pattern emerged in JavaScript.&lt;/p&gt;

&lt;p&gt;Let's have a look at some code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var foo = {
    makeRequest: function () {
        $.get('/foo', $.proxy(function (result) {
                this.update(result);
            }, this)
        );
    },

    update: function (data) { /* ... */ }
};

//somewhere later in the code
foo.makeRequest();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here we're using the &lt;code&gt;proxy&lt;/code&gt; method to make it possible to access the &lt;code&gt;update&lt;/code&gt; method, since when we called the &lt;code&gt;makeRequest&lt;/code&gt; method its &lt;code&gt;this&lt;/code&gt; is a reference to &lt;code&gt;foo&lt;/code&gt; (we're assuming that the assignment of &lt;code&gt;foo&lt;/code&gt; is out of scope for the &lt;code&gt;makeRequest&lt;/code&gt; method). So let's update it to use variable closures:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var foo = {
    makeRequest: function () {
        var that = this;
        $.get('/foo',function (result) {
            that.update(result);
        });
    },

    update: function (data) { /* ... */ }
};

foo.makeRequest();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The difference here is that I'm assigning the value of &lt;code&gt;this&lt;/code&gt; to a variable before the callback is created and inside the callback I refer back to the variable.&lt;/p&gt;

&lt;p&gt;So why is this better than using &lt;code&gt;proxy&lt;/code&gt;? The primary reason is readability, if you look at the first snippet you're intention is obscured by the use of &lt;code&gt;proxy&lt;/code&gt; to change the scope. When someone who understands JavaScript comes to that snippet they have to know what the use of &lt;code&gt;proxy&lt;/code&gt; is and why the &lt;code&gt;this&lt;/code&gt; context needs to be controlled. With the second snippet it's clearer to see that you want to call the &lt;code&gt;update&lt;/code&gt; method on the same object which &lt;code&gt;makeRequest&lt;/code&gt; was invoked from.&lt;/p&gt;

&lt;h2&gt;Use built-in methods&lt;/h2&gt;

&lt;p&gt;An often missed note of JavaScript (well ECMAScript really) is that the functionality that is provided by &lt;code&gt;proxy&lt;/code&gt; (and the similar methods in the other libraries) is built into the language, through the &lt;a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind"&gt;bind&lt;/a&gt; method. The &lt;code&gt;bind&lt;/code&gt; method was added as part of ECMAScript 5 and&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Creates a new function that, when called, itself calls this function in the context of the provided this value, with a given sequence of arguments preceding any provided when the new function was called.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Hmm that sounds pretty much like what you get from the &lt;code&gt;proxy&lt;/code&gt; method yet it's built into the language.&lt;/p&gt;

&lt;p&gt;This means that you can (potentially) get a performance boost (&lt;a href="http://jsperf.com/bind-vs-jquery-proxy"&gt;check it out on JSPerf&lt;/a&gt;) by using a native browser API rather than the wrapper. Also at the time of writing jQuery (1.7.1) doesn't use the native browser method it does the code itself.&lt;/p&gt;

&lt;p&gt;Performance aside the main difference between the jQuery implementation and the ECMASCript 5 specification is the jQuery &lt;code&gt;proxy&lt;/code&gt; method &lt;em&gt;does not throw a type error if the first argument is not a function&lt;/em&gt; which the &lt;a href="http://es5.github.com/#x15.3.4.5"&gt;spec states&lt;/a&gt; &lt;code&gt;bind&lt;/code&gt; will do. So although they are named differently they are providing the same functionality except for a critical check.&lt;/p&gt;

&lt;p&gt;The take away from this point is that it's built into the language so using it makes a lot of sense and when you're in browsers that don't support it it's easy to polyfil the missing API (the mdn docs include the polyfil).&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;That wraps up my "rant" against using the &lt;code&gt;proxy&lt;/code&gt; method in jQuery. The goal of this article was to teach you a bit more about the JavaScript language and that things people commonly try and work around have simpler solutions.&lt;/p&gt;

&lt;p&gt;By understanding language concepts such as &lt;code&gt;this&lt;/code&gt; and closures you can avoid manipulating scope.&lt;/p&gt;

&lt;p&gt;By knowing what's new in the language you can use built-in APIs and make faster and more portable code.&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/javascript/you-dont-need-jquery-proxy" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fyou-dont-need-jquery-proxy&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/javascript/you-dont-need-jquery-proxy</feedburner:origLink></item><item><title>Xamlizer - How to implement something silly in JavaScript</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/1EPZMSmapzc/xamlizer-implementing-something-silly-in-javascript</link><category>javascript</category><category>doing-it-wrong</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Wed, 26 Oct 2011 11:10:12 PDT</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/javascript/xamlizer-implementing-something-silly-in-javascript</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>I've never done much Xaml development, I started reading a WPF book and played around with it only to realise I didn't have any understanding of this concept of a stateful application or how layouts were going to work. And as a web developer who never saw the appeal of Flash I also never got into Silverlight as there was never a problem in my life that it would solve.</p>

<p>The one thing I do remember from my brief foray into that scary other world is the reliance on <code>INotifyPropertyChanged</code> and <code>INotifyPropertyChanging</code> interfaces. I've always thought that the idea behind these two interfaces was a good one, the primary problem though is how you actually have to implement them. Seriously, there's a lot of shit code you have to implement.</p>

<p>So I decided to do something a bit silly, I decided to implement the two interfaces in JavaScript.</p>

<h4>A dumb idea with a point</h4>

<p>Now I see no real reason to use the code that I'm going to look at in any current development (I'll explain why later) but more importantly I want to look at something that is part of ECMAScript 5 that doesn't get the attention it deserves, <a href="http://es5.github.com/#x15.2.3.6"><code>Object.defineProperty</code></a>.</p>

<h2>JavaScript properties throughout history</h2>

<p>JavaScript, unlike languages such as C#, doesn't really have this concept of a property like you get there, the idea of a <em>get</em> and <em>set</em> operating being something that you can control. Really this is how a <em>class</em> in JavaScript with some public properties looks:</p>

<pre><code>var person = {
    firstName: 'Aaron',
    lastName: 'Powell'
};
</code></pre>

<p>And when we want to update a property we'd do something like this:</p>

<pre><code>person.firstName = 'John';
</code></pre>

<p>Now there's nothing wrong with this, it does what you'll want to do <em>in a lot of scenarios</em>, the problem is when you're wanting a slightly more complex scenario, say you want to react to a change to the <code>firstName</code> property, maybe perform some validation.</p>

<p>Let's assume we want to have an <code>age</code> property on our <code>person</code>. Obviously we want to make sure that <code>age</code> is at least 0 and probably less than 110 (sounds reasonable :P), well how do you do this?</p>

<ul>
<li>Validation before assigning the property?
<ul>
<li>That'll work, but what if we're exposing it to external API's? How can we enforce the validation to them?</li>
</ul></li>
</ul>

<h4>Functions as properties</h4>

<p>The general way which this problem is solved is to rather than use assignable properties you use functions as properties, making your code look like this:</p>

<pre><code>var person = (function() {
	var _age;

	return {
		//firstName, lastName, etc
		age: function(val) {
	      	if(val !== undefined &amp;&amp; (val &gt;= 0 &amp;&amp; val &lt;= 100) {
	        	_age = val;
	      	} else {
	        	//Raise an error
	      	}
	      	return _age;
    	}
	}
})();
</code></pre>

<p>Now we use the <code>age</code> property like so:</p>

<pre><code>person.age(27);
console.log(person.age()); //outputs 27
</code></pre>

<p>Now this isn't really <em>that</em> bad, the main pain point to it is that we now have a different way to assign the value, we do it through a function invocation rather than through an assignment statement. This can come to light if you're writing a JavaScript templating engine, you need to check if the <em>property</em> is actually a property or a function property. But we do get some nice stuff like the fact that in JavaScript you don't need to do overloads so we can have the one function perform both the <code>get</code> and <code>set</code> operation for our property.</p>

<p>Libraries such as <a href="http://knockoutjs.com">KnockoutJS</a> use this pattern for properties to do their UI binding but it can cause confusion, like in KnockoutJS if you want to bind to a property you'd do something like this: <code>data-bind="css: { someClass: someBoolean }"</code> which Knockout will understand it's an observable property and bind to the result of the function, but if you want to use the <strong>false</strong> value you need to do <code>data-bind="css: { someClass: !someBoolean() }"</code>. Note that this time it's <strong>invoked the property as a function</strong> rather than just using the property.</p>

<p>The can be a bit confusing and I've seen more than one developer (including myself) getting stumped as to why their bindings weren't working only to realise that it'd because they are binding to <code>!someBoolean</code> which equates to <code>!function() { }</code> rather than the <strong>result</strong> of the function. It's a very face-palm moment.</p>

<h2>Introducing ES5 properties</h2>

<p>As part of the ECMAScript 5 spec the concept of properties was addresses and has resulted in the <code>Object.defineProperty</code> API (and an API to define multiple at once, being <code>Object.defineProperties</code>) and this allows us to (among other things) define <code>get</code> and <code>set</code> method bodies for our properties.</p>

<p>Let's revisit our <code>person.age</code> property example from above, but do it using an ECMAScript 5 property:</p>

<pre><code>var person = (function() {
	var _age;

	var newPerson = { 
		firstName: 'Aaron',
		lastName: 'Powell'
	};

	Object.defineProperty(newPerson, 'age', {
		get: function() { return _age; },
		set: function(value) {
			if(value &amp;&amp; value &gt;= 0 &amp;&amp; value &lt;= 110) {
				_age = value
			} else {
				//raise error
			}
		}
	});

	return newPerson;
})();
person.age = 27;
console.log(person.age);
</code></pre>

<p>Hopefully you can see here the difference between the <em>function property</em> and the ES5 property.</p>

<p>With ES5 the property with a function body <em>looks just like a public field</em>. Now there's a few other things you can do here, such as make properties read-only and exclude them from <code>for...in</code> loops, and for that check out the <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty">MDN</a> (you can also do body-less properties), but it makes it very easy to build smarts into your objects. Also like .NET if you want to provide a <code>get</code>/<code>set</code> you need to have a backing store, but that's easy to get around with closure scope.</p>

<p>So that covers a basic look ES5 properties. Now back to our bad idea...</p>

<h2>Implementing INotifyPropertyChange in JavaScript</h2>

<p>As I demonstrated above it is possible to add a body to your properties let's do something with that idea.</p>

<p>If you're not familiar with <code>INotifyPropertyChang*</code> then you should read the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx">MSDN</a> <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanging.aspx">docs</a>. The <strong>TL;DR</strong> is that you use trigger the <code>Changing</code> event before you assign the property and then the <code>Changed</code> event after it's assigned and the UI can react.</p>

<p>As I said I think there's a lot of value in this pattern, it's just that as most Xaml devs will tell you implementing it is a real pain in the ass.</p>

<p>So say you wanted to implement it in JavaScript, it's not overly hard, ultimately we need to do something like this:</p>

<pre><code>Object.defineProperty(foo, 'prop', {
	get: function() { return _prop; },
	set: function(val) {
		propertyChanging(this, 'prop');
		_prop = val;
		propertyChanged(this, 'prop');	
	}
});
</code></pre>

<p>I've ignored the guff code like what the <code>propertyChang*</code> methods are doing as well as subscribing handlers to the events but you get the idea. This really don't look any different to the C# version though does it? So what's the point?</p>

<h3>Making it better through the magic of JavaScript</h3>

<p>As you can see there's a lot of boilerplate code that you need to get this working. In .NET there's no real way to avoid this (unless you do some magic under the covers). But one of the cool things about JavaScript being a dynamic language is that we can modify an object pretty damn easily. Let's go back to our <code>person</code> object:</p>

<pre><code>var person = {
	firstName: 'Aaron',
	lastName: 'Powell',
	age: 27
};
</code></pre>

<p>Now imagine that I want to implement my JavaScript version of <code>INotifyPropertyChang*</code> on it so that my UI can react whenever I update the values, but I don't want to be going through and writing this all out myself, I've got a bunch of objects that I want to <em>promote</em> to implementing the interfaces.</p>

<p>Well since JavaScript doesn't actually have interfaces in the language it's a bit tricky, and this is where my funky little script comes in.</p>

<p><strong>Hello Xamlizer!</strong></p>

<p>So I've created a little JavaScript code snippet which I've called <strong><a href="https://gist.github.com/1318702">Xamlizer</a></strong> that'll take an object and implement <code>INotifyPropertyChang*</code> on it. Now the script isn't really that smart, all it does is goes through all the properties of the object and then converts them into properties that implement our pattern.</p>

<p>You can then use it like this:</p>

<pre><code>var person = {
	firstName: 'Aaron',
	lastName: 'Powell',
	age: 27
};

xamlizer(person);
person.addPropertyChanging(function(object, property) {
	console.log('Property ' + property + 'changing');
});

person.age = 28;
</code></pre>

<p>And there we go, we've got a script that'll turn our normal JavaScript objects into something that can notify subscribers when the property changes.</p>

<p>If you dig into the code for Xamlizer you'll see that it doesn't do anything really complex, it just modifies some properties. <em>Note: As I said it's not really that smart, it actually modifies anything public on the object, so if you have a function that is public it might get crazy :P. But hey, it's just demo code!</em></p>

<p>And if you want to see it in action check out the <a href="http://jsfiddle.net/slace/Zemxm/">jsfiddle</a>.</p>

<h2>Conclusion</h2>

<p>Well this wraps up our look at the limitations in how you have to do properties in ES3, the changes which ES5 provides you with (although their usefulness at the moment is debatable since we have to support ES3 browsers for a while still) and finished off with looking at how to implement a generic library to change fields to properties with debatable usefulness.</p>
<img src="http://www.aaron-powell.com/via-feed/javascript/xamlizer-implementing-something-silly-in-javascript" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fxamlizer-implementing-something-silly-in-javascript&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=1EPZMSmapzc:O-BSEcxxpAo:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=1EPZMSmapzc:O-BSEcxxpAo:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=1EPZMSmapzc:O-BSEcxxpAo:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/1EPZMSmapzc" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;I've never done much Xaml development, I started reading a WPF book and played around with it only to realise I didn't have any understanding of this concept of a stateful application or how layouts were going to work. And as a web developer who never saw the appeal of Flash I also never got into Silverlight as there was never a problem in my life that it would solve.&lt;/p&gt;

&lt;p&gt;The one thing I do remember from my brief foray into that scary other world is the reliance on &lt;code&gt;INotifyPropertyChanged&lt;/code&gt; and &lt;code&gt;INotifyPropertyChanging&lt;/code&gt; interfaces. I've always thought that the idea behind these two interfaces was a good one, the primary problem though is how you actually have to implement them. Seriously, there's a lot of shit code you have to implement.&lt;/p&gt;

&lt;p&gt;So I decided to do something a bit silly, I decided to implement the two interfaces in JavaScript.&lt;/p&gt;

&lt;h4&gt;A dumb idea with a point&lt;/h4&gt;

&lt;p&gt;Now I see no real reason to use the code that I'm going to look at in any current development (I'll explain why later) but more importantly I want to look at something that is part of ECMAScript 5 that doesn't get the attention it deserves, &lt;a href="http://es5.github.com/#x15.2.3.6"&gt;&lt;code&gt;Object.defineProperty&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;JavaScript properties throughout history&lt;/h2&gt;

&lt;p&gt;JavaScript, unlike languages such as C#, doesn't really have this concept of a property like you get there, the idea of a &lt;em&gt;get&lt;/em&gt; and &lt;em&gt;set&lt;/em&gt; operating being something that you can control. Really this is how a &lt;em&gt;class&lt;/em&gt; in JavaScript with some public properties looks:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var person = {
    firstName: 'Aaron',
    lastName: 'Powell'
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And when we want to update a property we'd do something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;person.firstName = 'John';
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now there's nothing wrong with this, it does what you'll want to do &lt;em&gt;in a lot of scenarios&lt;/em&gt;, the problem is when you're wanting a slightly more complex scenario, say you want to react to a change to the &lt;code&gt;firstName&lt;/code&gt; property, maybe perform some validation.&lt;/p&gt;

&lt;p&gt;Let's assume we want to have an &lt;code&gt;age&lt;/code&gt; property on our &lt;code&gt;person&lt;/code&gt;. Obviously we want to make sure that &lt;code&gt;age&lt;/code&gt; is at least 0 and probably less than 110 (sounds reasonable :P), well how do you do this?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Validation before assigning the property?
&lt;ul&gt;
&lt;li&gt;That'll work, but what if we're exposing it to external API's? How can we enforce the validation to them?&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;Functions as properties&lt;/h4&gt;

&lt;p&gt;The general way which this problem is solved is to rather than use assignable properties you use functions as properties, making your code look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var person = (function() {
	var _age;

	return {
		//firstName, lastName, etc
		age: function(val) {
	      	if(val !== undefined &amp;amp;&amp;amp; (val &amp;gt;= 0 &amp;amp;&amp;amp; val &amp;lt;= 100) {
	        	_age = val;
	      	} else {
	        	//Raise an error
	      	}
	      	return _age;
    	}
	}
})();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we use the &lt;code&gt;age&lt;/code&gt; property like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;person.age(27);
console.log(person.age()); //outputs 27
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now this isn't really &lt;em&gt;that&lt;/em&gt; bad, the main pain point to it is that we now have a different way to assign the value, we do it through a function invocation rather than through an assignment statement. This can come to light if you're writing a JavaScript templating engine, you need to check if the &lt;em&gt;property&lt;/em&gt; is actually a property or a function property. But we do get some nice stuff like the fact that in JavaScript you don't need to do overloads so we can have the one function perform both the &lt;code&gt;get&lt;/code&gt; and &lt;code&gt;set&lt;/code&gt; operation for our property.&lt;/p&gt;

&lt;p&gt;Libraries such as &lt;a href="http://knockoutjs.com"&gt;KnockoutJS&lt;/a&gt; use this pattern for properties to do their UI binding but it can cause confusion, like in KnockoutJS if you want to bind to a property you'd do something like this: &lt;code&gt;data-bind="css: { someClass: someBoolean }"&lt;/code&gt; which Knockout will understand it's an observable property and bind to the result of the function, but if you want to use the &lt;strong&gt;false&lt;/strong&gt; value you need to do &lt;code&gt;data-bind="css: { someClass: !someBoolean() }"&lt;/code&gt;. Note that this time it's &lt;strong&gt;invoked the property as a function&lt;/strong&gt; rather than just using the property.&lt;/p&gt;

&lt;p&gt;The can be a bit confusing and I've seen more than one developer (including myself) getting stumped as to why their bindings weren't working only to realise that it'd because they are binding to &lt;code&gt;!someBoolean&lt;/code&gt; which equates to &lt;code&gt;!function() { }&lt;/code&gt; rather than the &lt;strong&gt;result&lt;/strong&gt; of the function. It's a very face-palm moment.&lt;/p&gt;

&lt;h2&gt;Introducing ES5 properties&lt;/h2&gt;

&lt;p&gt;As part of the ECMAScript 5 spec the concept of properties was addresses and has resulted in the &lt;code&gt;Object.defineProperty&lt;/code&gt; API (and an API to define multiple at once, being &lt;code&gt;Object.defineProperties&lt;/code&gt;) and this allows us to (among other things) define &lt;code&gt;get&lt;/code&gt; and &lt;code&gt;set&lt;/code&gt; method bodies for our properties.&lt;/p&gt;

&lt;p&gt;Let's revisit our &lt;code&gt;person.age&lt;/code&gt; property example from above, but do it using an ECMAScript 5 property:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var person = (function() {
	var _age;

	var newPerson = { 
		firstName: 'Aaron',
		lastName: 'Powell'
	};

	Object.defineProperty(newPerson, 'age', {
		get: function() { return _age; },
		set: function(value) {
			if(value &amp;amp;&amp;amp; value &amp;gt;= 0 &amp;amp;&amp;amp; value &amp;lt;= 110) {
				_age = value
			} else {
				//raise error
			}
		}
	});

	return newPerson;
})();
person.age = 27;
console.log(person.age);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hopefully you can see here the difference between the &lt;em&gt;function property&lt;/em&gt; and the ES5 property.&lt;/p&gt;

&lt;p&gt;With ES5 the property with a function body &lt;em&gt;looks just like a public field&lt;/em&gt;. Now there's a few other things you can do here, such as make properties read-only and exclude them from &lt;code&gt;for...in&lt;/code&gt; loops, and for that check out the &lt;a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/defineProperty"&gt;MDN&lt;/a&gt; (you can also do body-less properties), but it makes it very easy to build smarts into your objects. Also like .NET if you want to provide a &lt;code&gt;get&lt;/code&gt;/&lt;code&gt;set&lt;/code&gt; you need to have a backing store, but that's easy to get around with closure scope.&lt;/p&gt;

&lt;p&gt;So that covers a basic look ES5 properties. Now back to our bad idea...&lt;/p&gt;

&lt;h2&gt;Implementing INotifyPropertyChange in JavaScript&lt;/h2&gt;

&lt;p&gt;As I demonstrated above it is possible to add a body to your properties let's do something with that idea.&lt;/p&gt;

&lt;p&gt;If you're not familiar with &lt;code&gt;INotifyPropertyChang*&lt;/code&gt; then you should read the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx"&gt;MSDN&lt;/a&gt; &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanging.aspx"&gt;docs&lt;/a&gt;. The &lt;strong&gt;TL;DR&lt;/strong&gt; is that you use trigger the &lt;code&gt;Changing&lt;/code&gt; event before you assign the property and then the &lt;code&gt;Changed&lt;/code&gt; event after it's assigned and the UI can react.&lt;/p&gt;

&lt;p&gt;As I said I think there's a lot of value in this pattern, it's just that as most Xaml devs will tell you implementing it is a real pain in the ass.&lt;/p&gt;

&lt;p&gt;So say you wanted to implement it in JavaScript, it's not overly hard, ultimately we need to do something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Object.defineProperty(foo, 'prop', {
	get: function() { return _prop; },
	set: function(val) {
		propertyChanging(this, 'prop');
		_prop = val;
		propertyChanged(this, 'prop');	
	}
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I've ignored the guff code like what the &lt;code&gt;propertyChang*&lt;/code&gt; methods are doing as well as subscribing handlers to the events but you get the idea. This really don't look any different to the C# version though does it? So what's the point?&lt;/p&gt;

&lt;h3&gt;Making it better through the magic of JavaScript&lt;/h3&gt;

&lt;p&gt;As you can see there's a lot of boilerplate code that you need to get this working. In .NET there's no real way to avoid this (unless you do some magic under the covers). But one of the cool things about JavaScript being a dynamic language is that we can modify an object pretty damn easily. Let's go back to our &lt;code&gt;person&lt;/code&gt; object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var person = {
	firstName: 'Aaron',
	lastName: 'Powell',
	age: 27
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now imagine that I want to implement my JavaScript version of &lt;code&gt;INotifyPropertyChang*&lt;/code&gt; on it so that my UI can react whenever I update the values, but I don't want to be going through and writing this all out myself, I've got a bunch of objects that I want to &lt;em&gt;promote&lt;/em&gt; to implementing the interfaces.&lt;/p&gt;

&lt;p&gt;Well since JavaScript doesn't actually have interfaces in the language it's a bit tricky, and this is where my funky little script comes in.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hello Xamlizer!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So I've created a little JavaScript code snippet which I've called &lt;strong&gt;&lt;a href="https://gist.github.com/1318702"&gt;Xamlizer&lt;/a&gt;&lt;/strong&gt; that'll take an object and implement &lt;code&gt;INotifyPropertyChang*&lt;/code&gt; on it. Now the script isn't really that smart, all it does is goes through all the properties of the object and then converts them into properties that implement our pattern.&lt;/p&gt;

&lt;p&gt;You can then use it like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var person = {
	firstName: 'Aaron',
	lastName: 'Powell',
	age: 27
};

xamlizer(person);
person.addPropertyChanging(function(object, property) {
	console.log('Property ' + property + 'changing');
});

person.age = 28;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And there we go, we've got a script that'll turn our normal JavaScript objects into something that can notify subscribers when the property changes.&lt;/p&gt;

&lt;p&gt;If you dig into the code for Xamlizer you'll see that it doesn't do anything really complex, it just modifies some properties. &lt;em&gt;Note: As I said it's not really that smart, it actually modifies anything public on the object, so if you have a function that is public it might get crazy :P. But hey, it's just demo code!&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;And if you want to see it in action check out the &lt;a href="http://jsfiddle.net/slace/Zemxm/"&gt;jsfiddle&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Well this wraps up our look at the limitations in how you have to do properties in ES3, the changes which ES5 provides you with (although their usefulness at the moment is debatable since we have to support ES3 browsers for a while still) and finished off with looking at how to implement a generic library to change fields to properties with debatable usefulness.&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/javascript/xamlizer-implementing-something-silly-in-javascript" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fxamlizer-implementing-something-silly-in-javascript&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/javascript/xamlizer-implementing-something-silly-in-javascript</feedburner:origLink></item><item><title>Rebuilding JavaScript Quiz in Nodejs</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/r9S2L7R7AZs/rebuilding-javascript-quiz-in-nodejs</link><category>nodejs</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Wed, 12 Oct 2011 11:04:39 PDT</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/javascript/rebuilding-javascript-quiz-in-nodejs</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>A few months back I <a href="http://www.aaron-powell.com/javascript/javascript-quiz">announced a new site</a> I was running called <a href="http://javascriptquiz.com">JavaScript Quiz</a>. When I started to site it was to be done quickly so I chose an out-of-the-box blogging platform, that being <a href="http://posterous.com/">Posterous</a>.</p>

<p>Since then I've come to realise that it <em>isn't</em> the platform I want wanting to go with. One of my main problems with it is its comment management system. Anyone who has submitted an answer to me will know what I'm talking about, the excessive spam which you end up with when I do publish all the answers.</p>

<p>Well because of this I decided to move away from Posterous and go with a new platform. As my new platform I decided that I wanted to use <a href="http://nodejs.org">Node.js</a> because well this is a JavaScript quiz so why not use JavaScript!</p>

<h2>The software</h2>

<p>When looking at what I wanted to do with the new site I decided I wanted something that was easy to create a site in and also easy to update content it. A lot of people are raving about <a href="http://jekyllrb.com/">Jekyll</a> of recent, which is a Ruby <em>CMS</em> which runs a flat file system website and Markdown as an editing language.</p>

<p>This seemed ideal, JavaScript Quiz isn't a big site nor is it a dynamic site so something that runs off flat files is very ideal. I'm also quite a fan of Markdown (<a href="http://funnelweblog.com/what-is-markdown">which we use in FunnelWeb</a>) so being able to write my posts in that is very nice an idea.</p>

<p>So I started looking for a Node.js alternative as I'd prefer to use something than write it myself (<a href="http://www.aaron-powell.com/umbraco/so-long-and-thanks-for-all-the-fish">I'm a bit over developing a CMS at the moment</a>) and I came across a project called <a href="https://github.com/balupton/docpad">Docpad</a>.</p>

<h3>Intro to Docpad</h3>

<p>Docpad is a Node.js CMS in a similar style to Jekyll written by a guy from Sydney named <a href="http://twitter.com/balupton">Benjamin Lupton</a> (and I like supporting home-grown software so that was a big plus). It's got a good set of templating engines to pick from so you don't have to use raw HTML if you want something a bit more cool for your templates (more shortly) and best of all it's shit simple to use.</p>

<p>You need to install the following <a href="http://npmjs.org">npm</a> packages and you're off and running:</p>

<ul>
<li>coffee-script</li>
<li>express</li>
<li>docpad</li>
</ul>

<p>You're better off installing both <code>coffee-script</code> and <code>docpad</code> globally since they both have executables but you don't have to.</p>

<p><em>Note: I had problems using Node.js with cygwin on Windows, I couldn't get <code>docpad</code> to install but that seemed to be a cygwin issue as it worked fine on both my Linux and OSX machines, just something to watch out for :).</em></p>

<p>This isn't a Docpad tutorial, go check out the <a href="https://github.com/balupton/docpad/wiki">docs</a> if you want to learn more.</p>

<h3>Templates</h3>

<p>As I mentioned Docpad has a number of different HTML templating engines available, you can use <a href="https://github.com/sstephenson/eco">Eco</a>, <a href="https://github.com/visionmedia/jade">Jade</a>, <a href="http://haml-lang.com/">Haml</a> or the one I chose, <a href="http://coffeekup.org/">CoffeeKup</a>!</p>

<p>CoffeeKup is a way of using <a href="http://coffeescript.org">CoffeeScript</a> as a HTML template engine. It's pretty cool and it means that you're able to do some really powerful things with the templates and interacting with the document you're rendering. Plus it means that we're using JavaScript/ CofeeScript for most of our site (one language to rule them all!).</p>

<h3>CSS</h3>

<p>I'm not using any of the CSS templating engines (despite submitting a request for <a href="https://github.com/aeosynth/ccss">CCSS</a> to be included :P) mainly because I'm using <a href="http://h5bp.com">HTML5 Boiler Plate</a>'s css and I don't want to have to convert it every time I upgrade.</p>

<p>The rest of the CSS is really basic and I've just cobbled together so I can get the site live, expect it to be improved as I get more time.</p>

<h2>Fixing commenting</h2>

<p>As I mentioned commenting is something that was really a pain to anyone who was entering the quiz each week as you'd get spammed up with emails (don't worry, I got them all as well so it was <strong>very</strong> annoying). Good news is that the new site wont have this problem, I've gone with <a href="http://disqus.com">Disqus</a> for comments (still moderated) which means that it should be much nicer an experience.</p>

<p>From an admin point of view it's much nicer as well :).</p>

<h2>Hosting</h2>

<p>One advantage of Posterous was that it was a hosted solution so it wasn't costing me any more and this is something that I wanted to ensure didn't change. I decided that I'd go with <a href="http://heroku.com">Heroku</a> for my hosting since they have <a href="http://blog.heroku.com/archives/2011/6/22/the_new_heroku_2_node_js_new_http_routing_capabilities/">offered Node.js hosting for a while now</a>.</p>

<p>This means that I am also using Git to store the site and I have it hosted on GitHub at the moment (sorry it's not a public repo :P).</p>

<p>Because of this I have a nice workflow of being able to edit my content, run it through the Docpad 'compiler' and commit in the generated HTML. This then goes up to Heroku and just runs off the flat files.</p>

<p>Ideally I'd not be committing the generated files and have part of the app startup code generate the files but so far I've had nothing but trouble getting it working that way. Heroku's cedar stack (which is where node.js runs) <strong>is</strong> a writable file system but something still seems to be going amiss (and it's not exactly easy to dig into...).</p>

<h2>Wrap up</h2>

<p>So this is how I've gone about the relaunch of JavaScript Quiz. The new site should be active soon (awaiting the DNS to change over :P). I wont be porting the old comments so the old site will stay active. Hopefully I've got the redirects all sorted out (yes the 404 page is pretty shit so far :P). Hopefully this provides a nice new home for the site.</p>
<img src="http://www.aaron-powell.com/via-feed/javascript/rebuilding-javascript-quiz-in-nodejs" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2frebuilding-javascript-quiz-in-nodejs&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=r9S2L7R7AZs:gmbQFJ-3lUA:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=r9S2L7R7AZs:gmbQFJ-3lUA:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=r9S2L7R7AZs:gmbQFJ-3lUA:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/r9S2L7R7AZs" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;A few months back I &lt;a href="http://www.aaron-powell.com/javascript/javascript-quiz"&gt;announced a new site&lt;/a&gt; I was running called &lt;a href="http://javascriptquiz.com"&gt;JavaScript Quiz&lt;/a&gt;. When I started to site it was to be done quickly so I chose an out-of-the-box blogging platform, that being &lt;a href="http://posterous.com/"&gt;Posterous&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Since then I've come to realise that it &lt;em&gt;isn't&lt;/em&gt; the platform I want wanting to go with. One of my main problems with it is its comment management system. Anyone who has submitted an answer to me will know what I'm talking about, the excessive spam which you end up with when I do publish all the answers.&lt;/p&gt;

&lt;p&gt;Well because of this I decided to move away from Posterous and go with a new platform. As my new platform I decided that I wanted to use &lt;a href="http://nodejs.org"&gt;Node.js&lt;/a&gt; because well this is a JavaScript quiz so why not use JavaScript!&lt;/p&gt;

&lt;h2&gt;The software&lt;/h2&gt;

&lt;p&gt;When looking at what I wanted to do with the new site I decided I wanted something that was easy to create a site in and also easy to update content it. A lot of people are raving about &lt;a href="http://jekyllrb.com/"&gt;Jekyll&lt;/a&gt; of recent, which is a Ruby &lt;em&gt;CMS&lt;/em&gt; which runs a flat file system website and Markdown as an editing language.&lt;/p&gt;

&lt;p&gt;This seemed ideal, JavaScript Quiz isn't a big site nor is it a dynamic site so something that runs off flat files is very ideal. I'm also quite a fan of Markdown (&lt;a href="http://funnelweblog.com/what-is-markdown"&gt;which we use in FunnelWeb&lt;/a&gt;) so being able to write my posts in that is very nice an idea.&lt;/p&gt;

&lt;p&gt;So I started looking for a Node.js alternative as I'd prefer to use something than write it myself (&lt;a href="http://www.aaron-powell.com/umbraco/so-long-and-thanks-for-all-the-fish"&gt;I'm a bit over developing a CMS at the moment&lt;/a&gt;) and I came across a project called &lt;a href="https://github.com/balupton/docpad"&gt;Docpad&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;Intro to Docpad&lt;/h3&gt;

&lt;p&gt;Docpad is a Node.js CMS in a similar style to Jekyll written by a guy from Sydney named &lt;a href="http://twitter.com/balupton"&gt;Benjamin Lupton&lt;/a&gt; (and I like supporting home-grown software so that was a big plus). It's got a good set of templating engines to pick from so you don't have to use raw HTML if you want something a bit more cool for your templates (more shortly) and best of all it's shit simple to use.&lt;/p&gt;

&lt;p&gt;You need to install the following &lt;a href="http://npmjs.org"&gt;npm&lt;/a&gt; packages and you're off and running:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;coffee-script&lt;/li&gt;
&lt;li&gt;express&lt;/li&gt;
&lt;li&gt;docpad&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You're better off installing both &lt;code&gt;coffee-script&lt;/code&gt; and &lt;code&gt;docpad&lt;/code&gt; globally since they both have executables but you don't have to.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: I had problems using Node.js with cygwin on Windows, I couldn't get &lt;code&gt;docpad&lt;/code&gt; to install but that seemed to be a cygwin issue as it worked fine on both my Linux and OSX machines, just something to watch out for :).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This isn't a Docpad tutorial, go check out the &lt;a href="https://github.com/balupton/docpad/wiki"&gt;docs&lt;/a&gt; if you want to learn more.&lt;/p&gt;

&lt;h3&gt;Templates&lt;/h3&gt;

&lt;p&gt;As I mentioned Docpad has a number of different HTML templating engines available, you can use &lt;a href="https://github.com/sstephenson/eco"&gt;Eco&lt;/a&gt;, &lt;a href="https://github.com/visionmedia/jade"&gt;Jade&lt;/a&gt;, &lt;a href="http://haml-lang.com/"&gt;Haml&lt;/a&gt; or the one I chose, &lt;a href="http://coffeekup.org/"&gt;CoffeeKup&lt;/a&gt;!&lt;/p&gt;

&lt;p&gt;CoffeeKup is a way of using &lt;a href="http://coffeescript.org"&gt;CoffeeScript&lt;/a&gt; as a HTML template engine. It's pretty cool and it means that you're able to do some really powerful things with the templates and interacting with the document you're rendering. Plus it means that we're using JavaScript/ CofeeScript for most of our site (one language to rule them all!).&lt;/p&gt;

&lt;h3&gt;CSS&lt;/h3&gt;

&lt;p&gt;I'm not using any of the CSS templating engines (despite submitting a request for &lt;a href="https://github.com/aeosynth/ccss"&gt;CCSS&lt;/a&gt; to be included :P) mainly because I'm using &lt;a href="http://h5bp.com"&gt;HTML5 Boiler Plate&lt;/a&gt;'s css and I don't want to have to convert it every time I upgrade.&lt;/p&gt;

&lt;p&gt;The rest of the CSS is really basic and I've just cobbled together so I can get the site live, expect it to be improved as I get more time.&lt;/p&gt;

&lt;h2&gt;Fixing commenting&lt;/h2&gt;

&lt;p&gt;As I mentioned commenting is something that was really a pain to anyone who was entering the quiz each week as you'd get spammed up with emails (don't worry, I got them all as well so it was &lt;strong&gt;very&lt;/strong&gt; annoying). Good news is that the new site wont have this problem, I've gone with &lt;a href="http://disqus.com"&gt;Disqus&lt;/a&gt; for comments (still moderated) which means that it should be much nicer an experience.&lt;/p&gt;

&lt;p&gt;From an admin point of view it's much nicer as well :).&lt;/p&gt;

&lt;h2&gt;Hosting&lt;/h2&gt;

&lt;p&gt;One advantage of Posterous was that it was a hosted solution so it wasn't costing me any more and this is something that I wanted to ensure didn't change. I decided that I'd go with &lt;a href="http://heroku.com"&gt;Heroku&lt;/a&gt; for my hosting since they have &lt;a href="http://blog.heroku.com/archives/2011/6/22/the_new_heroku_2_node_js_new_http_routing_capabilities/"&gt;offered Node.js hosting for a while now&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This means that I am also using Git to store the site and I have it hosted on GitHub at the moment (sorry it's not a public repo :P).&lt;/p&gt;

&lt;p&gt;Because of this I have a nice workflow of being able to edit my content, run it through the Docpad 'compiler' and commit in the generated HTML. This then goes up to Heroku and just runs off the flat files.&lt;/p&gt;

&lt;p&gt;Ideally I'd not be committing the generated files and have part of the app startup code generate the files but so far I've had nothing but trouble getting it working that way. Heroku's cedar stack (which is where node.js runs) &lt;strong&gt;is&lt;/strong&gt; a writable file system but something still seems to be going amiss (and it's not exactly easy to dig into...).&lt;/p&gt;

&lt;h2&gt;Wrap up&lt;/h2&gt;

&lt;p&gt;So this is how I've gone about the relaunch of JavaScript Quiz. The new site should be active soon (awaiting the DNS to change over :P). I wont be porting the old comments so the old site will stay active. Hopefully I've got the redirects all sorted out (yes the 404 page is pretty shit so far :P). Hopefully this provides a nice new home for the site.&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/javascript/rebuilding-javascript-quiz-in-nodejs" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2frebuilding-javascript-quiz-in-nodejs&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/javascript/rebuilding-javascript-quiz-in-nodejs</feedburner:origLink></item><item><title>Tips for travelling as a geek</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/21juzQOx-p4/tips-for-travelling-as-a-geek</link><category>random</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Thu, 13 Oct 2011 09:11:44 PDT</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/tips-for-travelling-as-a-geek</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Anyone who follows me on <a href="http://twitter.com/slace">twitter</a> will have probably noticed that in the last two weeks I've been tweeting with a geolocation in Vietnam. If you're really smart you may have worked out that I was on holidays over there!</p>

<p>I had a bit of tech with me, an iPad, iPhone, laptop and 2 kindles so I thought I'd share some of my experiences and tips for travelling as a geek.</p>

<h2>Stay connected</h2>

<p>Something that I find is very useful when travelling is having access to the internet. It allows me to do those useful things such as email/ skype my parents, use google maps and check in on foursquare.</p>

<p>So my first pointer when going overseas is work out how you plan to stay connected. Most hotels I've stayed in recently have had free wifi so if that's good enough for you then check out the places you plan to stay. Also a lot of cafe's and bars (particularly ones targeting travellers) offer free wifi so that can allow you your mid-day twitter fix.</p>

<p>The other option is picking up a local sim. I've been to the USA, Denmark and Vietnam this year and all those countries have prepaid sims which you can pick up and drop into your device. For the USA check out things like <a href="http://www.wireless.att.com/cell-phone-service/go-phones/index.jsp#fbid=xkUQSfBVUcY">GoPhone</a> from AT&amp;T. In Denmark I picked up a sim card from the post office (don't remember who the provider was though) for 99 Danish Krone that lasted for 1 week and in Vietnam I got a sim for a month for the whole of $1USD!</p>

<p>So before you go check out the country and you'll probably find an easy way to pick up a sim card. We found this really useful in Vietnam as it meant we could look up an address rather than relying on shitty maps in guide books, saving an argument or two with the girlfriend :P.</p>

<p><strong>Before you go for a local sim card make sure your phone is network unlocked. I ended up in Denmark with a network locked phone and my sim wasn't usable in it :(</strong></p>

<h2>Internet beats books</h2>

<p>Like a studious traveller we picked up our copy of the <a href="http://www.lonelyplanet.com/">Lonely Planet</a> but by the end of the trip we were only use it for one purpose, the find out where <strong>not</strong> to go.</p>

<p>Now I don't want to rag on Lonely Planet too much but it's really hard for a print book to keep pace with the internet. Instead we turned to good ol' technology (since I had a local sim) to find out stuff to do. Now I want to talk about two sites that are invaluable if you're travelling.</p>

<h3>Wikitravel</h3>

<p>Url: <a href="http://wikitravel.org">http://wikitravel.org</a></p>

<p>Wikitravel is the wikipedia of travel websites. It's got lots of great tips on history of a place, what to see while you're there how to get in, out and around. The kind of stuff you can get out of a Lonely Planet guide book but it is able to be kept up to date (say around pricing of cabs). It can even give you those handy tips that you wont find out until you've hit them (such as Melbourne trams having coin-only ticket machines).</p>

<p>That said be careful of vandalism/ shameless self promotion on the site, you'll occasionally find companies promoting themselves on there. It's generally pretty easy to pick them though.</p>

<h3>Trip Advisor</h3>

<p>Url: <a href="http://www.tripadvisor.com/">http://www.tripadvisor.com/</a></p>

<p>Trip Advisor is a <strong>must</strong> when you're planning your trip and when you're away. The site is full of user generated content and allows for people to enter information about places they've visited, stayed, eaten at, etc and then vote against them.</p>

<p>Again this is something that kills Lonely Planet. Where Lonely Planet can only have a finite amount of places listed and gets out of date, a site based around generate content can reflect the actual mood of travellers to an area.</p>

<p>We used this to find recommendations for hotels, places to eat or just check out others opinions for places we got recommended by friends.</p>

<h2>Have adapters</h2>

<p>It goes without saying that when you're travelling having local power adapters is a valuable thing but what I found more valuable was carrying a multi-port adapter. Don't go crazy and take like a 10 port power board if you only have 2 devices but they can be handy (particularly if you're travelling for work as well as play).</p>

<h2>Travel insurance</h2>

<p>It goes without saying that you should have travel insurance with you but make sure that your policy will cover you for the devices you are carrying with you. Last thing you want is to lose your laptop and find out that you only had $500 of coverage!</p>

<p>I went with <a href="http://www.travelinsurancedirect.com.au/">Travel Insurance Direct</a> who have a reasonably well priced set of plans including yearly world-wide plans.</p>

<h2>TL;DR</h2>

<ul>
<li>Get a local sim</li>
<li>Use <a href="http://wikitravel.org">WikiTravel</a> and <a href="http://www.tripadvisor.com/">Trip Advisor</a></li>
<li>Make sure your travel insurance will cover your gear</li>
</ul>
<img src="http://www.aaron-powell.com/via-feed/tips-for-travelling-as-a-geek" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2ftips-for-travelling-as-a-geek&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=21juzQOx-p4:YaS9y0d0Jj0:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=21juzQOx-p4:YaS9y0d0Jj0:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=21juzQOx-p4:YaS9y0d0Jj0:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/21juzQOx-p4" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Anyone who follows me on &lt;a href="http://twitter.com/slace"&gt;twitter&lt;/a&gt; will have probably noticed that in the last two weeks I've been tweeting with a geolocation in Vietnam. If you're really smart you may have worked out that I was on holidays over there!&lt;/p&gt;

&lt;p&gt;I had a bit of tech with me, an iPad, iPhone, laptop and 2 kindles so I thought I'd share some of my experiences and tips for travelling as a geek.&lt;/p&gt;

&lt;h2&gt;Stay connected&lt;/h2&gt;

&lt;p&gt;Something that I find is very useful when travelling is having access to the internet. It allows me to do those useful things such as email/ skype my parents, use google maps and check in on foursquare.&lt;/p&gt;

&lt;p&gt;So my first pointer when going overseas is work out how you plan to stay connected. Most hotels I've stayed in recently have had free wifi so if that's good enough for you then check out the places you plan to stay. Also a lot of cafe's and bars (particularly ones targeting travellers) offer free wifi so that can allow you your mid-day twitter fix.&lt;/p&gt;

&lt;p&gt;The other option is picking up a local sim. I've been to the USA, Denmark and Vietnam this year and all those countries have prepaid sims which you can pick up and drop into your device. For the USA check out things like &lt;a href="http://www.wireless.att.com/cell-phone-service/go-phones/index.jsp#fbid=xkUQSfBVUcY"&gt;GoPhone&lt;/a&gt; from AT&amp;amp;T. In Denmark I picked up a sim card from the post office (don't remember who the provider was though) for 99 Danish Krone that lasted for 1 week and in Vietnam I got a sim for a month for the whole of $1USD!&lt;/p&gt;

&lt;p&gt;So before you go check out the country and you'll probably find an easy way to pick up a sim card. We found this really useful in Vietnam as it meant we could look up an address rather than relying on shitty maps in guide books, saving an argument or two with the girlfriend :P.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Before you go for a local sim card make sure your phone is network unlocked. I ended up in Denmark with a network locked phone and my sim wasn't usable in it :(&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;Internet beats books&lt;/h2&gt;

&lt;p&gt;Like a studious traveller we picked up our copy of the &lt;a href="http://www.lonelyplanet.com/"&gt;Lonely Planet&lt;/a&gt; but by the end of the trip we were only use it for one purpose, the find out where &lt;strong&gt;not&lt;/strong&gt; to go.&lt;/p&gt;

&lt;p&gt;Now I don't want to rag on Lonely Planet too much but it's really hard for a print book to keep pace with the internet. Instead we turned to good ol' technology (since I had a local sim) to find out stuff to do. Now I want to talk about two sites that are invaluable if you're travelling.&lt;/p&gt;

&lt;h3&gt;Wikitravel&lt;/h3&gt;

&lt;p&gt;Url: &lt;a href="http://wikitravel.org"&gt;http://wikitravel.org&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Wikitravel is the wikipedia of travel websites. It's got lots of great tips on history of a place, what to see while you're there how to get in, out and around. The kind of stuff you can get out of a Lonely Planet guide book but it is able to be kept up to date (say around pricing of cabs). It can even give you those handy tips that you wont find out until you've hit them (such as Melbourne trams having coin-only ticket machines).&lt;/p&gt;

&lt;p&gt;That said be careful of vandalism/ shameless self promotion on the site, you'll occasionally find companies promoting themselves on there. It's generally pretty easy to pick them though.&lt;/p&gt;

&lt;h3&gt;Trip Advisor&lt;/h3&gt;

&lt;p&gt;Url: &lt;a href="http://www.tripadvisor.com/"&gt;http://www.tripadvisor.com/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Trip Advisor is a &lt;strong&gt;must&lt;/strong&gt; when you're planning your trip and when you're away. The site is full of user generated content and allows for people to enter information about places they've visited, stayed, eaten at, etc and then vote against them.&lt;/p&gt;

&lt;p&gt;Again this is something that kills Lonely Planet. Where Lonely Planet can only have a finite amount of places listed and gets out of date, a site based around generate content can reflect the actual mood of travellers to an area.&lt;/p&gt;

&lt;p&gt;We used this to find recommendations for hotels, places to eat or just check out others opinions for places we got recommended by friends.&lt;/p&gt;

&lt;h2&gt;Have adapters&lt;/h2&gt;

&lt;p&gt;It goes without saying that when you're travelling having local power adapters is a valuable thing but what I found more valuable was carrying a multi-port adapter. Don't go crazy and take like a 10 port power board if you only have 2 devices but they can be handy (particularly if you're travelling for work as well as play).&lt;/p&gt;

&lt;h2&gt;Travel insurance&lt;/h2&gt;

&lt;p&gt;It goes without saying that you should have travel insurance with you but make sure that your policy will cover you for the devices you are carrying with you. Last thing you want is to lose your laptop and find out that you only had $500 of coverage!&lt;/p&gt;

&lt;p&gt;I went with &lt;a href="http://www.travelinsurancedirect.com.au/"&gt;Travel Insurance Direct&lt;/a&gt; who have a reasonably well priced set of plans including yearly world-wide plans.&lt;/p&gt;

&lt;h2&gt;TL;DR&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Get a local sim&lt;/li&gt;
&lt;li&gt;Use &lt;a href="http://wikitravel.org"&gt;WikiTravel&lt;/a&gt; and &lt;a href="http://www.tripadvisor.com/"&gt;Trip Advisor&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Make sure your travel insurance will cover your gear&lt;/li&gt;
&lt;/ul&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/tips-for-travelling-as-a-geek" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2ftips-for-travelling-as-a-geek&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/tips-for-travelling-as-a-geek</feedburner:origLink></item><item><title>Creating a ViewModel from the server</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/KK_3zcrF7b8/creating-vms-from-server</link><category>knockoutjs</category><category>javascript</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Wed, 21 Sep 2011 12:14:19 PDT</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/javascript/creating-vms-from-server</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>If you've been doing much work with <a href="http://knockoutjs.com">KnockoutJS</a> you'll probably see examples where the code looks like this:</p>

<pre><code>var todoViewModel = function() {
    this.items = new ko.observableArray(['Item 1', 'Item 2', 'Item 3']);
    this.selectedItem = new ko.observable('Item 1');
};
</code></pre>

<p>What I'm trying to point out here is that the <code>viewModel</code> is being defined in JavaScript and that the items within it are coded into your JavaScript.</p>

<p>While you can argue that this is demo code and it should only be treated as such something I've noticed is <em>there isn't any other examples</em>. I haven't seen any example where they are talking about getting the data initially from the server for their viewModel.</p>

<p>So how do you approach this? In this article I'm going to look at how to create a viewModel from the server using ASP.Net MVC.</p>

<p><em>Note: I'm talking about doing a viewModel as part of the initial page load since generally speaking you'll have been doing data layer interaction as part of the request. Building a viewModel using an AJAX request is a different story and I wont be covering.</em></p>

<h2>From the server to the client</h2>

<p>Let's get started with an example of our controller:</p>

<pre><code>public class TaskController : Controller
{
    public ActionResult Index()
    {
        var vm = new TaskViewModel
                     {
                         Tasks = new[] { new Task("Write Blog Post"), new Task("Publish Blog Post") }
                     };

        return View(vm);
    }
}
</code></pre>

<p>I'm just going to have a reasonably simple ViewModel that just has a collection of tasks that I want to display as part of my KnockoutJS-built UI but the tasks are to be pulled in from my data layer (obviously this is demo code and it's hard coded so you'll have to use your imagination for that part :P).</p>

<p>For the view I'm just creating something that is very simple for the task list:</p>

<pre><code>&lt;form data-bind="submit:addTask"&gt;
    Add task: &lt;input type="text" data-bind='value:taskToAdd, valueUpdate: "afterkeydown"' /&gt;
    &lt;button type="submit" data-bind="enable: taskToAdd().length &gt; 0"&gt;Add&lt;/button&gt;
&lt;/form&gt;

&lt;p&gt;Your values:&lt;/p&gt;
&lt;select multiple="multiple" height="5" data-bind="options:tasks"&gt; &lt;/select&gt;

&lt;div&gt;
    &lt;button data-bind="click: removeSelected, enable: hasTasks"&gt;Remove&lt;/button&gt;
    &lt;button data-bind="click: sortTasks, enable: hasTasks"&gt;Sort&lt;/button&gt;
&lt;/div&gt;
</code></pre>

<p>Now we have a conundrum, how do I as part of my response create a KnockoutJS ViewModel that I can then use in my UI?</p>

<h2>It's all about the serialization</h2>

<p>When I was prototyping this for my current project I remembers that <a href="http://twitter.com/#!/shazwazza">Shannon</a> has mentioned that he'd done something similar himself and I've shamelessly taken his approach and am using it :P.</p>

<p>His approach was to use a serializer to create a JSON object from the model (there was some other stuff in the skype message he sent me but I'll confess to having not read that :P). For the serialization you can use the <a href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx">JavaScriptSerializer</a>, the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx">DataContractJsonSerializer</a> or <a href="http://json.codeplex.com/">Json.NET</a>. Personally I prefer Json.NET and it's what I'll be using in this demo.</p>

<p>So let's make a little HTML helper to do this for us:</p>

<pre><code>public static class HtmlHelperExtensions
{
    public static IHtmlString KnockoutFrom&lt;T&gt;(this HtmlHelper&lt;T&gt; html, T obj)
    {
        var serializer = new JsonSerializer
                             {
                                 ContractResolver = new CamelCasePropertyNamesContractResolver()
                             };

        return new HtmlString(JObject.FromObject(obj, serializer).ToString());
    }
}
</code></pre>

<p>All we're doing here is creating an instance of the <code>JsonSerializer</code> from Json.NET and telling it to use the <code>CamelCasePropertyNamesContractResolver</code>. This is why I like Json.NET, it allows me to convert my .NET naming conventions into JavaScript conventions without a lot of effort. Lastly we just return the serialized object. Not really anything special happening in here.</p>

<p>Now in my View I can do this:</p>

<pre><code>@Html.KnockoutFrom(Model)
</code></pre>

<p>Hmm but this isn't really helpful, we're just getting out JSON blob in our view, I still would have to do a bunch of work to actually make it usable and especially if I am doing this on a lot of pages it's a lot of code that I'd prefer not to do every time. So let's see if we can improve our extension method.</p>

<h2>Setting up the viewModel</h2>

<p>So what do we want from our improved version? Well I'd like the observables to be set up for me and I'd like it to avoid global variables.</p>

<p>To do this what I'm going to do is update my extension method to use the <a href="http://knockoutjs.com/documentation/plugins-mapping.html">Knockout Mapping plugin</a>. This plugin is really sweet as it allows me to map a JSON object into a KnockoutJS object and is great when you're working with AJAX data, you can easily pull down some data from the server and then use the plugin to extend it into your ViewModel.</p>

<p>In this case though I'm going to use it to map the JSON version of our server ViewModel into our KnockoutJS one:</p>

<pre><code>    public static IHtmlString KnockoutFrom&lt;T&gt;(this HtmlHelper&lt;T&gt; html, T obj)
    {
        var serializer = new JsonSerializer
                             {
                                 ContractResolver = new CamelCasePropertyNamesContractResolver()
                             };

        var sb = new StringBuilder();
        sb.Append("(function() {");

        var json = JObject.FromObject(obj, serializer);

        sb.Append("var vm = ko.mapping.fromJS(" + json + ");");

        sb.Append("ko.applyBindings(vm);");

        sb.Append("})();");

        return new HtmlString(sb.ToString());
    }
</code></pre>

<p>The main updates here are:</p>

<ul>
<li>I'm using a <code>StringBuilder</code> to build up some JavaScript (normally I hate server-generated JavaScript but here it serves a good purpose)</li>
<li>I'm creating an <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/">immediately-invoked function expression</a> to prevent leakage</li>
<li>I'm doing my binding straight away, hiding the need for that too</li>
</ul>

<p>Excellent, this works, at least it works to an extent as we still have a few problems:</p>

<ul>
<li>What if I want to restrict where the binding happens?</li>
<li>What about adding methods to my KnockoutJS viewModel?</li>
</ul>

<h2>Improving interactivity</h2>

<p>While the above will work fine for simple scenarios it's not great if you have a complex UI that you want to work with, and realistically it's not likely you'll have a viewModel you don't want  to extend with dependantObservables or anything, so let's do some refactoring.</p>

<p>I'm going to change the end of my extension method to look like this:</p>

<pre><code>        sb.Append("var vm = ko.mapping.fromJS(" + json + ");");

        var type = obj.GetType();

        var ns = JavaScriptify(type.Namespace);
        sb.Append("namespace('" + ns + "');");
        sb.Append(ns + "." + JavaScriptify(type.Name) + " = vm;");

        sb.Append("})();");

        return new HtmlString(sb.ToString());
</code></pre>

<p>What I've done here is instead of doing the bindings I'm just going to create a global object which the viewModel will be assigned to (but I am <a href="http://www.aaron-powell.com/slace-core-javascript-library">namespacing</a> it so it's a bit better). This object I can then interact with in my JavaScript and add methods/ properties/ etc to myself.</p>

<p>I'm also using a helper method to make the .NET namespace &amp; type names friendlier for JavaScript:</p>

<pre><code>    private static string JavaScriptify(string s)
    {
        return string.Join(".", s.Split('.').Select(x =&gt; x[0].ToString().ToLower() + x.Substring(1, x.Length - 1)));
    }
</code></pre>

<p>With this new extension method I can update my View to play around with the viewModel before binding:</p>

<pre><code>&lt;script&gt;
    @Html.KnockoutFrom(Model)

    $(function() {
        var model = knockout.serverViewModels.models.taskViewModel;

        model.addTask = function() {};
        model.taskToAdd = new ko.observable('');
        model.removeSelected = function() {};
        model.hasTasks = function() {};
        model.sortTasks = function() {};

        ko.applyBindings(model);
    });
&lt;/script&gt;
</code></pre>

<h2>Conclusion</h2>

<p>This wraps up my post on how to convert your server ViewModel into something that can be used in your KnockoutJS, allowing you to push all data down in the initial request rather than subsequent ones.</p>

<p>Thanks to Shannon for the initial idea, hopefully this little extension will make it even easier.</p>

<p>If you want to grab the code it is <a href="http://hg.apwll.me/knockoutjs-server-viewmodels">available here</a>.</p>

<p>One final note, the Json.NET serializer <strong>does</strong> support the <code>DataMember</code> attributes, so you can also selectively include properties from your server ViewModel by attributing them too.</p>
<img src="http://www.aaron-powell.com/via-feed/javascript/creating-vms-from-server" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fcreating-vms-from-server&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=KK_3zcrF7b8:i8yeO4nPpDg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=KK_3zcrF7b8:i8yeO4nPpDg:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=KK_3zcrF7b8:i8yeO4nPpDg:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/KK_3zcrF7b8" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;If you've been doing much work with &lt;a href="http://knockoutjs.com"&gt;KnockoutJS&lt;/a&gt; you'll probably see examples where the code looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var todoViewModel = function() {
    this.items = new ko.observableArray(['Item 1', 'Item 2', 'Item 3']);
    this.selectedItem = new ko.observable('Item 1');
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What I'm trying to point out here is that the &lt;code&gt;viewModel&lt;/code&gt; is being defined in JavaScript and that the items within it are coded into your JavaScript.&lt;/p&gt;

&lt;p&gt;While you can argue that this is demo code and it should only be treated as such something I've noticed is &lt;em&gt;there isn't any other examples&lt;/em&gt;. I haven't seen any example where they are talking about getting the data initially from the server for their viewModel.&lt;/p&gt;

&lt;p&gt;So how do you approach this? In this article I'm going to look at how to create a viewModel from the server using ASP.Net MVC.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: I'm talking about doing a viewModel as part of the initial page load since generally speaking you'll have been doing data layer interaction as part of the request. Building a viewModel using an AJAX request is a different story and I wont be covering.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;From the server to the client&lt;/h2&gt;

&lt;p&gt;Let's get started with an example of our controller:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public class TaskController : Controller
{
    public ActionResult Index()
    {
        var vm = new TaskViewModel
                     {
                         Tasks = new[] { new Task("Write Blog Post"), new Task("Publish Blog Post") }
                     };

        return View(vm);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I'm just going to have a reasonably simple ViewModel that just has a collection of tasks that I want to display as part of my KnockoutJS-built UI but the tasks are to be pulled in from my data layer (obviously this is demo code and it's hard coded so you'll have to use your imagination for that part :P).&lt;/p&gt;

&lt;p&gt;For the view I'm just creating something that is very simple for the task list:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;form data-bind="submit:addTask"&amp;gt;
    Add task: &amp;lt;input type="text" data-bind='value:taskToAdd, valueUpdate: "afterkeydown"' /&amp;gt;
    &amp;lt;button type="submit" data-bind="enable: taskToAdd().length &amp;gt; 0"&amp;gt;Add&amp;lt;/button&amp;gt;
&amp;lt;/form&amp;gt;

&amp;lt;p&amp;gt;Your values:&amp;lt;/p&amp;gt;
&amp;lt;select multiple="multiple" height="5" data-bind="options:tasks"&amp;gt; &amp;lt;/select&amp;gt;

&amp;lt;div&amp;gt;
    &amp;lt;button data-bind="click: removeSelected, enable: hasTasks"&amp;gt;Remove&amp;lt;/button&amp;gt;
    &amp;lt;button data-bind="click: sortTasks, enable: hasTasks"&amp;gt;Sort&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we have a conundrum, how do I as part of my response create a KnockoutJS ViewModel that I can then use in my UI?&lt;/p&gt;

&lt;h2&gt;It's all about the serialization&lt;/h2&gt;

&lt;p&gt;When I was prototyping this for my current project I remembers that &lt;a href="http://twitter.com/#!/shazwazza"&gt;Shannon&lt;/a&gt; has mentioned that he'd done something similar himself and I've shamelessly taken his approach and am using it :P.&lt;/p&gt;

&lt;p&gt;His approach was to use a serializer to create a JSON object from the model (there was some other stuff in the skype message he sent me but I'll confess to having not read that :P). For the serialization you can use the &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx"&gt;JavaScriptSerializer&lt;/a&gt;, the &lt;a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx"&gt;DataContractJsonSerializer&lt;/a&gt; or &lt;a href="http://json.codeplex.com/"&gt;Json.NET&lt;/a&gt;. Personally I prefer Json.NET and it's what I'll be using in this demo.&lt;/p&gt;

&lt;p&gt;So let's make a little HTML helper to do this for us:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;public static class HtmlHelperExtensions
{
    public static IHtmlString KnockoutFrom&amp;lt;T&amp;gt;(this HtmlHelper&amp;lt;T&amp;gt; html, T obj)
    {
        var serializer = new JsonSerializer
                             {
                                 ContractResolver = new CamelCasePropertyNamesContractResolver()
                             };

        return new HtmlString(JObject.FromObject(obj, serializer).ToString());
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All we're doing here is creating an instance of the &lt;code&gt;JsonSerializer&lt;/code&gt; from Json.NET and telling it to use the &lt;code&gt;CamelCasePropertyNamesContractResolver&lt;/code&gt;. This is why I like Json.NET, it allows me to convert my .NET naming conventions into JavaScript conventions without a lot of effort. Lastly we just return the serialized object. Not really anything special happening in here.&lt;/p&gt;

&lt;p&gt;Now in my View I can do this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@Html.KnockoutFrom(Model)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Hmm but this isn't really helpful, we're just getting out JSON blob in our view, I still would have to do a bunch of work to actually make it usable and especially if I am doing this on a lot of pages it's a lot of code that I'd prefer not to do every time. So let's see if we can improve our extension method.&lt;/p&gt;

&lt;h2&gt;Setting up the viewModel&lt;/h2&gt;

&lt;p&gt;So what do we want from our improved version? Well I'd like the observables to be set up for me and I'd like it to avoid global variables.&lt;/p&gt;

&lt;p&gt;To do this what I'm going to do is update my extension method to use the &lt;a href="http://knockoutjs.com/documentation/plugins-mapping.html"&gt;Knockout Mapping plugin&lt;/a&gt;. This plugin is really sweet as it allows me to map a JSON object into a KnockoutJS object and is great when you're working with AJAX data, you can easily pull down some data from the server and then use the plugin to extend it into your ViewModel.&lt;/p&gt;

&lt;p&gt;In this case though I'm going to use it to map the JSON version of our server ViewModel into our KnockoutJS one:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    public static IHtmlString KnockoutFrom&amp;lt;T&amp;gt;(this HtmlHelper&amp;lt;T&amp;gt; html, T obj)
    {
        var serializer = new JsonSerializer
                             {
                                 ContractResolver = new CamelCasePropertyNamesContractResolver()
                             };

        var sb = new StringBuilder();
        sb.Append("(function() {");

        var json = JObject.FromObject(obj, serializer);

        sb.Append("var vm = ko.mapping.fromJS(" + json + ");");

        sb.Append("ko.applyBindings(vm);");

        sb.Append("})();");

        return new HtmlString(sb.ToString());
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The main updates here are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;I'm using a &lt;code&gt;StringBuilder&lt;/code&gt; to build up some JavaScript (normally I hate server-generated JavaScript but here it serves a good purpose)&lt;/li&gt;
&lt;li&gt;I'm creating an &lt;a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/"&gt;immediately-invoked function expression&lt;/a&gt; to prevent leakage&lt;/li&gt;
&lt;li&gt;I'm doing my binding straight away, hiding the need for that too&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Excellent, this works, at least it works to an extent as we still have a few problems:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What if I want to restrict where the binding happens?&lt;/li&gt;
&lt;li&gt;What about adding methods to my KnockoutJS viewModel?&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Improving interactivity&lt;/h2&gt;

&lt;p&gt;While the above will work fine for simple scenarios it's not great if you have a complex UI that you want to work with, and realistically it's not likely you'll have a viewModel you don't want  to extend with dependantObservables or anything, so let's do some refactoring.&lt;/p&gt;

&lt;p&gt;I'm going to change the end of my extension method to look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;        sb.Append("var vm = ko.mapping.fromJS(" + json + ");");

        var type = obj.GetType();

        var ns = JavaScriptify(type.Namespace);
        sb.Append("namespace('" + ns + "');");
        sb.Append(ns + "." + JavaScriptify(type.Name) + " = vm;");

        sb.Append("})();");

        return new HtmlString(sb.ToString());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What I've done here is instead of doing the bindings I'm just going to create a global object which the viewModel will be assigned to (but I am &lt;a href="http://www.aaron-powell.com/slace-core-javascript-library"&gt;namespacing&lt;/a&gt; it so it's a bit better). This object I can then interact with in my JavaScript and add methods/ properties/ etc to myself.&lt;/p&gt;

&lt;p&gt;I'm also using a helper method to make the .NET namespace &amp;amp; type names friendlier for JavaScript:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    private static string JavaScriptify(string s)
    {
        return string.Join(".", s.Split('.').Select(x =&amp;gt; x[0].ToString().ToLower() + x.Substring(1, x.Length - 1)));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With this new extension method I can update my View to play around with the viewModel before binding:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;script&amp;gt;
    @Html.KnockoutFrom(Model)

    $(function() {
        var model = knockout.serverViewModels.models.taskViewModel;

        model.addTask = function() {};
        model.taskToAdd = new ko.observable('');
        model.removeSelected = function() {};
        model.hasTasks = function() {};
        model.sortTasks = function() {};

        ko.applyBindings(model);
    });
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;This wraps up my post on how to convert your server ViewModel into something that can be used in your KnockoutJS, allowing you to push all data down in the initial request rather than subsequent ones.&lt;/p&gt;

&lt;p&gt;Thanks to Shannon for the initial idea, hopefully this little extension will make it even easier.&lt;/p&gt;

&lt;p&gt;If you want to grab the code it is &lt;a href="http://hg.apwll.me/knockoutjs-server-viewmodels"&gt;available here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;One final note, the Json.NET serializer &lt;strong&gt;does&lt;/strong&gt; support the &lt;code&gt;DataMember&lt;/code&gt; attributes, so you can also selectively include properties from your server ViewModel by attributing them too.&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/javascript/creating-vms-from-server" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fcreating-vms-from-server&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/javascript/creating-vms-from-server</feedburner:origLink></item><item><title>So long and thanks for all the fish</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/2q_pIX5zWCw/so-long-and-thanks-for-all-the-fish</link><category>umbraco</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Thu, 15 Sep 2011 07:28:30 PDT</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/umbraco/so-long-and-thanks-for-all-the-fish</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>So it saddens me to say but as of today I will not be contributing to Umbraco, I have been stepped down from my contributor role on the project.</p>

<p>I wish Shannon, Alex, Matt, Niels and the rest of the team the best for the Umbraco 5 release.</p>
<img src="http://www.aaron-powell.com/via-feed/umbraco/so-long-and-thanks-for-all-the-fish" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fumbraco%2fso-long-and-thanks-for-all-the-fish&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=2q_pIX5zWCw:Y458te1Bmxc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=2q_pIX5zWCw:Y458te1Bmxc:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=2q_pIX5zWCw:Y458te1Bmxc:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/2q_pIX5zWCw" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;So it saddens me to say but as of today I will not be contributing to Umbraco, I have been stepped down from my contributor role on the project.&lt;/p&gt;

&lt;p&gt;I wish Shannon, Alex, Matt, Niels and the rest of the team the best for the Umbraco 5 release.&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/umbraco/so-long-and-thanks-for-all-the-fish" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fumbraco%2fso-long-and-thanks-for-all-the-fish&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/umbraco/so-long-and-thanks-for-all-the-fish</feedburner:origLink></item><item><title>Going beyond the browser with QUnit - Part 2</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/N1qmG1JtPwo/qunit-beyond-the-browser-part-2</link><category>javascript</category><category>nodejs</category><category>qunit</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Mon, 05 Sep 2011 18:32:04 PDT</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/javascript/qunit-beyond-the-browser-part-2</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>In my <a href="http://www.aaron-powell.com/javascript/qunit-beyond-the-browser-part-1">last post</a> I talked about what you need to do if you want to monitor changes and run tests automatically under Node.js but there was a few assumptions in there. One of the main assumptions I had was that you weren't doing any DOM interactions.</p>

<p>In this part we're going to look at how you can use DOM interactions in your QUnit tests and still run them under Node.js.</p>

<h2>Working in a DOM-less JavaScript environment</h2>

<p>One thing that can trip people up when they first come to Node.js is they don't realise that JavaScript isn't tied to the browser. In reality JavaScript is just a language that happens to be used predominately in the browser, meaning that the <code>window</code> object isn't part of the JavaScript specification, it's just something that's part of the runtime.</p>

<p>So when you're running your code under Node.js you can't just <code>document.getElementById</code> or <code>$('#foo')</code>. Uh-oh, how are we going to run tests against the DOM, after all if you want to test a library like Knockout.Unobtrusive you kind of need to be able to do that!</p>

<p>Well don't fear, the smart people in the Node.js community have solved this problem with a nice little package, <a href="http://search.npmjs.org/#/jsdom">jsdom</a>!</p>

<p>jsdom is essentially an implementation of the DOM in Node.js allowing you do create a <code>document</code> object, a <code>window</code> object and interact with it as though it was in a browser.</p>

<p><em>Note: There are limitations to <code>jsdom</code>, it doesn't do everything you'd want but it's a great way to do basic interactions such as we want to do in our tests.</em></p>

<h2>Updating out test runner</h2>

<p>In my previous post I showed you how to set up a basic test runner in your Cakefile. For our tests we're going to need to add some new stuff into our runtime (Node.js) and to do that we can use the <code>dep</code> option when we set up the runner:</p>

<pre><code>test = 
  deps: ["./tests/test-env.js"]
  code: "./#{output}/#{file}.js",
  tests: "./tests/#{file}.tests.js"
</code></pre>

<p>What I'm going to do is create a <code>test-env.js</code> file which will be executed before the tests, allowing me to set up our pesudo-DOM.</p>

<h2>Creating our test environment</h2>

<p>I'm going to set up a few new variables:</p>

<pre><code>var jsdom = require('jsdom'),
    fs = require('fs'),
    dom = fs.readFileSync("./tests/knockout.unobtrusive.tests.html").toString(),
    document = jsdom.jsdom(dom, null, { features: { QuerySelector: true } }),
    window = document.createWindow(),
    navigator = {
      userAgent: 'node-js'
    };
</code></pre>

<p>First thing I'm doing here is importing <code>jsdom</code> and <code>fs</code>. This will mean I can work with <code>jsdom</code> and the file system.</p>

<p>The next step is to pull in our test HTML page as a string. We've got some base HTML which we'll be interacting with during our tests. This is also the HTML we'd be running in our browser for our browser-based tests because keep in mind we want to share our tests between Node.js and the browser.</p>

<p>Now that we have our DOM as a string we'll create our <code>document</code> object from it. One other thing we are doing is specifying that we do want <code>querySelector</code> and <code>querySelectorAll</code> available, and this is done with the <code>{ features: { QuerySelector: true } }</code> argument to <code>jsdom</code>.</p>

<p>Lastly we need to create a <code>window</code> object and a <code>navigator</code> object.</p>

<p>So when we have all these local variables we need to make sure that they'll be available everywhere:</p>

<pre><code>global.window = window;
global.navigator = navigator;
global.document = window.document;
</code></pre>

<p>Unlike the browser Node.js's global object is called <code>global</code>, once we add our variables to that they'll be available in any of the other files we use in the runner.</p>

<h2>Augmenting our tests</h2>

<p>In the original set of tests that were in the Knockout.Unobtrusive project there was a heavy reliance on jQuery. Now admittedly there is a <a href="http://search.npmjs.org/#/jquery">jQuery npm package</a> but I couldn't get it running on Node.js 0.4.10 but it's not really important (I'd prefer not to rely on jQuery in my tests anyway).</p>

<p>So I'm going to do a check for jQuery (our Node.js tests wont have it):</p>

<pre><code>var get, getAll, camalizer, data,
  dataMatcher = /data-(.+)/,
  dashAlphaMatcher = /-([a-z])/ig;

if(typeof $ !== 'undefined') {
  getAll = get = $;
} else {
  camalizer = function(x, letter) {
    return letter.toUpperCase();
  };

  data = function(el) {
    var attribute,
        attributes = el.attributes,
        data = {};

    for(var i = 0, il = attributes.length; i &lt; il; i++) {
      attribute = attributes[i];
      if(dataMatcher.test(attribute.name)) {
        data[attribute.name.match(dataMatcher)[1].replace(dashAlphaMatcher, camalizer)] = attribute.value;
      }
    }

    return function(attr) {
      return data[attr];
    };
  };

  get = function(id) {
    if(id.indexOf('#') === 0) {
      id = id.substring(1, id.length);
    }

    var el = document.getElementById(id);

    if(!el) {
      el = document.querySelectorAll(id)[0];
    }

    el.data = data(el);
    return el;
  };

  getAll = function(selector) {
    var el,
        elements = document.querySelectorAll(selector);

    if(elements[0] &amp;&amp; !elements[0].dataset) {
      for(var i=0, il=elements.length; i &lt; il; i++) {
        el = elements[i];
        el.data = data(el);
      }
    }

    elements.each = function(fn) {
      var that = this;
      that.forEach(function(value, index) {
        fn.apply(that, [index, value]);
      });
    };

    return elements;
  };
</code></pre>

<p>Ok so the obvious first step is to check for jQuery and then we're deferring everything to that, but instead of just exposing <code>$</code> I'm going to expose two methods, <code>get</code> and <code>getAll</code>. The former will be useful for getting a single element, the latter for multiple elements.</p>

<p>Next I'm creating two helper methods, the first being a camel case method (handy for working with <code>data-*</code> and the second simulating the <code>.data</code> API which you get from jQuery itself.</p>

<p><em>Note: The data method isn't exactly the same as using the $.data API, but I'm only replicating what I need at the current time.</em></p>

<p>In our simulated data API it will iterate through all the attributes and find any <code>data-*</code> ones (using a regex to look for them) then turning them into camel cased strings (like the spec, so <code>data-foo-bar</code> becomes <code>fooBar</code>). It's probably a bit more complicated than it needs to be but it works nicely as I want.</p>

<p>The only other interesting point of note is that the <code>getAll</code> method will also simulate the <code>.each</code> API from jQuery so that we can use those loops in our tests.</p>

<p>And there you go you're essentially done. Once you replace all your usages of jQuery in your tests for the <code>get</code> and <code>getAll</code> API then you'll be ready to roll!</p>

<h2>Be careful with DOM manipulations</h2>

<p>Something that I got tripped up with when porting the Knockout.Unobtrusive tests was that you don't want your DOM manipulations to persist across the tests.</p>

<p>If you've done work with QUnit you'll know that if you a DOM element with an <code>id</code> of <code>qunit-fixture</code> then it'll get rebuilt after every single test.</p>

<p>Well there's a problem, the Node.js implementation of QUnit isn't designed to work with the DOM so naturally this doesn't work. But it's an easy one to get around, QUnit exposes a method called <code>reset</code> that you can use to force a reset of the <code>qunit-fixture</code> element. Since the Node.js one doesn't worry about the DOM it doesn't have this method.</p>

<p>To implement this ourselves we'll create a <code>module</code> for our test that we can have a <code>teardown</code> method on the end of it:</p>

<pre><code>QUnit.module('createBindings', {
  teardown: function() {
    if(!QUnit.reset) {
      //do the reset
    }
  }
});
</code></pre>

<p><em>Note: you need to either access <code>module</code> via <code>QUnit.module</code> or assign that to <code>module</code> yourself because <code>module</code> is a reserved word in Node.js.</em></p>

<p>For the reset method I've created a helper function back in the <code>test-env.js</code> file:</p>

<pre><code>global.rebuildDom = function() {
  global.document = jsdom.jsdom(dom, null, { features: { QuerySelector: true } });
  global.window = global.document.createWindow();
};
</code></pre>

<p>This will rebuild both the <code>document</code> and <code>window</code> objects from the original DOM string. So we can update our module like so:</p>

<pre><code>QUnit.module('createBindings', {
  teardown: function() {
    if(!QUnit.reset) {
      rebuildDom();
    }
  }
});
</code></pre>

<h2>Conclusion</h2>

<p>I'm aware that this has been a bit of a long and complicated post but hopefully it gives you some starting points for how you could approach doing online &amp; offline JavaScript tests.</p>
<img src="http://www.aaron-powell.com/via-feed/javascript/qunit-beyond-the-browser-part-2" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fqunit-beyond-the-browser-part-2&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=N1qmG1JtPwo:jGM4CTB5NiI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=N1qmG1JtPwo:jGM4CTB5NiI:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=N1qmG1JtPwo:jGM4CTB5NiI:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/N1qmG1JtPwo" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;In my &lt;a href="http://www.aaron-powell.com/javascript/qunit-beyond-the-browser-part-1"&gt;last post&lt;/a&gt; I talked about what you need to do if you want to monitor changes and run tests automatically under Node.js but there was a few assumptions in there. One of the main assumptions I had was that you weren't doing any DOM interactions.&lt;/p&gt;

&lt;p&gt;In this part we're going to look at how you can use DOM interactions in your QUnit tests and still run them under Node.js.&lt;/p&gt;

&lt;h2&gt;Working in a DOM-less JavaScript environment&lt;/h2&gt;

&lt;p&gt;One thing that can trip people up when they first come to Node.js is they don't realise that JavaScript isn't tied to the browser. In reality JavaScript is just a language that happens to be used predominately in the browser, meaning that the &lt;code&gt;window&lt;/code&gt; object isn't part of the JavaScript specification, it's just something that's part of the runtime.&lt;/p&gt;

&lt;p&gt;So when you're running your code under Node.js you can't just &lt;code&gt;document.getElementById&lt;/code&gt; or &lt;code&gt;$('#foo')&lt;/code&gt;. Uh-oh, how are we going to run tests against the DOM, after all if you want to test a library like Knockout.Unobtrusive you kind of need to be able to do that!&lt;/p&gt;

&lt;p&gt;Well don't fear, the smart people in the Node.js community have solved this problem with a nice little package, &lt;a href="http://search.npmjs.org/#/jsdom"&gt;jsdom&lt;/a&gt;!&lt;/p&gt;

&lt;p&gt;jsdom is essentially an implementation of the DOM in Node.js allowing you do create a &lt;code&gt;document&lt;/code&gt; object, a &lt;code&gt;window&lt;/code&gt; object and interact with it as though it was in a browser.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: There are limitations to &lt;code&gt;jsdom&lt;/code&gt;, it doesn't do everything you'd want but it's a great way to do basic interactions such as we want to do in our tests.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;Updating out test runner&lt;/h2&gt;

&lt;p&gt;In my previous post I showed you how to set up a basic test runner in your Cakefile. For our tests we're going to need to add some new stuff into our runtime (Node.js) and to do that we can use the &lt;code&gt;dep&lt;/code&gt; option when we set up the runner:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;test = 
  deps: ["./tests/test-env.js"]
  code: "./#{output}/#{file}.js",
  tests: "./tests/#{file}.tests.js"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What I'm going to do is create a &lt;code&gt;test-env.js&lt;/code&gt; file which will be executed before the tests, allowing me to set up our pesudo-DOM.&lt;/p&gt;

&lt;h2&gt;Creating our test environment&lt;/h2&gt;

&lt;p&gt;I'm going to set up a few new variables:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var jsdom = require('jsdom'),
    fs = require('fs'),
    dom = fs.readFileSync("./tests/knockout.unobtrusive.tests.html").toString(),
    document = jsdom.jsdom(dom, null, { features: { QuerySelector: true } }),
    window = document.createWindow(),
    navigator = {
      userAgent: 'node-js'
    };
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;First thing I'm doing here is importing &lt;code&gt;jsdom&lt;/code&gt; and &lt;code&gt;fs&lt;/code&gt;. This will mean I can work with &lt;code&gt;jsdom&lt;/code&gt; and the file system.&lt;/p&gt;

&lt;p&gt;The next step is to pull in our test HTML page as a string. We've got some base HTML which we'll be interacting with during our tests. This is also the HTML we'd be running in our browser for our browser-based tests because keep in mind we want to share our tests between Node.js and the browser.&lt;/p&gt;

&lt;p&gt;Now that we have our DOM as a string we'll create our &lt;code&gt;document&lt;/code&gt; object from it. One other thing we are doing is specifying that we do want &lt;code&gt;querySelector&lt;/code&gt; and &lt;code&gt;querySelectorAll&lt;/code&gt; available, and this is done with the &lt;code&gt;{ features: { QuerySelector: true } }&lt;/code&gt; argument to &lt;code&gt;jsdom&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Lastly we need to create a &lt;code&gt;window&lt;/code&gt; object and a &lt;code&gt;navigator&lt;/code&gt; object.&lt;/p&gt;

&lt;p&gt;So when we have all these local variables we need to make sure that they'll be available everywhere:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;global.window = window;
global.navigator = navigator;
global.document = window.document;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Unlike the browser Node.js's global object is called &lt;code&gt;global&lt;/code&gt;, once we add our variables to that they'll be available in any of the other files we use in the runner.&lt;/p&gt;

&lt;h2&gt;Augmenting our tests&lt;/h2&gt;

&lt;p&gt;In the original set of tests that were in the Knockout.Unobtrusive project there was a heavy reliance on jQuery. Now admittedly there is a &lt;a href="http://search.npmjs.org/#/jquery"&gt;jQuery npm package&lt;/a&gt; but I couldn't get it running on Node.js 0.4.10 but it's not really important (I'd prefer not to rely on jQuery in my tests anyway).&lt;/p&gt;

&lt;p&gt;So I'm going to do a check for jQuery (our Node.js tests wont have it):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var get, getAll, camalizer, data,
  dataMatcher = /data-(.+)/,
  dashAlphaMatcher = /-([a-z])/ig;

if(typeof $ !== 'undefined') {
  getAll = get = $;
} else {
  camalizer = function(x, letter) {
    return letter.toUpperCase();
  };

  data = function(el) {
    var attribute,
        attributes = el.attributes,
        data = {};

    for(var i = 0, il = attributes.length; i &amp;lt; il; i++) {
      attribute = attributes[i];
      if(dataMatcher.test(attribute.name)) {
        data[attribute.name.match(dataMatcher)[1].replace(dashAlphaMatcher, camalizer)] = attribute.value;
      }
    }

    return function(attr) {
      return data[attr];
    };
  };

  get = function(id) {
    if(id.indexOf('#') === 0) {
      id = id.substring(1, id.length);
    }

    var el = document.getElementById(id);

    if(!el) {
      el = document.querySelectorAll(id)[0];
    }

    el.data = data(el);
    return el;
  };

  getAll = function(selector) {
    var el,
        elements = document.querySelectorAll(selector);

    if(elements[0] &amp;amp;&amp;amp; !elements[0].dataset) {
      for(var i=0, il=elements.length; i &amp;lt; il; i++) {
        el = elements[i];
        el.data = data(el);
      }
    }

    elements.each = function(fn) {
      var that = this;
      that.forEach(function(value, index) {
        fn.apply(that, [index, value]);
      });
    };

    return elements;
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Ok so the obvious first step is to check for jQuery and then we're deferring everything to that, but instead of just exposing &lt;code&gt;$&lt;/code&gt; I'm going to expose two methods, &lt;code&gt;get&lt;/code&gt; and &lt;code&gt;getAll&lt;/code&gt;. The former will be useful for getting a single element, the latter for multiple elements.&lt;/p&gt;

&lt;p&gt;Next I'm creating two helper methods, the first being a camel case method (handy for working with &lt;code&gt;data-*&lt;/code&gt; and the second simulating the &lt;code&gt;.data&lt;/code&gt; API which you get from jQuery itself.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: The data method isn't exactly the same as using the $.data API, but I'm only replicating what I need at the current time.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In our simulated data API it will iterate through all the attributes and find any &lt;code&gt;data-*&lt;/code&gt; ones (using a regex to look for them) then turning them into camel cased strings (like the spec, so &lt;code&gt;data-foo-bar&lt;/code&gt; becomes &lt;code&gt;fooBar&lt;/code&gt;). It's probably a bit more complicated than it needs to be but it works nicely as I want.&lt;/p&gt;

&lt;p&gt;The only other interesting point of note is that the &lt;code&gt;getAll&lt;/code&gt; method will also simulate the &lt;code&gt;.each&lt;/code&gt; API from jQuery so that we can use those loops in our tests.&lt;/p&gt;

&lt;p&gt;And there you go you're essentially done. Once you replace all your usages of jQuery in your tests for the &lt;code&gt;get&lt;/code&gt; and &lt;code&gt;getAll&lt;/code&gt; API then you'll be ready to roll!&lt;/p&gt;

&lt;h2&gt;Be careful with DOM manipulations&lt;/h2&gt;

&lt;p&gt;Something that I got tripped up with when porting the Knockout.Unobtrusive tests was that you don't want your DOM manipulations to persist across the tests.&lt;/p&gt;

&lt;p&gt;If you've done work with QUnit you'll know that if you a DOM element with an &lt;code&gt;id&lt;/code&gt; of &lt;code&gt;qunit-fixture&lt;/code&gt; then it'll get rebuilt after every single test.&lt;/p&gt;

&lt;p&gt;Well there's a problem, the Node.js implementation of QUnit isn't designed to work with the DOM so naturally this doesn't work. But it's an easy one to get around, QUnit exposes a method called &lt;code&gt;reset&lt;/code&gt; that you can use to force a reset of the &lt;code&gt;qunit-fixture&lt;/code&gt; element. Since the Node.js one doesn't worry about the DOM it doesn't have this method.&lt;/p&gt;

&lt;p&gt;To implement this ourselves we'll create a &lt;code&gt;module&lt;/code&gt; for our test that we can have a &lt;code&gt;teardown&lt;/code&gt; method on the end of it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;QUnit.module('createBindings', {
  teardown: function() {
    if(!QUnit.reset) {
      //do the reset
    }
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Note: you need to either access &lt;code&gt;module&lt;/code&gt; via &lt;code&gt;QUnit.module&lt;/code&gt; or assign that to &lt;code&gt;module&lt;/code&gt; yourself because &lt;code&gt;module&lt;/code&gt; is a reserved word in Node.js.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;For the reset method I've created a helper function back in the &lt;code&gt;test-env.js&lt;/code&gt; file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;global.rebuildDom = function() {
  global.document = jsdom.jsdom(dom, null, { features: { QuerySelector: true } });
  global.window = global.document.createWindow();
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will rebuild both the &lt;code&gt;document&lt;/code&gt; and &lt;code&gt;window&lt;/code&gt; objects from the original DOM string. So we can update our module like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;QUnit.module('createBindings', {
  teardown: function() {
    if(!QUnit.reset) {
      rebuildDom();
    }
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;I'm aware that this has been a bit of a long and complicated post but hopefully it gives you some starting points for how you could approach doing online &amp;amp; offline JavaScript tests.&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/javascript/qunit-beyond-the-browser-part-2" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fqunit-beyond-the-browser-part-2&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/javascript/qunit-beyond-the-browser-part-2</feedburner:origLink></item><item><title>Slides from WEB203</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/s6QBRjgnDHw/slides</link><category>auteched</category><category>speaking</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Wed, 21 Dec 2011 15:49:15 PST</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/speaking/teched-au-2011/slides</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>I recently spoke at Teched AU in a session called Chasing the Evolving Web.</p>

<p>Here's the assets from the talk:</p>

<ul>
<li><a href="http://www.aaron-powell.com/get/presentations/auteched/WEB203_Powell.pptx">Slides</a></li>
<li><a href="http://channel9.msdn.com/Events/TechEd/Australia/Tech-Ed-Australia-2011/web203">Recording</a></li>
</ul>

<p>And here's a list of the tools which I looked at in my presentation:</p>

<ul>
<li><a href="http://h5bp.com">HTML5 Boilerplate</a></li>
<li><a href="http://modernizr.com">Modernizr</a></li>
<li><a href="http://yepnopejs.com">YepNope.js</a></li>
<li><a href="http://raphaeljs.com">RaphaelJS</a></li>
<li><a href="http://amplifyjs.com">AmplifyJS</a></li>
<li><a href="http://knockoutjs.com">Knockout</a></li>
</ul>
<img src="http://www.aaron-powell.com/via-feed/speaking/teched-au-2011/slides" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fspeaking%2fteched-au-2011%2fslides&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=s6QBRjgnDHw:GoWvSnDShDU:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=s6QBRjgnDHw:GoWvSnDShDU:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=s6QBRjgnDHw:GoWvSnDShDU:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/s6QBRjgnDHw" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;I recently spoke at Teched AU in a session called Chasing the Evolving Web.&lt;/p&gt;

&lt;p&gt;Here's the assets from the talk:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.aaron-powell.com/get/presentations/auteched/WEB203_Powell.pptx"&gt;Slides&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://channel9.msdn.com/Events/TechEd/Australia/Tech-Ed-Australia-2011/web203"&gt;Recording&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And here's a list of the tools which I looked at in my presentation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://h5bp.com"&gt;HTML5 Boilerplate&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://modernizr.com"&gt;Modernizr&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://yepnopejs.com"&gt;YepNope.js&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://raphaeljs.com"&gt;RaphaelJS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://amplifyjs.com"&gt;AmplifyJS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://knockoutjs.com"&gt;Knockout&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/speaking/teched-au-2011/slides" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fspeaking%2fteched-au-2011%2fslides&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/speaking/teched-au-2011/slides</feedburner:origLink></item><item><title>Going beyond the browser with QUnit - Part 1</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/x_5fs9t6XIc/qunit-beyond-the-browser-part-1</link><category>javascript</category><category>nodejs</category><category>qunit</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Sat, 03 Sep 2011 21:21:24 PDT</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/javascript/qunit-beyond-the-browser-part-1</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>When it comes to unit testing my JavaScript my preferred framework is <a href="http://docs.jquery.com/Qunit">QUnit</a>. If you're not familiar with QUnit it's the test framework for <a href="http://jquery.com">jQuery</a> so I think it's reasonably well up to the task of testing JavaScript.</p>

<p>Recently I wrote an article on a <a href="http://www.aaron-powell.com/javascript/knockoutjs-preparser">preparser I've written for Knockout</a>. Interestingly enough at the same time Brendan Satrom had <a href="http://bsatrom.github.com/Knockout.Unobtrusive/">the same idea</a>. I quite like the approach that Brendan has taken so I decided to have a poke around in the code and see if we could even merge the two projects.</p>

<p>The first thing I noticed when looking into the code was that it was written using <a href="http://jashkenas.github.com/coffee-script/">CoffeeScript</a>. The second thing I noticed was that the tests were all written using QUnit and were to be run in the browser. But there was a bit of a nuisance, the tests were against the compiles JavaScript, not the raw CoffeeScript (it was running against the generated file), to do any modifications, and test them, you have to copy the CoffeeScript to the online compiler, the back to the compiled file and then run the tests.</p>

<p>I'm sure you can see where the problems can come into this solution.</p>

<p>Well I've done a few small projects using CoffeeScript in the past and I've also included some tests into it so I decided at having a crack at getting this to work.</p>

<h2>Getting your tools together</h2>

<p>So to get started I'm using Windows and I'm going to be using Node.js to do the browser-less coding. Although I'm aware there is a version of Node.js for Windows I'm still using a self-compiled version with cygwin because <a href="http://npmjs.org">npm</a> works fine under cygwin but not with the Windows compiled version.</p>

<p>Additionally I'm going to be using a few npm packages:</p>

<ul>
<li><a href="http://search.npmjs.org/#/coffee-script">CoffeeScript</a></li>
<li><a href="http://search.npmjs.org/#/qunit">QUnit</a></li>
<li><a href="http://search.npmjs.org/#/colors">Colors</a></li>
</ul>

<h2>Getting started by watching cake</h2>

<p>If you've done much work with CoffeeScript you'll probably have come across the concept of a <a href="http://jashkenas.github.com/coffee-script/#cake">Cakefile</a>, if you haven't, a Cakefile is a CoffeeScript version of a <a href="http://rake.rubyforge.org/files/doc/rakefile_rdoc.html">Rakefile</a> (or MSBuild is a similar concept if you're coming from .NET just a lot more horrible), so I'm going to start off by using Cake to create a file system watcher.</p>

<p>The basic idea if I want to have a Cake task which will monitor for changes on the file system (specifically our CoffeeScript file) and when a change happens we'll compile it to JavaScript and run our tests.</p>

<p>First off I'll define some constants in our Cakefile:</p>

<pre><code>fs = require 'fs'
path = require 'path'
CoffeeScript = require 'coffee-script'
file = 'knockout.unobtrusive'
source = 'coffee'
output = 'js'
</code></pre>

<p>Next it's time to setup our <code>watch</code> task:</p>

<pre><code>task 'watch', 'Watch prod source files and build changes', -&gt;
    msg = "Watching for changes in #{source}"
    console.log msg

    fs.watchFile "#{source}/#{file}.coffee", (curr, prev) -&gt;
        if +curr.mtime isnt +prev.mtime
            console.log "Saw change in #{source}/#{file}.coffee"
            try
              invoke 'build'
              console.log 'build complete'
              invoke 'tests'
            catch e
              msg = 'Error with CoffeeScript build'
              console.log msg
              console.log e
</code></pre>

<p>We're using the standard <code>watchFile</code> method in Node and in the callback we'll ensure that the change times aren't equal (double-checking for false positives) and if there's a valid change we want to execute the following two tasks:</p>

<ul>
<li><code>build</code></li>
<li><code>tests</code></li>
</ul>

<p>Additionally we're wrapping this in a <code>try/ catch</code> so that if it fails we can provide a useful message but have the watcher keep running (say if you save while you're half-way through a change you wont get a major failure or anything).</p>

<p>Now let's have a look at the <code>build</code> task. This task will allow us to compile our coffee file into JavaScript. This is just going to be a standard Cake task as well so you can use it elsewhere if you want:</p>

<pre><code>task 'build', "builds #{file}", -&gt;
    console.log "building #{file} from coffeescript"
    code = fs.readFileSync "#{source}/#{file}.coffee", 'utf8'
    fs.writeFile "#{output}/#{file}.js", CoffeeScript.compile code
</code></pre>

<p>Since Node (well JavaScript) is a callback-based programming model generally speaking you'll be doing asynchronous operations, even with the file system. Node has provided some changes though to allow for <em>synchronous</em> programming. In this case I'm going to be using the synchronous read operation. The main reason for this is so that I don't have to pass around a callback which will then do the tests (this could get messy in the Cakefile).</p>

<p>Once the read operation is completed we pipe the output into the CofeeScript compiler API (which we can call from CoffeeScript/ JavaScript) and write the output of that into a JavaScript file.</p>

<p>When the <code>build</code> task is done the next step in our watcher is to call out to our test runner. As mentioned above I wanted to reuse the QUnit tests that already shipped in source of Knockout.Unobtrusive I plan to use the Node.js implementation of QUnit. It's rather simple and again we'll create a Cake task:</p>

<pre><code>task 'tests', "run tests for #{file}", -&gt;
    console.log 'Time for some tests! '
    runner = require 'qunit'
    sys = require 'sys'
    colors = require 'colors'
    test = 
      code: "./#{output}/#{file}.js",
      tests: "./tests/#{file}.tests.js"

    runner.options.summary = false

    report = (r) -&gt;
      if r.errors
        msg = "Uh oh, there were errors"
        sys.puts msg.bold.red
      else
        msg = 'All test pass'
        sys.puts msg.green

    runner.run test, report
</code></pre>

<p>So a few things of note:</p>

<ul>
<li>We're using the runner which comes with QUnit for Node.js</li>
<li>We're creating an object with our tests info which includes:
<ul>
<li>The file under test</li>
<li>The tests to execute</li>
</ul></li>
<li>I'm suppressing the summary (we execute the tests a lot so there's no need to see it)</li>
<li>Lastly there's a callback for when the runner finishes which will either dump a message on success or failure (with a pretty colour!)</li>
</ul>

<p>From the point of view of the Cakefile that's really all we have a need for, we've got our watcher up and running and we can just kick it off:</p>

<pre><code>cake watch
</code></pre>

<p>Now whenever we edit our CoffeeScript file it'll go nicely.</p>

<h2>Wrapping up</h2>

<p>So this wraps up the first part of migrating our tests out of the browser to make a more automated series of JavaScript tests.</p>

<p>Next time we'll look at how to deal with some of the limitations of working in a DOM-less environment.</p>
<img src="http://www.aaron-powell.com/via-feed/javascript/qunit-beyond-the-browser-part-1" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fqunit-beyond-the-browser-part-1&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=x_5fs9t6XIc:ALREBhUkEbw:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=x_5fs9t6XIc:ALREBhUkEbw:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=x_5fs9t6XIc:ALREBhUkEbw:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/x_5fs9t6XIc" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;When it comes to unit testing my JavaScript my preferred framework is &lt;a href="http://docs.jquery.com/Qunit"&gt;QUnit&lt;/a&gt;. If you're not familiar with QUnit it's the test framework for &lt;a href="http://jquery.com"&gt;jQuery&lt;/a&gt; so I think it's reasonably well up to the task of testing JavaScript.&lt;/p&gt;

&lt;p&gt;Recently I wrote an article on a &lt;a href="http://www.aaron-powell.com/javascript/knockoutjs-preparser"&gt;preparser I've written for Knockout&lt;/a&gt;. Interestingly enough at the same time Brendan Satrom had &lt;a href="http://bsatrom.github.com/Knockout.Unobtrusive/"&gt;the same idea&lt;/a&gt;. I quite like the approach that Brendan has taken so I decided to have a poke around in the code and see if we could even merge the two projects.&lt;/p&gt;

&lt;p&gt;The first thing I noticed when looking into the code was that it was written using &lt;a href="http://jashkenas.github.com/coffee-script/"&gt;CoffeeScript&lt;/a&gt;. The second thing I noticed was that the tests were all written using QUnit and were to be run in the browser. But there was a bit of a nuisance, the tests were against the compiles JavaScript, not the raw CoffeeScript (it was running against the generated file), to do any modifications, and test them, you have to copy the CoffeeScript to the online compiler, the back to the compiled file and then run the tests.&lt;/p&gt;

&lt;p&gt;I'm sure you can see where the problems can come into this solution.&lt;/p&gt;

&lt;p&gt;Well I've done a few small projects using CoffeeScript in the past and I've also included some tests into it so I decided at having a crack at getting this to work.&lt;/p&gt;

&lt;h2&gt;Getting your tools together&lt;/h2&gt;

&lt;p&gt;So to get started I'm using Windows and I'm going to be using Node.js to do the browser-less coding. Although I'm aware there is a version of Node.js for Windows I'm still using a self-compiled version with cygwin because &lt;a href="http://npmjs.org"&gt;npm&lt;/a&gt; works fine under cygwin but not with the Windows compiled version.&lt;/p&gt;

&lt;p&gt;Additionally I'm going to be using a few npm packages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://search.npmjs.org/#/coffee-script"&gt;CoffeeScript&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://search.npmjs.org/#/qunit"&gt;QUnit&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://search.npmjs.org/#/colors"&gt;Colors&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Getting started by watching cake&lt;/h2&gt;

&lt;p&gt;If you've done much work with CoffeeScript you'll probably have come across the concept of a &lt;a href="http://jashkenas.github.com/coffee-script/#cake"&gt;Cakefile&lt;/a&gt;, if you haven't, a Cakefile is a CoffeeScript version of a &lt;a href="http://rake.rubyforge.org/files/doc/rakefile_rdoc.html"&gt;Rakefile&lt;/a&gt; (or MSBuild is a similar concept if you're coming from .NET just a lot more horrible), so I'm going to start off by using Cake to create a file system watcher.&lt;/p&gt;

&lt;p&gt;The basic idea if I want to have a Cake task which will monitor for changes on the file system (specifically our CoffeeScript file) and when a change happens we'll compile it to JavaScript and run our tests.&lt;/p&gt;

&lt;p&gt;First off I'll define some constants in our Cakefile:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fs = require 'fs'
path = require 'path'
CoffeeScript = require 'coffee-script'
file = 'knockout.unobtrusive'
source = 'coffee'
output = 'js'
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Next it's time to setup our &lt;code&gt;watch&lt;/code&gt; task:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;task 'watch', 'Watch prod source files and build changes', -&amp;gt;
    msg = "Watching for changes in #{source}"
    console.log msg

    fs.watchFile "#{source}/#{file}.coffee", (curr, prev) -&amp;gt;
        if +curr.mtime isnt +prev.mtime
            console.log "Saw change in #{source}/#{file}.coffee"
            try
              invoke 'build'
              console.log 'build complete'
              invoke 'tests'
            catch e
              msg = 'Error with CoffeeScript build'
              console.log msg
              console.log e
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We're using the standard &lt;code&gt;watchFile&lt;/code&gt; method in Node and in the callback we'll ensure that the change times aren't equal (double-checking for false positives) and if there's a valid change we want to execute the following two tasks:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;build&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;tests&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Additionally we're wrapping this in a &lt;code&gt;try/ catch&lt;/code&gt; so that if it fails we can provide a useful message but have the watcher keep running (say if you save while you're half-way through a change you wont get a major failure or anything).&lt;/p&gt;

&lt;p&gt;Now let's have a look at the &lt;code&gt;build&lt;/code&gt; task. This task will allow us to compile our coffee file into JavaScript. This is just going to be a standard Cake task as well so you can use it elsewhere if you want:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;task 'build', "builds #{file}", -&amp;gt;
    console.log "building #{file} from coffeescript"
    code = fs.readFileSync "#{source}/#{file}.coffee", 'utf8'
    fs.writeFile "#{output}/#{file}.js", CoffeeScript.compile code
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Since Node (well JavaScript) is a callback-based programming model generally speaking you'll be doing asynchronous operations, even with the file system. Node has provided some changes though to allow for &lt;em&gt;synchronous&lt;/em&gt; programming. In this case I'm going to be using the synchronous read operation. The main reason for this is so that I don't have to pass around a callback which will then do the tests (this could get messy in the Cakefile).&lt;/p&gt;

&lt;p&gt;Once the read operation is completed we pipe the output into the CofeeScript compiler API (which we can call from CoffeeScript/ JavaScript) and write the output of that into a JavaScript file.&lt;/p&gt;

&lt;p&gt;When the &lt;code&gt;build&lt;/code&gt; task is done the next step in our watcher is to call out to our test runner. As mentioned above I wanted to reuse the QUnit tests that already shipped in source of Knockout.Unobtrusive I plan to use the Node.js implementation of QUnit. It's rather simple and again we'll create a Cake task:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;task 'tests', "run tests for #{file}", -&amp;gt;
    console.log 'Time for some tests! '
    runner = require 'qunit'
    sys = require 'sys'
    colors = require 'colors'
    test = 
      code: "./#{output}/#{file}.js",
      tests: "./tests/#{file}.tests.js"

    runner.options.summary = false

    report = (r) -&amp;gt;
      if r.errors
        msg = "Uh oh, there were errors"
        sys.puts msg.bold.red
      else
        msg = 'All test pass'
        sys.puts msg.green

    runner.run test, report
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So a few things of note:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We're using the runner which comes with QUnit for Node.js&lt;/li&gt;
&lt;li&gt;We're creating an object with our tests info which includes:
&lt;ul&gt;
&lt;li&gt;The file under test&lt;/li&gt;
&lt;li&gt;The tests to execute&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;I'm suppressing the summary (we execute the tests a lot so there's no need to see it)&lt;/li&gt;
&lt;li&gt;Lastly there's a callback for when the runner finishes which will either dump a message on success or failure (with a pretty colour!)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;From the point of view of the Cakefile that's really all we have a need for, we've got our watcher up and running and we can just kick it off:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cake watch
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now whenever we edit our CoffeeScript file it'll go nicely.&lt;/p&gt;

&lt;h2&gt;Wrapping up&lt;/h2&gt;

&lt;p&gt;So this wraps up the first part of migrating our tests out of the browser to make a more automated series of JavaScript tests.&lt;/p&gt;

&lt;p&gt;Next time we'll look at how to deal with some of the limitations of working in a DOM-less environment.&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/javascript/qunit-beyond-the-browser-part-1" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fqunit-beyond-the-browser-part-1&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/javascript/qunit-beyond-the-browser-part-1</feedburner:origLink></item><item><title>Slides from WUX202</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/TAnG5xrNjhQ/slides</link><category>tenz</category><category>speaking</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Sat, 03 Sep 2011 16:58:50 PDT</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/speaking/teched-nz-2011/slides</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>I recently spoke at Teched NZ in a session called Chasing the Evolving Web.</p>

<p>Here's the slides from the talk:</p>

<ul>
<li><a href="http://www.aaron-powell.com/get/presentations/tenz11/Chasing-the-evolving-web.pptx">Slides</a></li>
</ul>

<p>And here's a list of the tools which I looked at in my presentation:</p>

<ul>
<li><a href="http://h5bp.com">HTML5 Boilerplate</a></li>
<li><a href="http://modernizr.com">Modernizr</a></li>
<li><a href="http://yepnopejs.com">YepNope.js</a></li>
<li><a href="http://raphaeljs.com">RaphaelJS</a></li>
<li><a href="http://easeljs.com">EaselJS</a></li>
<li><a href="http://amplifyjs.com">AmplifyJS</a></li>
<li><a href="http://knockoutjs.com">Knockout</a></li>
<li><a href="http://backbonejs.com">Backbone</a></li>
</ul>
<img src="http://www.aaron-powell.com/via-feed/speaking/teched-nz-2011/slides" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fspeaking%2fteched-nz-2011%2fslides&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=TAnG5xrNjhQ:4egScZOWuHY:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=TAnG5xrNjhQ:4egScZOWuHY:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=TAnG5xrNjhQ:4egScZOWuHY:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/TAnG5xrNjhQ" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;I recently spoke at Teched NZ in a session called Chasing the Evolving Web.&lt;/p&gt;

&lt;p&gt;Here's the slides from the talk:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.aaron-powell.com/get/presentations/tenz11/Chasing-the-evolving-web.pptx"&gt;Slides&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And here's a list of the tools which I looked at in my presentation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="http://h5bp.com"&gt;HTML5 Boilerplate&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://modernizr.com"&gt;Modernizr&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://yepnopejs.com"&gt;YepNope.js&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://raphaeljs.com"&gt;RaphaelJS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://easeljs.com"&gt;EaselJS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://amplifyjs.com"&gt;AmplifyJS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://knockoutjs.com"&gt;Knockout&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://backbonejs.com"&gt;Backbone&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/speaking/teched-nz-2011/slides" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fspeaking%2fteched-nz-2011%2fslides&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/speaking/teched-nz-2011/slides</feedburner:origLink></item><item><title>Introducing the KnockoutJS preparser</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/L6Fm_RPO5C4/knockoutjs-preparser</link><category>javascript</category><category>knockoutjs</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Mon, 08 Aug 2011 21:39:13 PDT</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/javascript/knockoutjs-preparser</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>In my <a href="http://www.aaron-powell.com/javascript/why-i-don-t-like-knockoutjs">previous post</a> I outlined one of the biggest issues I have with <a href="http://knockoutjs.com">KnockoutJS</a> as being its WPF/ Silverlight binding syntax and how it requires you to put JavaScript into your HTML.</p>

<p>Now I'm a pretty firm believe that if you are going to criticise something then you better make it constructive. Just saying "I don't like <code>blah</code>" isn't helpful to a) the author of <code>blah</code> or b) people wanting to learn more about <code>blah</code>, so I decided that I would follow up my criticism of KnockoutJS with a way <em>I</em> would go about fixing it.</p>

<h2>Introducing the KnockoutJS preparser</h2>

<p>To address my issue with KnockoutJS use of JavaScript in HTML I started looking at how I would go about it and the solution I kept coming back to was using the <code>data-*</code> attributes to describe in my HTML an intention. I decided that if I could do this in a good, convention approach then I should be able to translate it back into a KnockoutJS binding with minimal impact.</p>

<p>Out of this idea (and a challenge from my colleague <a href="http://duc.as">Ducas</a>) I set about taking my idea from my brain and putting in code.</p>

<p>Essentially what I came up with was taking this:</p>

<pre><code>&lt;span data-ko-text="firstName"&gt;&lt;/span&gt;
</code></pre>

<p>And turning it into this:</p>

<pre><code>&lt;span data-bind="text: firstName"&gt;&lt;/span&gt;
</code></pre>

<p>The idea is that you take <code>data-ko-*</code> as a prefix and use that to describe what could (well will...) become your binding syntax. Once getting this done I threw the code up on github and you can grab it from the <a href="https://github.com/aaronpowell/KnockoutJS-Pre-parser">KnockoutJS Pre-Parser</a> project page.</p>

<h2>What does it address</h2>

<p>The ultimate goal is to be able to use the <code>data-ko-*</code> to describe out what you want in your HTML and the pre-parser will pick that up and <em>Knockout-ify</em> it for you. Ideally I'd like to support all <strong>common</strong> scenarios and so far I support:</p>

<ul>
<li>Basic bindings with text, css, value, etc</li>
<li>Template name binding</li>
<li>Pre-parser syntax within a template</li>
<li>Template options (but not completely, you still have to embed JSON in your template options attribute. I added it about 3 hours ago so it's still being worked on :P)</li>
<li>Event handler wire ups (if you want a complex handler like defining scope, etc you'll still have to embed JavaScript for now, I'm trying to work out how to get around that)</li>
</ul>

<h2>How to use it</h2>

<p>If you really want to know how to use it I suggest you read the <a href="https://github.com/aaronpowell/KnockoutJS-Pre-parser/blob/master/README.md">Readme</a> or the tests but the quick and dirty is:</p>

<ul>
<li>Include it after you include KnockoutJS</li>
<li>???</li>
<li>Profit</li>
</ul>

<p>The pre-parser will actually hijack the <code>ko.applyBinding</code> method and perform the pre-parsing at that point, no custom stuff needs to be done to make it work :).</p>

<h2>Where to get it</h2>

<p>At the moment the only way to get it is via <a href="https://github.com/aaronpowell/KnockoutJS-Pre-parser">Github</a>, depending on interest/ motivation I'll put it up on Nuget for people to get it via as well.</p>

<h2>Conclusion</h2>

<p>So this wraps up my introduction to the KnockoutJS Pre-parser and an approach I am taking to address one of the issues which I have with KnockoutJS. Feel free to give me any feedback you have on the library and the idea in general.</p>
<img src="http://www.aaron-powell.com/via-feed/javascript/knockoutjs-preparser" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fknockoutjs-preparser&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=L6Fm_RPO5C4:4l1Ij-huguM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=L6Fm_RPO5C4:4l1Ij-huguM:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=L6Fm_RPO5C4:4l1Ij-huguM:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/L6Fm_RPO5C4" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;In my &lt;a href="http://www.aaron-powell.com/javascript/why-i-don-t-like-knockoutjs"&gt;previous post&lt;/a&gt; I outlined one of the biggest issues I have with &lt;a href="http://knockoutjs.com"&gt;KnockoutJS&lt;/a&gt; as being its WPF/ Silverlight binding syntax and how it requires you to put JavaScript into your HTML.&lt;/p&gt;

&lt;p&gt;Now I'm a pretty firm believe that if you are going to criticise something then you better make it constructive. Just saying "I don't like &lt;code&gt;blah&lt;/code&gt;" isn't helpful to a) the author of &lt;code&gt;blah&lt;/code&gt; or b) people wanting to learn more about &lt;code&gt;blah&lt;/code&gt;, so I decided that I would follow up my criticism of KnockoutJS with a way &lt;em&gt;I&lt;/em&gt; would go about fixing it.&lt;/p&gt;

&lt;h2&gt;Introducing the KnockoutJS preparser&lt;/h2&gt;

&lt;p&gt;To address my issue with KnockoutJS use of JavaScript in HTML I started looking at how I would go about it and the solution I kept coming back to was using the &lt;code&gt;data-*&lt;/code&gt; attributes to describe in my HTML an intention. I decided that if I could do this in a good, convention approach then I should be able to translate it back into a KnockoutJS binding with minimal impact.&lt;/p&gt;

&lt;p&gt;Out of this idea (and a challenge from my colleague &lt;a href="http://duc.as"&gt;Ducas&lt;/a&gt;) I set about taking my idea from my brain and putting in code.&lt;/p&gt;

&lt;p&gt;Essentially what I came up with was taking this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;span data-ko-text="firstName"&amp;gt;&amp;lt;/span&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And turning it into this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;span data-bind="text: firstName"&amp;gt;&amp;lt;/span&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The idea is that you take &lt;code&gt;data-ko-*&lt;/code&gt; as a prefix and use that to describe what could (well will...) become your binding syntax. Once getting this done I threw the code up on github and you can grab it from the &lt;a href="https://github.com/aaronpowell/KnockoutJS-Pre-parser"&gt;KnockoutJS Pre-Parser&lt;/a&gt; project page.&lt;/p&gt;

&lt;h2&gt;What does it address&lt;/h2&gt;

&lt;p&gt;The ultimate goal is to be able to use the &lt;code&gt;data-ko-*&lt;/code&gt; to describe out what you want in your HTML and the pre-parser will pick that up and &lt;em&gt;Knockout-ify&lt;/em&gt; it for you. Ideally I'd like to support all &lt;strong&gt;common&lt;/strong&gt; scenarios and so far I support:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Basic bindings with text, css, value, etc&lt;/li&gt;
&lt;li&gt;Template name binding&lt;/li&gt;
&lt;li&gt;Pre-parser syntax within a template&lt;/li&gt;
&lt;li&gt;Template options (but not completely, you still have to embed JSON in your template options attribute. I added it about 3 hours ago so it's still being worked on :P)&lt;/li&gt;
&lt;li&gt;Event handler wire ups (if you want a complex handler like defining scope, etc you'll still have to embed JavaScript for now, I'm trying to work out how to get around that)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;How to use it&lt;/h2&gt;

&lt;p&gt;If you really want to know how to use it I suggest you read the &lt;a href="https://github.com/aaronpowell/KnockoutJS-Pre-parser/blob/master/README.md"&gt;Readme&lt;/a&gt; or the tests but the quick and dirty is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Include it after you include KnockoutJS&lt;/li&gt;
&lt;li&gt;???&lt;/li&gt;
&lt;li&gt;Profit&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The pre-parser will actually hijack the &lt;code&gt;ko.applyBinding&lt;/code&gt; method and perform the pre-parsing at that point, no custom stuff needs to be done to make it work :).&lt;/p&gt;

&lt;h2&gt;Where to get it&lt;/h2&gt;

&lt;p&gt;At the moment the only way to get it is via &lt;a href="https://github.com/aaronpowell/KnockoutJS-Pre-parser"&gt;Github&lt;/a&gt;, depending on interest/ motivation I'll put it up on Nuget for people to get it via as well.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;So this wraps up my introduction to the KnockoutJS Pre-parser and an approach I am taking to address one of the issues which I have with KnockoutJS. Feel free to give me any feedback you have on the library and the idea in general.&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/javascript/knockoutjs-preparser" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fknockoutjs-preparser&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/javascript/knockoutjs-preparser</feedburner:origLink></item><item><title>JavaScript: A story</title><link>http://feedproxy.google.com/~r/LinqToAaronPowell/~3/EJOJakzrl38/a-story</link><category>javascript</category><category>random</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Aaron Powell</dc:creator><pubDate>Tue, 09 Aug 2011 20:17:35 PDT</pubDate><guid isPermaLink="false">http://www.aaron-powell.com/javascript/a-story</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Everyone use to notice the old war veteran that sat on the corner. His uniform was tatty and he’s always be spouting about his heyday with lines like “Don’t  you remember my role in the first browser war” and “If it wasn’t for me VBScript would be the language of choice of the browser!”. We’d look at him with pity, throw a few dollars his way and carry on with our day but never really got to know him. People who weren't from around here would come by occasionally and notice our friend and look on bemused, wondering why we put up with him.</p>

<p>As the years went by we’d still see him sitting on his corner, but gradually he was looking less dishevelled. We still threw him money and chuckled to ourselves when he’d say “You’re not the only one who does this, everyone listens to me, I’m the most popular out there”. I mean who could really take the guy seriously? We'd put up with him for years now, we knew some of his quirks but we never really paid him the time of day unless we wanted to get lost in pain and suffering.</p>

<p>Then one day he was gone; there was no dishevelled old man sitting on our corner in tatty military gear. We felt sad, had our old friend passed away at the end of the first decade in the 21st century? Should we have paid more attention to him; maybe actually loved him? In reflection maybe he wasn't so crazy; maybe he did have a point; maybe there really was a time when his uniform sparkled and we'd have looked at him with awe.</p>

<p>But then we noticed someone looking at us. We turned to see a proud looking man in a shiny new military uniform and as we looked longer we noticed that it wasn’t some stranger looking at us but it was our old friend JavaScript. He was now sober, he’d been given a shave, a shiny new uniform and an array of new armaments. But what was most important was that he was looking for action.</p>

<p>He saw us looking back at him, he smiled and shouted “I’m ready for round two, let's get this browser war started”.</p>

<p>And with a quiet dignity he wandered off to help us fight the next generation of wars.</p>
<img src="http://www.aaron-powell.com/via-feed/javascript/a-story" />  <div class='facebook'>
                      <iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fa-story&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'></iframe>
                    </div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=EJOJakzrl38:zDLwR1EAN7Q:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/LinqToAaronPowell?a=EJOJakzrl38:zDLwR1EAN7Q:-BTjWOF_DHI"><img src="http://feeds.feedburner.com/~ff/LinqToAaronPowell?i=EJOJakzrl38:zDLwR1EAN7Q:-BTjWOF_DHI" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/LinqToAaronPowell/~4/EJOJakzrl38" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Everyone use to notice the old war veteran that sat on the corner. His uniform was tatty and he’s always be spouting about his heyday with lines like “Don’t  you remember my role in the first browser war” and “If it wasn’t for me VBScript would be the language of choice of the browser!”. We’d look at him with pity, throw a few dollars his way and carry on with our day but never really got to know him. People who weren't from around here would come by occasionally and notice our friend and look on bemused, wondering why we put up with him.&lt;/p&gt;

&lt;p&gt;As the years went by we’d still see him sitting on his corner, but gradually he was looking less dishevelled. We still threw him money and chuckled to ourselves when he’d say “You’re not the only one who does this, everyone listens to me, I’m the most popular out there”. I mean who could really take the guy seriously? We'd put up with him for years now, we knew some of his quirks but we never really paid him the time of day unless we wanted to get lost in pain and suffering.&lt;/p&gt;

&lt;p&gt;Then one day he was gone; there was no dishevelled old man sitting on our corner in tatty military gear. We felt sad, had our old friend passed away at the end of the first decade in the 21st century? Should we have paid more attention to him; maybe actually loved him? In reflection maybe he wasn't so crazy; maybe he did have a point; maybe there really was a time when his uniform sparkled and we'd have looked at him with awe.&lt;/p&gt;

&lt;p&gt;But then we noticed someone looking at us. We turned to see a proud looking man in a shiny new military uniform and as we looked longer we noticed that it wasn’t some stranger looking at us but it was our old friend JavaScript. He was now sober, he’d been given a shave, a shiny new uniform and an array of new armaments. But what was most important was that he was looking for action.&lt;/p&gt;

&lt;p&gt;He saw us looking back at him, he smiled and shouted “I’m ready for round two, let's get this browser war started”.&lt;/p&gt;

&lt;p&gt;And with a quiet dignity he wandered off to help us fight the next generation of wars.&lt;/p&gt;
&lt;img src="http://www.aaron-powell.com/via-feed/javascript/a-story" /&gt;  &lt;div class='facebook'&gt;
                      &lt;iframe src='http://www.facebook.com/plugins/like.php?href=http%3a%2f%2fwww.aaron-powell.com%2fjavascript%2fa-story&amp;amp;layout=standard&amp;amp;show_faces=true&amp;amp;width=450&amp;amp;action=like&amp;amp;colorscheme=light&amp;amp;height=80' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:450px; height:80px;' allowTransparency='true'&gt;&lt;/iframe&gt;
                    &lt;/div&gt;</description><feedburner:origLink>http://www.aaron-powell.com/javascript/a-story</feedburner:origLink></item></channel></rss>

