<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>Blog dedicated to random mental doodles, code, graphics, amateur furniture and product designs, and other cool shit produced by Branko Vukelic.</description><title>Idea Machine</title><generator>Tumblr (3.0; @brankovukelic)</generator><link>http://www.brankovukelic.com/</link><item><title>Getting started with modular JavaScript</title><description>&lt;p&gt;If you are developing rich internet application, and moving business logic to the client-side by truckloads, there is nothing better than using some form of module system, a loader that can take care of dependencies and asynchronous loading of your modules, and a system to package everything up for production use as a minified single JavaScript file. This is a very quick introduction to &lt;a href="http://requirejs.org/"&gt;RequireJS&lt;/a&gt; and &lt;a href="https://github.com/amdjs/amdjs-api/wiki/AMD"&gt;AMD modules&lt;/a&gt; which makes all of above come true.&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;In this tutorial, you will find just one way to do things. There are many more, but as soon as you figure out this one way of doing things, you will most certainly discover the others with ease. Therefore, we won&amp;#8217;t dwell on all the nuances of AMD modules, and instead focus on how I generally do things so you can get started quickly and painlessly.&lt;/p&gt;

&lt;h3&gt;NodeJS (we&amp;#8217;ll need it later)&lt;/h3&gt;

&lt;p&gt;Before you start, you will need to install &lt;a href="http://nodejs.org/"&gt;NodeJS&lt;/a&gt; in your computer. Installation is well covered on the homepage, so I won&amp;#8217;t go into details, but keep in mind that, if you use Linux, you probably do not want to install the version from your distribution&amp;#8217;s package repository unless you are running Arch Linux and use AUR to do it. Grab the source and compile it (trust me, it&amp;#8217;s not hard). For Linux users, here&amp;#8217;s a copy-paste series of commands that will install NodeJS 0.6.15 into your user&amp;#8217;s home directory (note it needs to be all one line, so I had to break it up with ):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd ~ 
wget &lt;a href="http://nodejs.org/dist/v0.6.15/node-v0.6.15.tar.gz"&gt;http://nodejs.org/dist/v0.6.15/node-v0.6.15.tar.gz&lt;/a&gt;
tar xvf node-v0.6.15.tar.gz
mkdir -p ~/local
cd node-v0.6.15
./configure --prefix=$HOME/local
make install
echo 'export PATH=$PATH:$HOME/local/bin' &amp;gt;&amp;gt; ~/.bashrc
echo 'export NODE_PATH=$HOME/local' &amp;gt;&amp;gt; ~/.bashrc
source ~/.bashrc
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you can type &lt;code&gt;node -v&lt;/code&gt; and confirm NodeJS is working. Also make sure NPM is installed along with NodeJS by typing &lt;code&gt;npm -v&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;Setting things up&lt;/h3&gt;

&lt;p&gt;Apart from NodeJS, you will also need to create a project directory. Let&amp;#8217;s call our project &lt;code&gt;test&lt;/code&gt; (yes, very creative, I know).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;mkdir test
cd test
mkdir js
mkdir css
mkdir img
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There&amp;#8217;s our project tree.&lt;/p&gt;

&lt;p&gt;Now we need a few more things. First, an index file that looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;!doctype html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;RIA test&amp;lt;/title&amp;gt;
    &amp;lt;link rel="stylesheet" href="css/main.css"&amp;gt;
    &amp;lt;script src="js/require.js" data-main="js/boot"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;!-- move along, nothing to see here! --&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This file will remain absolutely intact throughout the development. It does mention a few files and paths that we currently don&amp;#8217;t have, so let&amp;#8217;s take care of those.&lt;/p&gt;

&lt;p&gt;Create an empty CSS file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;touch css/main.css
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Download &lt;code&gt;require.js&lt;/code&gt; and &lt;code&gt;jquery.js&lt;/code&gt;, and create empty &lt;code&gt;boot.js&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd js
wget &lt;a href="http://requirejs.org/docs/release/1.0.7/comments/require.js"&gt;http://requirejs.org/docs/release/1.0.7/comments/require.js&lt;/a&gt;
wget &lt;a href="http://code.jquery.com/jquery-1.7.2.js"&gt;http://code.jquery.com/jquery-1.7.2.js&lt;/a&gt;
touch boot.js
cd ..
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And&amp;#8230; that&amp;#8217;s it. That&amp;#8217;s the skeleton setup for our RIA frontend. If you haven&amp;#8217;t bothered to create these, you can grab a &lt;a href="https://github.com/foxbunny/amdtut/zipball/prepared"&gt;zip file&lt;/a&gt; with the contents we have so far.&lt;/p&gt;

&lt;p&gt;Now, a word about what these files will do.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;require.js&lt;/code&gt; is our module loader with dependency resolution. It has an API that conforms to the &lt;a href="https://github.com/amdjs/amdjs-api/wiki/AMD"&gt;AMD spcification&lt;/a&gt; which we will make use of to build our modules.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;jquery.js&lt;/code&gt;&amp;#8230; ok, seriously, does anyone need an explanation about what jQuery is and what it is used for?&lt;/p&gt;

&lt;p&gt;&lt;code&gt;boot.js&lt;/code&gt; is our main module, which kicks off the whole application (more on that later).&lt;/p&gt;

&lt;p&gt;&lt;code&gt;main.css&lt;/code&gt; is a CSS file that we will use to collect all our CSS modules (yes, you read right, CSS &lt;em&gt;modules&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Ok, let&amp;#8217;s get the ball rolling.&lt;/p&gt;

&lt;h3&gt;Baby step&lt;/h3&gt;

&lt;p&gt;If you load the index.html now, you&amp;#8217;ll see that nothing actually happens, and our page is blank. That&amp;#8217;s because our &lt;code&gt;boot&lt;/code&gt; module isn&amp;#8217;t doing anything yet. So let&amp;#8217;s add something to it.&lt;/p&gt;

&lt;p&gt;Before we do this, you should be aware that &lt;code&gt;boot&lt;/code&gt; module is special, not just because it&amp;#8217;s the last module that gets loaded, but also because&amp;#8230; Um, what&amp;#8217;s that? Yes, I said &amp;#8216;last&amp;#8217;. It&amp;#8217;s last because any dependencies that it lists will get loaded first. And dependencies of those dependencies before that&amp;#8230; And so on. Got it? Ok, where was I&amp;#8230;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;boot.js&lt;/code&gt; uses a syntax that is a wee bit different than other modules. I&amp;#8217;ll get around to that, but first, let me show you the code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require(['jquery'], function($) {
  $(document).ready(function() {
    alert('ready!');
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If the code is correct, you should see no JavaScript errors, and you should see an alert box that says &lt;em&gt;ready!&lt;/em&gt;. What that means is, jquery was successfully loaded, and the &lt;code&gt;ready&lt;/code&gt; even handler was fired correctly as well. So everything works. (Get the &lt;a href="https://github.com/foxbunny/amdtut/zipball/simpleboot"&gt;zip file&lt;/a&gt; of this step.)&lt;/p&gt;

&lt;p&gt;The whole module is basically a &lt;code&gt;require()&lt;/code&gt; call with two arguments. The first argument is a list of dependencies. You list dependencies without the &lt;code&gt;.js&lt;/code&gt; extension, and relative to wherever you &lt;code&gt;boot&lt;/code&gt; script is. So if your boot script is in &lt;code&gt;js/&lt;/code&gt; directory (as it should be per this tutorial), then a dependency that looks like &lt;code&gt;lib/somemodule.js&lt;/code&gt; will be loaded from &lt;code&gt;js/lib/somemodule.js&lt;/code&gt;. Although paths are relative, true relative paths cannot be used. So, you cannot say something like &lt;code&gt;../lib/somemodule.js&lt;/code&gt; or &lt;code&gt;./lib/somemodule.js&lt;/code&gt;. There are workarounds for this, but those workarounds are neither elegant, nor strictly required (no pun intended) to have a good experience developing with AMD.&lt;/p&gt;

&lt;h3&gt;Let&amp;#8217;s build our first AMD modules&lt;/h3&gt;

&lt;p&gt;First order of business is templating. We want to make a very simple template library, and use it as a module.&lt;/p&gt;

&lt;p&gt;Create a directory called &lt;code&gt;lib&lt;/code&gt; in the &lt;code&gt;js&lt;/code&gt; directory. That&amp;#8217;s where we will keep all our helper libraries:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;mkdir js/lib
touch js/lib/template.js
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let&amp;#8217;s edit the &lt;code&gt;template.js&lt;/code&gt; now:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;define([], function() {

});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;First thing first, that&amp;#8217;s the module skeleton. It looks very much like &lt;code&gt;boot.js&lt;/code&gt;, except that it uses &lt;code&gt;define()&lt;/code&gt; call instead of &lt;code&gt;require()&lt;/code&gt; call. And that&amp;#8217;s basically your AMD module&amp;#8230; more or less.&lt;/p&gt;

&lt;p&gt;The empty array is our dependency list, which is empty because we have (and need) no dependencies. The function is called a &lt;em&gt;factory&lt;/em&gt; function, and its job is to return the finished module.&lt;/p&gt;

&lt;p&gt;The module is currently empty, because factory function doesn&amp;#8217;t do anything. Since it has no code in it, it&amp;#8217;s not very useful (not useful at all, that is), so let&amp;#8217;s work on that:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;define([], function() {
  var template = {};
  return template;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Ok, that&amp;#8217;s better. What we&amp;#8217;ve done is, we&amp;#8217;ve created an empty object called &lt;code&gt;template&lt;/code&gt;, and returned it. Now our &lt;code&gt;template&lt;/code&gt; module is actually a real module, albeit it still does nothing.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;template&lt;/code&gt; object actually represents the eternal interface of our module. Anything that we put in that object will be exposed (because the object is returned from the function). This is where we define the API for the module.&lt;/p&gt;

&lt;p&gt;The template module obviously needs a rendering function. So let&amp;#8217;s expose such a function through the &lt;code&gt;template&lt;/code&gt; object:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  /**
   * Render template
   * 
   * @param {String} t Template
   * @param {Object} d Data
   * @return {String} Rendered template
   */
  template.render = function(t, d) {
    // For each key in `d`, subsitute key in template with value
    for (key in d) {
      // We'll use '$key' format for placeholders in our template
      t = t.replace(new RegExp('\\$' + key, 'g'), d[key]);
    }

    // Return 'rendered' template
    return t;
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is rudimentary template &amp;#8216;engine&amp;#8217; that simply takes an object with keys, and replaces $+key placeholders in a string with values corresponding to those keys. Let&amp;#8217;s test this out. Edit the &lt;code&gt;boot&lt;/code&gt; module to look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require(['jquery', 'lib/template'], function($, template) {
  $(document).ready(function() { 
    var tHithere = "Hi there. It's now $time";
    $('body').append(template.render(tHithere, {time: new Date()}));
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you reload the page now, it should print out &amp;#8220;Hi there, it&amp;#8217;s now NOW&amp;#8221;, where NOW is your current date and time were you are (in my case it&amp;#8217;s &amp;#8220;Hi there, it&amp;#8217;s now Thu Apr 12&amp;#160;2012&amp;#160;17:26:35 GMT+0200 (CEST)&amp;#8221;). (&lt;a href="https://github.com/foxbunny/amdtut/zipball/simpletemplate"&gt;zip file&lt;/a&gt; of current progress)&lt;/p&gt;

&lt;p&gt;So, let me show you something interesting now. Open your development console and try rendering a template. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;gt; template.render('My name is $name', {name: 'Branko'});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What you get is a &lt;code&gt;ReferenceError&lt;/code&gt;. Why? Because modules are not global. Whatever you defined in your module is not accessible globally, and even when the module is referenced from another module, it&amp;#8217;s only accessible from within that module. This makes it possible to have complete freedom when defining stuff inside your modules.&lt;/p&gt;

&lt;h3&gt;Privacy&lt;/h3&gt;

&lt;p&gt;So, module exposed methods are accessible from modules that reference (load) the module. How about if we wanted to keep some things private? Let&amp;#8217;s do that now. The line where we build the regular expression is a bit ugly, so let&amp;#8217;s move that part out into a private function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;define([], function() {
  var template = {};

  // Build regular expression
  function keyRe(key) {
    return new RegExp('\\$' + key, 'g');
  }

  /**
   * Render template
   * 
   * @param {String} t Template
   * @param {Object} d Data
   * @return {String} Rendered template
   */
  template.render = function(t, d) {
    // For each key in `d`, subsitute key in template with value
    for (key in d) {
      // We'll use '$key' format for placeholders in our template
      t = t.replace(keyRe(key), d[key]);
    }

    // Return 'rendered' template
    return t;
  };

  return template;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The new function &lt;code&gt;keyRe&lt;/code&gt; is not exposed through a property on the &lt;code&gt;template&lt;/code&gt; object, so it&amp;#8217;s therefore &lt;em&gt;not&lt;/em&gt; accessible to other modules. You can try calling &lt;code&gt;keyRe()&lt;/code&gt; from the &lt;code&gt;boot&lt;/code&gt; module, or even try &lt;code&gt;template.keyRe&lt;/code&gt;, but both attempts would fail. (&lt;a href="https://github.com/foxbunny/amdtut/zipball/privatefunc"&gt;zip file&lt;/a&gt; of current progress)&lt;/p&gt;

&lt;h3&gt;Loading text templates&lt;/h3&gt;

&lt;p&gt;This is all fine and dandy, but if we wanted to edit HTML templates, it would be cumbersome to use  JavaScript strings, right? So, we obviously need a way to load templates from text files.&lt;/p&gt;

&lt;p&gt;Before we get to that, let&amp;#8217;s first define a template that we&amp;#8217;ll use. Create a directory called &lt;code&gt;templates&lt;/code&gt; in your &lt;code&gt;js&lt;/code&gt; directory:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;mkdir js/templates
touch js/templates/main.tpl
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now edit &lt;code&gt;main.tpl&lt;/code&gt; to look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;h1&amp;gt;RIA test&amp;lt;/h1&amp;gt;

&amp;lt;p&amp;gt;Hi, it's now $time, and you're looking at 
foxbunny's &amp;lt;em&amp;gt;AMD tutorial&amp;lt;/em&amp;gt;.&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;#8217;s done. But how do we load it? RequireJS sports a plugin system, which allows for various load plugins to be used. One such plugin is the aptly named &amp;#8216;text&amp;#8217; plugin, which can be used to load plain-text files from a server. Download that plugin and put it in &lt;code&gt;js&lt;/code&gt; directory:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd js
wget &lt;a href="http://requirejs.org/docs/release/1.0.7/comments/text.js"&gt;http://requirejs.org/docs/release/1.0.7/comments/text.js&lt;/a&gt;
cd ..
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let&amp;#8217;s modify our &lt;code&gt;boot&lt;/code&gt; module to use this plugin and fetch &lt;code&gt;main.tpl&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require(
  [
    'jquery', 
    'lib/template', 
    'text!templates/main.tpl'
  ], function(
    $, 
    template, 
    tMain
  ) {

  $(document).ready(function() { 
    $('body').append(template.render(tMain, {time: new Date()}));
  });

});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, I&amp;#8217;ve changed the layout a bit so I can keep better track of dependencies. The way we used the text plugin is we just prepended &lt;code&gt;text!&lt;/code&gt; to the path of the template file we wanted to load. Note that we must also include the extension in the template&amp;#8217;s path. (&lt;a href="https://github.com/foxbunny/amdtut/zipball/textplugin"&gt;zip file&lt;/a&gt; of current progress)&lt;/p&gt;

&lt;p&gt;If you are using Chrome, the text plugin may trigger a security error &amp;#8220;NETWORK_ERR: XMLHttpRequest Exception 101&amp;#8221; because Chrome does not allow AJAX requests to be made to local file system. If you want to get around this, you must use a server to server your project.&lt;/p&gt;

&lt;h3&gt;Adding some style&lt;/h3&gt;

&lt;p&gt;Let&amp;#8217;s add some stylesheets to spice things up a bit. We&amp;#8217;ll divide the CSS properties into two modules, one dealing with layout, and one dealing with typography. In reality, you might take a completely different approach, and divide stylesheets by functionality, or by widget. The basic principle of writing modular stylesheets is the same.&lt;/p&gt;

&lt;p&gt;Add two files, one called &lt;code&gt;layout.css&lt;/code&gt;, and one called &lt;code&gt;type.css&lt;/code&gt; to your css directory:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;touch css/layout.css
touch css/type.css
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now edit &lt;code&gt;layout.css&lt;/code&gt; to look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;* {
  margin: 0;
  padding: 0;
}

body {
  margin: 30px;
  width: 300px;
  border-radius: 10px;
  background: #996;
  padding: 1em;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.7);
  border: 1px solid #fff;
}

html {
  background: #588;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Contents of the &lt;code&gt;type.css&lt;/code&gt; might look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;html, body {
  font-family: Helvetica, Arial, "Liberation Sans", sans-serif;
  font-size: 14px;
}

h1 {
  font-size: 2em;
  margin-bottom: 1em;
  color: #ee9;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To load these modules, just use the &lt;code&gt;@import&lt;/code&gt; rules (note that if you add any CSS properties to &lt;code&gt;main.css&lt;/code&gt;, the &lt;code&gt;@import&lt;/code&gt; rules &lt;em&gt;must&lt;/em&gt; be at the top of the file, or they won&amp;#8217;t work). Edit the &lt;code&gt;main.css&lt;/code&gt; file to look like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@import url('./layout.css');
@import url('./type.css');
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The rendered page now looks more acceptable, depending on where you come from. (&lt;a href="https://github.com/foxbunny/amdtut/zipball/styled"&gt;your zipball&lt;/a&gt; with stylesheets)&lt;/p&gt;

&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_m2dkm0L54S1qa7r0v.png" alt="Screenshot of the page after adding styles"/&gt;&lt;/p&gt;

&lt;h3&gt;Final steps&lt;/h3&gt;

&lt;p&gt;Now that you&amp;#8217;ve learned how to use RequireJS (I hope you have), and also a bit about organizing your code, let&amp;#8217;s take a look at our payload.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_m2dkskieRo1qa7r0v.png" alt="Network panel in chrome showing 10 requests and 348kb of data"/&gt;&lt;/p&gt;

&lt;p&gt;That&amp;#8217;s 10 requests and 348kb of payload right there. A bit on the heavy side. But no matter how heavy, the number of requests is always the main reason your site loads so slow (or maybe it doesn&amp;#8217;t, but if it did, it would be the number of items, and &lt;em&gt;then&lt;/em&gt; the size of the items).&lt;/p&gt;

&lt;p&gt;We can cut this down to 4 (one for &lt;code&gt;index.html&lt;/code&gt;, one for &lt;code&gt;require.js&lt;/code&gt; loader, one of all other JavaScript files, and one for all CSS). Technically, you can even remove &lt;code&gt;require.js&lt;/code&gt; from the equation by including it with other JS files, but I&amp;#8217;ll leave that as an exercise to you.&lt;/p&gt;

&lt;p&gt;The reason we installed NodeJS before is because of this. RequireJS project provides a nice optimization tool called &lt;code&gt;r.js&lt;/code&gt; which will help us package our project into a set of 4 files we mentioned above.&lt;/p&gt;

&lt;p&gt;First thing first, let&amp;#8217;s install r.js:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;npm install requirejs -g
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the &lt;code&gt;-g&lt;/code&gt; flag which tells NPM (Node package manager) to install the &lt;code&gt;requirejs&lt;/code&gt; package globally. With that done, we now have access to &lt;code&gt;r.js&lt;/code&gt; command. Before you can try this new toy, you need to write a project description. Just grab this one and put it in a file called &lt;code&gt;app.build&lt;/code&gt; in the &lt;code&gt;test&lt;/code&gt; directory:&lt;/p&gt;

&lt;p&gt;({
     appDir: &amp;#8220;.&amp;#8221;,
     baseUrl: &amp;#8220;js&amp;#8221;,
     dir: &amp;#8220;../build&amp;#8221;,
     uglify: {
       top_level: false,
       accii_only: false,
       beautify: false
     },
     optimizeCss: &amp;#8220;standard&amp;#8221;,
     inlineText: true,
     findNestedDependencies: true,
     modules: [
       {
       name: &amp;#8220;boot&amp;#8221;,
       path: &amp;#8220;js/boot&amp;#8221;
     }
     ]
   })&lt;/p&gt;

&lt;p&gt;You can read more about what each option does by looking at the &amp;#8216;full version&amp;#8217; of the build file &lt;a href="https://github.com/jrburke/r.js/blob/master/build/example.build.js"&gt;in r.js&amp;#8217;s github repository&lt;/a&gt;. In our case, we optimize CSS, inline any plain-text/HTML templates into modules that require them (so that they won&amp;#8217;t be loaded separately after the page is loaded), and specify a few options for uglifyJS (JavaScript minifier) to avoid headaches with non-ASCII characters, etc.&lt;/p&gt;

&lt;p&gt;The most important options above are &lt;code&gt;appDir&lt;/code&gt; which points to a directory relative to the build file, and &lt;code&gt;dir&lt;/code&gt;, which specifies where the optimized project will be output. Note that the output directory will contain everything that your source directory does.&lt;/p&gt;

&lt;p&gt;Now that we&amp;#8217;ve got our build profile, we can proceed to actually build it. (&lt;a href="https://github.com/foxbunny/amdtut/zipball/buildprofile"&gt;zip file&lt;/a&gt; of the current progress)&lt;/p&gt;

&lt;p&gt;To build it simply run this command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;r.js -o app.build
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The built project will be dumped into a directory called &lt;code&gt;build&lt;/code&gt; just outside the &lt;code&gt;test&lt;/code&gt; directory.&lt;/p&gt;

&lt;p&gt;Loading the built project now gives us this in our network tab:&lt;/p&gt;

&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_m2dlohCvta1qa7r0v.png" alt="Network tab after loading the built project"/&gt;&lt;/p&gt;

&lt;p&gt;Yes, that&amp;#8217;s right. 4 requests, and exactly 114kb of payload, all your dependencies and templates neatly packed into a single JS file, and all your CSS modules neatly packed into a single CSS file. How cool is that!&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;You&amp;#8217;ve hopefully learned how to write AMD modules, and use them with RequireJS. You&amp;#8217;ve possibly learned a thing or two about writing modular code in general. And you&amp;#8217;ve learned a thing or two about how to spare your users from that 5-minute load time. But if you&amp;#8217;re not used to rich internet applications in general, you might be missing a point here. So, load up that test page again, right-click on it, and do &amp;#8220;View source&amp;#8221;. Here&amp;#8217;s what it looks like here:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;!doctype html&amp;gt;
&amp;lt;html&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;RIA test&amp;lt;/title&amp;gt;
    &amp;lt;link rel="stylesheet" href="css/main.css"&amp;gt;
    &amp;lt;script src="js/require.js" data-main="js/boot"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;!-- move along, nothing to see here! --&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Yes, &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt; is completely empty. Even though the page does contain things, and the developer tools show you all the elements on the page, the &amp;#8220;View source&amp;#8221; function is empty because it is showing you the page as it was originally loaded from the server. We&amp;#8217;ve actually built the whole page using JavaScript.&lt;/p&gt;

&lt;p&gt;Yeah, I knew you knew. These things aren&amp;#8217;t exactly news. I hope, though, that RequireJS has made your work much easier, and much more organized.&lt;/p&gt;

&lt;p&gt;The source code of this project can be downloaded from &lt;a href="https://github.com/foxbunny/amdtut"&gt;its GitHub repository&lt;/a&gt;. Feel free to use it as you see fit, without any restrictions. You can also use it as a template for your future projects. I use this template in production at Monwara LLC, so it should work.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/20970258165</link><guid>http://www.brankovukelic.com/post/20970258165</guid><pubDate>Thu, 12 Apr 2012 19:07:00 +0200</pubDate><category>amd</category><category>javascript</category><category>modular code</category><category>requirejs</category><category>featured</category><category>tutorials</category></item><item><title>The New Resistance: Aftermath of the Serbian Revolution</title><description>&lt;p&gt;On 5 October 2000, almost twelve years ago, Serbia has won its freedom. Its people have ousted Slobodan Milošević, and ended an almost ten-year-long rule of the Serbian Socialist Party (SPS). And then what? For the next twelve years, have the Serbs seen any improvement?&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;The key to revolution&amp;#8217;s success was a youth organization called Otpor. Today, Otpor&amp;#8217;s founders are traveling across the globe to teach the tactics they used to other nations. A typical session might include wisdom like this:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&amp;#8220;Do a small thing and if it is successful, you have the confidence to do another one and another one,&amp;#8221; Popovic said. &amp;#8220;You recruit people, train them, and keep them constantly active. You hit, proclaim victory &amp;#8212; and get the hell out. If it is successful, people will come to you. Participating in small successes, you build self-confidence. Nonviolent struggle changes the way people think of themselves.&amp;#8221; &amp;#8212; &lt;a href="http://www.foreignpolicy.com/articles/2011/02/16/revolution_u?page=0,5"&gt;&amp;#8220;Revolution U&amp;#8221;, Foreign Policy, 16 February 2011&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Have people really changed the way they think of themselves, though? Twelve years after the 5 October revolution in Serbia, I&amp;#8217;ve talked to many young people that participated directly or indirectly in the events, and observed the people around me. There is definitely a permanent change that resulted from the past events. But I also feel those changes are not exactly what Popović and others thought or hoped they&amp;#8217;d be.&lt;/p&gt;

&lt;p&gt;Economic situation in Serbia is not at all good. This country is still transitioning towards free market capitalism, and western-style parliamentary democracy still hasn&amp;#8217;t rooted itself in the Serbian collective consciousness. Some of the today&amp;#8217;s students are again involved in protests, still looking for a definitive change towards a better society. There are voices that claim 1990s were vastly better.&lt;/p&gt;

&lt;p&gt;During the 1990s, Serbia was under economic blockade imposed by the western countries. Trade with most other countries was virtually non-existent. Domestic production (mainly foods) and smuggling formed the basis of day-to-day survival. Inflation was unimaginably high, and paychecks usually invalidated in under 12 hours. Those crisis, however, had a sense of reality to it that people knew what to do with. They were desperate, but not apathetic. They fought and prevailed in the end.&lt;/p&gt;

&lt;p&gt;During the 78-day NATO military campaign over Serbia in 1998, I felt most strongly the high spirit of survivalism in Serbia. Although, as a foreigner, I have had problems myself, I still adored this energy, and things used to be fun during those times. Most people did not fear. The Early 1990&amp;#8217;s economic crisis seemed like the worst they survived, and that nothing could ever break them. Unfortunately, this was the last climax of the Serbian spirit before it was permanently smashed after the 5 October revolution in 2000.&lt;/p&gt;

&lt;p&gt;Today&amp;#8217;s crisis is different. People are drowning in debt, struggling at the verge of existence, constantly pressed to make ends meet. Whether one will earn enough to pay the electricity bills that are several month overdue has become a common concern. Even worse, poverty brought about a tremendous storm of corruption, and young mothers in some Serbian cities have a realistic concern of having to come up with bribes in excess of their monthly income simply to prevent their child from being murdered by corrupted doctors. (Of course, you won&amp;#8217;t see these in news, but I actually know people who are concerned about this.) The everyday stress is slowly but surely breaking people into fatalist, apathetic wrecks.&lt;/p&gt;

&lt;p&gt;Unlike in 1990s, though, the lack of immediate and obvious danger suspends them between an illusion that they might make it, and the actual poverty that surrounds them. They are locked in passivity and insensitivity, hoping subconsciously for a hero that would salvage them from the bad situation they are in, instead of believing in their own power as Otpor&amp;#8217;s former leaders would like to think (or have us think at least).&lt;/p&gt;

&lt;p&gt;The danger of the new situation is that the minimum level of survival is still guaranteed (or at least most people think so). This provides a tiny safe spot in the sea of poverty, that people can cling on to. People usually fight if they believe there is no place to go, but as long as they have &lt;em&gt;something&lt;/em&gt;, they will stick to it, and not try to move for the fear of losing this foothold.&lt;/p&gt;

&lt;p&gt;Another phenomenon I&amp;#8217;ve observed talking to people is that there are people who actually believe it&amp;#8217;s much better now. The case is usually that things &lt;em&gt;are&lt;/em&gt; somewhat better than having to scrape for life, but only for them alone. For example, graphic designers are now sought for, unlike before the revolution, and most graphic designers can get decent jobs as a result. (&amp;#8220;Decent&amp;#8221;, is of course, subject to debate.) Talking to these people, you quickly realize they have very little understanding of the current situation, and that they, essentially, live in a surreal world that heavily draws on the ideas of the early 2000s. These people are, I feel, as spiritually wrecked as the poor, and they invent this illusion of a better Serbia in order to cover it up. For them, if something &lt;em&gt;is&lt;/em&gt; wrong, then it is the direct result of the evils Slobodan Milošević did over a decade ago, and everything else is &amp;#8220;fine and dandy&amp;#8221; until proven otherwise. This distortion creates a much bigger danger to the society at large, as such undisillusionable people are more likely to have a reactionary attitude, in case people decide to oppose the new powers in Serbia.&lt;/p&gt;

&lt;p&gt;While the former Otpor leaders, now working as CANVAS, are selling their ideology to countries around the globe that are only too eager to jump on the revolutionary bandwagon, people have to be aware of the consequences of such revolutions. &lt;em&gt;The art of war&lt;/em&gt; is not the same as &lt;em&gt;the art of post-war&lt;/em&gt;. What remains after a non-violent revolution is not much better than what remains after a war: a sea of spiritually wrecked people that are even weaker and even more susceptible to manipulation than before. Or perhaps, &lt;a href="http://landdestroyer.blogspot.com/2011/06/fake-revolutions.html"&gt;financiers of CANVAS&lt;/a&gt; actually look forward to sailing on those seas?&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/16227093794</link><guid>http://www.brankovukelic.com/post/16227093794</guid><pubDate>Sat, 21 Jan 2012 16:03:00 +0100</pubDate><category>global politics</category><category>Serbia</category></item><item><title>Apple laptop parody featuring Plum D series, an imaginary...</title><description>&lt;img src="http://24.media.tumblr.com/tumblr_lso3fen1mi1qapde9o1_500.jpg"/&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;Apple laptop parody featuring Plum D series, an imaginary Serbian-made laptop with pretty cool specs.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/11117455233</link><guid>http://www.brankovukelic.com/post/11117455233</guid><pubDate>Fri, 07 Oct 2011 01:18:49 +0200</pubDate><category>Apple</category><category>parody</category><category>fun</category><category>Blender 3D</category><category>Plum</category><category>Serbia</category></item><item><title>After watching the Trigun series and the movie edition, I...</title><description>&lt;img src="http://24.media.tumblr.com/tumblr_lsjb7fcfP21qapde9o1_500.jpg"/&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;After watching the &lt;a href="http://en.wikipedia.org/wiki/Trigun"&gt;Trigun&lt;/a&gt; series and the movie edition, I couldn’t resist recreating the sunglasses worn by the protagonist, Vash the Stampede. Used Blender as usual. Before you ask, yes, the internal renderer is still missing the caustics.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/11016278919</link><guid>http://www.brankovukelic.com/post/11016278919</guid><pubDate>Tue, 04 Oct 2011 11:18:51 +0200</pubDate><category>Vash</category><category>Trigun</category><category>sunglasses</category><category>anime</category><category>Blender 3D</category></item><item><title>Node Web Development</title><description>&lt;blockquote&gt;
  &lt;p&gt;Quit scratching your head already. Of course you&amp;#8217;re doing it, scratching your
  head and mumbling to yourself, &amp;#8220;What&amp;#8217;s a browser language doing on the
  server?&amp;#8221; In truth, JavaScript has a long and largely unknown history outside
  the browser.  JavaScript is a programming language, just like any other
  language, and the better question to ask is &amp;#8220;Why should JavaScript remain
  trapped inside browsers?&amp;#8221;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_lrh37eEQde1qa7r0v.png" alt="Cover of Node Web Development"/&gt;&lt;/p&gt;

&lt;p&gt;With these words, begins your jorney though web development using server-side
JavaScript with Node.js. Right from the start, David Herron&amp;#8217;s &lt;em&gt;Node Web
Development&lt;/em&gt; (2011, Packt) gives hints as to who this book would be most useful
to: experienced software engineers, getting ready to explore the Node.js
platform for the very first time. Frontend engineers that are looking to get
into backend development, would probably find this book very useful.&lt;/p&gt;

&lt;p&gt;If you &lt;em&gt;are&lt;/em&gt; the tartget audience, though, you will find this book to be one of
the best resources on Node.js available.&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;Before I begin my review, I would like to note that the review was requested by
Packt. Although it has been requested, you can consider this to be my
completely open and honest review of the book. In other words, it really &lt;em&gt;is&lt;/em&gt; a
good book.&lt;/p&gt;

&lt;p&gt;Node.js isn&amp;#8217;t just any new thing that comes to Web. You could say that Node.js
is as important to server-side as something like client-side Python (substitute
&amp;#8216;Python&amp;#8217; with your favorite language) would be to browsers. It also proves
(hopefully once and for all) that JavaScript &lt;em&gt;is&lt;/em&gt; a powerful language and does
away with the myth that it&amp;#8217;s only good for light scripting in browsers.
Finally, it creates an opportunity for talented front-end engineers to also try
their JavaScript skills on the server-side.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Node Web Development&lt;/em&gt; is therefore a book that reveals the true face of
JavaScript, in addition to being a good introduction to Node.js platform, and
thus makes an important contribution to modern web development as a whole.&lt;/p&gt;

&lt;p&gt;With &lt;em&gt;Node Web Development&lt;/em&gt;, it&amp;#8217;s like walking into a restaurant for a burger,
and getting salad, drinks, and free WiFi with it, for free. The order of topics
in the book is a bit non-standard, but very much in line with how work is done
in reality. That&amp;#8217;s probably one of the things experienced users will find very
useful. If you&amp;#8217;re already a web developer, you will appreciate having things
that interest you the most covered early on. As for newbies, it will lay down a
good foundation, which is also a good thing. All in all, you will learn, I
believe, a proper way to do things, from someone that&amp;#8217;s been doing it for a
very long time. ;)&lt;/p&gt;

&lt;p&gt;If you are an experienced JavaScript developer, you will appreciate the fact
that an exotic thing like JavaScript modules is covered first thing. Modules
are probably one of the most important things frontend developers should learn
coming to Node.&lt;/p&gt;

&lt;p&gt;NPM, Node Package Manager, is covered in great detail early on. That is
excellent, considering it has become a de facto standard in the Node developer
toolbox.&lt;/p&gt;

&lt;p&gt;The book also covers some of the libraries that are typically used for web
development on Node. These include Connect, Express, and Mongoose (MongoDB
ORM).&lt;/p&gt;

&lt;p&gt;All in all, you will learn 80% of Node-related &amp;#8216;stuff&amp;#8217; that needs knowing if
you want to do web development on Node.&lt;/p&gt;

&lt;p&gt;One thing I found missing was unit testing. Node.js has a few very good unit
testing libraries that are definitely worth covering. I guess covering the full
choice would be outside the scope of most books (except maybe a book dedicated
to unit testing in Node), but I think at least expresso should have been
mentioned.&lt;/p&gt;

&lt;p&gt;As someone who has been using Node for almost two months now, I definitely
found the book useful. If you are just starting, I think this book is a must.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/10168010462</link><guid>http://www.brankovukelic.com/post/10168010462</guid><pubDate>Tue, 13 Sep 2011 19:23:00 +0200</pubDate><category>nodejs</category><category>packt</category><category>books</category></item><item><title>Herman's Thought Soup</title><description>&lt;a href="http://herdhound.blogspot.com/"&gt;Herman's Thought Soup&lt;/a&gt;: &lt;p&gt;People who follow me &lt;a href="http://twitter.com/#!/foxbunny"&gt;on Twitter&lt;/a&gt; know about it, but I thought I’d leave a short note here as well. So anyway, there’s this thing, a blog about anything and everything Herd-Hound-related. There will be quite a few posts about the technical stuff that goes on under the hood, but also the business stuff. Stay tuned. ;)&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/10126724410</link><guid>http://www.brankovukelic.com/post/10126724410</guid><pubDate>Mon, 12 Sep 2011 17:26:36 +0200</pubDate><category>Herd Hound</category></item><item><title>We have a new family member, the lovely Labrador Retriever we...</title><description>&lt;img src="http://25.media.tumblr.com/tumblr_lr5xb7sTKS1qapde9o1_500.jpg"/&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;We have a new family member, the lovely Labrador Retriever we call &lt;a href="http://en.wikipedia.org/wiki/Michiko_to_Hatchin"&gt;Hatchin&lt;/a&gt;. :)&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/9922165291</link><guid>http://www.brankovukelic.com/post/9922165291</guid><pubDate>Wed, 07 Sep 2011 19:16:19 +0200</pubDate><category>family</category></item><item><title>Packt launch sixth annual Open Source Awards</title><description>&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_lr5sazLmru1qa7r0v.png" alt=""/&gt;&lt;/p&gt;

&lt;p&gt;The &lt;a href="http://www.packtpub.com/open-source-awards-home"&gt;2011 Open Source Awards&lt;/a&gt; was launched today by Packt, inviting people to visit &lt;a href="http://www.packtpub.com/"&gt;&lt;a href="http://www.PacktPub.com"&gt;www.PacktPub.com&lt;/a&gt;&lt;/a&gt; and submit nominations for their favorite Open Source project. Now in its sixth year, the Awards continue in its aim of encouraging, supporting, recognizing and rewarding all Open Source projects.&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;The 2010 Open Source Award Winners included the Open Source Content Management System (CMS) Award winner CMS Made Simple, Open Source JavaScript Libraries Award winner jQuery and Pimcore the winner of the Most Promising Open Source Project Award.&lt;/p&gt;

&lt;p&gt;The 2011 Awards will feature a prize fund of $24,000 with several new categories introduced and the vote of the public becoming more influential. This year all CMS projects will compete in an even tighter contest in the Open Source CMS Award category with the now defunct Hall of Fame CMS finalists re-entered into the CMS category. Projects such as Drupal and Joomla! will face off with CMS Made Simple and MODx for the first time since 2008.&lt;/p&gt;

&lt;p&gt;While the Most Promising Open Source Project and the Open Source JavaScript Libraries categories will be back for a second year, Packt is introducing new categories for Open Source Business Applications, Open Source Multimedia Software and Open Source Mobile Toolkit and Libraries. These new categories will ensure that the Open Source Awards remain committed to providing the platform to recognise excellence within the community while supporting Open Source projects both new and old.&lt;/p&gt;

&lt;p&gt;“We’ve managed to continue to provide new levels of accessibility for Open Source projects, while encouraging a more competitive nature in the contest by increasing the public votes influence. Additionally, we thought it would be a great idea to reward more projects thus we’ve introduced sub-category awards across a number of the categories during the voting stage. We expect the Awards this year to be bigger and better.” said Julian Copes, organizer of this year’s Awards.
Packt has opened up nominations for people to submit their favorite Open Source projects for each category at &lt;a href="http://www.PacktPub.com/open-source-awards-home"&gt;www.PacktPub.com/open-source-awards-home&lt;/a&gt; . The top five in each category will go through to the final, which begins mid-September. For more information on the categories, read Packt’s recent announcement: &lt;a href="http://www.packtpub.com/blog/2011-open-source-awards-announcement"&gt;www.packtpub.com/blog/2011-open-source-awards-announcement&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;About Packt&lt;/h3&gt;

&lt;p&gt;Packt is a modern, unique publishing company with a focus on producing cutting-edge books for communities of developers, administrators, and newbies alike.&lt;/p&gt;

&lt;p&gt;Packt’s books and publications share the experiences of fellow IT professionals in adapting and customizing today&amp;#8217;s systems, applications, and frameworks. Their solutions-based books give readers the knowledge and power to customize the software and technologies they’re using to get the job done.&lt;/p&gt;

&lt;p&gt;For more information, please visit &lt;a href="http://www.packtpub.com/"&gt;&lt;a href="http://www.PacktPub.com"&gt;www.PacktPub.com&lt;/a&gt;&lt;/a&gt;&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/9919341396</link><guid>http://www.brankovukelic.com/post/9919341396</guid><pubDate>Wed, 07 Sep 2011 17:29:00 +0200</pubDate><category>open-source</category><category>packt</category><category>awards</category></item><item><title>Show Me Your Email!</title><description>&lt;p&gt;If you sign up for a social networking account, you can understand that the terms of service contain stuff like &amp;#8220;you give us permission to publicly display your information for the purpose of providing you the service&amp;#8221;. How would you feel if your email provider had the same in their TOS?&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;I was thinking about email today. I use email for everything and anything. My social networking goes on in my inbox. Work goes without saying. Personal stuff, too. I don&amp;#8217;t use Facebook, nor Google+, and I only use Twitter to publish stuff from my blogs.&lt;/p&gt;

&lt;p&gt;Now, I&amp;#8217;ve always considered email the most private service on Internet. If there was one service on which my privacy would be absolutely protected it would be email, so I thought. But I guess it doesn&amp;#8217;t hold true anymore. Here&amp;#8217;s an excerpt from the TOS from an email provider I&amp;#8217;m currently using (replaced company name with &amp;#8216;ACME&amp;#8217;):&lt;/p&gt;

&lt;p&gt;&amp;#8220;We respect your right to ownership of content created or stored by you. You own the content created or stored by you. Unless specifically permitted by you, your use of the Services does not grant ACME the license to use, reproduce, adapt, modify, publish or distribute the content created by you or stored in your user account for ACME’s commercial, marketing or any similar purpose. But you grant ACME permission to access, copy, distribute, store, transmit, reformat, publicly display and publicly perform the content of your user account solely as required for the purpose of providing the Services to you.&amp;#8221;&lt;/p&gt;

&lt;p&gt;So, the ACME service respect my ownership of the content, but they do get to &amp;#8216;publicly display&amp;#8217;&amp;#8230; my email&amp;#8230; I&amp;#8217;m sure they didn&amp;#8217;t mean it to come out that way, but it did, didn&amp;#8217;t it? I don&amp;#8217;t know if it makes sense at all. If I post on Facebook, I can understand that it is meant to be publicly displayed to a fairly large chunk of the public. And I understand that I need to give Facebook permission to do so. But what about email? It is decidedly &lt;em&gt;not&lt;/em&gt; meant to be public. In fact, I use it specifically so that it doesn&amp;#8217;t go public. Otherwise, I&amp;#8217;d just tell everyone to watch my blog and post personal messages here, right? So I definitely don&amp;#8217;t understand why &amp;#8220;publicly display&amp;#8221; has to appear in email (and office) SaaS provider&amp;#8217;s TOS.&lt;/p&gt;

&lt;p&gt;IANAL, but I checked the Y! Mail&amp;#8217;s TOS and no such clause appears there, so it&amp;#8217;s generally speaking (from IANAL perspective) &amp;#8216;safer&amp;#8217; to use for email than the service I&amp;#8217;m using right now. You only give Yahoo! permission to publicly display stuff that you upload to &amp;#8216;publicly accessible areas&amp;#8217; which makes a lot of sense. Google has something similar in their TOS, but they aren&amp;#8217;t as clear as Yahoo!. The FAQ says this: &amp;#8220;We do require that you give us a licence to the content you post so that we can host it and, if you ask us to, make it available to others.&amp;#8221; So, with &lt;em&gt;my&lt;/em&gt; permission, they can post it publicly, but not without it.&lt;/p&gt;

&lt;p&gt;As far as services accessing our email&amp;#8217;s content, I believe Google does that to facilitate context-sensitive ads in Gmail. There&amp;#8217;s also a service called &lt;a href="http://www.gmx.com/"&gt;GMX Mail&lt;/a&gt; that outright reads its users&amp;#8217; email (supposedly to facilitate their security). Such practice is not only undesirable, but should be alarming to most webmail users (I stopped using Gmail a while ago, and was kicked out of GMX because they believed that one of my messages, which they obviously read, violated their TOS.)&lt;/p&gt;

&lt;p&gt;It would be very difficult to check each and every TOS out there to find a reliable email provider that would really care about the privacy of my email. However, it would be good to keep in mind that email isn&amp;#8217;t as sacred as it used to be (if it ever were). Apart for self-hosting email, there is no telling what might happen to your messages. You might see them leaked publicly one day, and find yourself in a situation where you cannot even sue the company that leaked them because &lt;em&gt;you&lt;/em&gt; gave them the permission to begin with&amp;#8230;&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/9912608070</link><guid>http://www.brankovukelic.com/post/9912608070</guid><pubDate>Wed, 07 Sep 2011 10:41:59 +0200</pubDate><category>email</category><category>privacy</category></item><item><title>New Node.js Book from Packt</title><description>&lt;p&gt;&lt;a href="http://www.packtpub.com/node-javascript-web-development/book"&gt;&lt;img src="http://media.tumblr.com/tumblr_lqjg7miYhl1qa7r0v.png" alt="Node Web Development by David Herron (Packt)"/&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Node.js is the new cool thing on the web, and everybody seems to be talking about it these days. And when everyone starts talking about something you start seeing books on the subject. Some time ago, I&amp;#8217;ve caught &lt;a href="http://groups.google.com/group/nodejs/msg/243d966620e1898a"&gt;David&amp;#8217;s anouncement&lt;/a&gt; of the book he was writing, and was wondering about when it will be available, when Packt contacted me asking for a review of David&amp;#8217;s &lt;a href="http://www.packtpub.com/node-javascript-web-development/book"&gt;Node web development&lt;/a&gt;, which has just been released (August 2011).&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;Now, you could say I&amp;#8217;m a bit biased when it comes to Packt. They&amp;#8217;ve published a &lt;a href="https://www.packtpub.com/python-3-object-oriented-programming/book"&gt;great book on Python 3&lt;/a&gt; by my friend and mentor, Dusty Phillips, and I also consider them a friend of open-source, which automatically promotes them to the friend-of-mine status. David himself is also a veteran developer (currently at Yahoo!), so I must say I have really high hopes for David&amp;#8217;s book. We&amp;#8217;ll see if it lives up to the standards that my previous contact with Packt books (and books from other publishers like Apress and O&amp;#8217;Reilly) have set for me.&lt;/p&gt;

&lt;p&gt;For now, I can only tell you that it&amp;#8217;s a book for people starting with Node.js, and that it&amp;#8217;s 172 pages. Cover&amp;#8217;s also nice, as usual. (That plant represents a single-threaded JavaScript VM?) Expect a more thorough review in a week or two, but for now, here&amp;#8217;s the &lt;a href="http://www.packtpub.com/sites/default/files/5146OS-Chapter-3-Node-Modules.pdf?utm_source=packtpub&amp;amp;utm_medium=free&amp;amp;utm_campaign=pdf"&gt;free chapter&lt;/a&gt; to give you some idea of what the book is like.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/9414644644</link><guid>http://www.brankovukelic.com/post/9414644644</guid><pubDate>Fri, 26 Aug 2011 16:13:00 +0200</pubDate><category>books</category><category>nodejs</category><category>javascript</category><category>packt</category></item><item><title>Bullet-proofing Setters and Getters</title><description>&lt;p&gt;JavaScript has two very handy methods that you can use on an object:
&lt;code&gt;__defineSetter__()&lt;/code&gt;, and &lt;code&gt;__defineGetter__()&lt;/code&gt;. They allow you to write
accessor functions for your objects. Here, I&amp;#8217;ll show you how to write them so
they are as tamper-free as possible.&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;I needed a bullet-proof pattern for accessors for my
&lt;a href="http://herdhound.github.com/Daimyo"&gt;Daimyo&lt;/a&gt; library that I use to hook &lt;a href="http://www.herdhound.com/"&gt;Herd
Hound&lt;/a&gt; to &lt;a href="http://www.feefighters.com/samurai"&gt;Samurai payment
gateway&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now, before I begin, it should be noted that method that I&amp;#8217;ll be showing you
here actually covers only simple types (&lt;code&gt;String&lt;/code&gt;, &lt;code&gt;Number&lt;/code&gt;, &lt;code&gt;RegExp&lt;/code&gt;, and
&lt;code&gt;Date&lt;/code&gt;). Composite types like &lt;code&gt;Object&lt;/code&gt; or &lt;code&gt;Array&lt;/code&gt; require a different
approach, which I will only briefly mention, with a link to useful code that
can get you there.&lt;/p&gt;

&lt;p&gt;So, let&amp;#8217;s get started. First the normal way to do accessors:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Constructor() {
    var self = this;

    self.__defineSetter__('prop', function(val) {
        self._prop = val;
    });

    self.__defineGetter__('prop', function() {
        return self._prop;
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;These are simply setting and returning a different property that will hold the
real value. Obviously, you&amp;#8217;d do more complex stuff to the incoming or outgoing
value, which is the point of accessors.&lt;/p&gt;

&lt;p&gt;Let me demonstrate one teeny-weeny problem with this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var myObj = new Constructor();

myObj.prop = 'foo';
console.log(myObj.prop); // =&amp;gt; 'foo'
console.log(myObj._prop); // =&amp;gt; 'foo'
myObj.prop = 'bar';
myObj._prop = 'foo';
console.log(myObj.prop); // =&amp;gt; 'foo'
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So obviously, our &lt;code&gt;_prop&lt;/code&gt; property is exposed, and anyone can play with it.
It&amp;#8217;s all cool as long as you are dealing with a well-behaved developer who will
respect the API and never touch stuff that starts with an underscore (except,
obviously, the &lt;code&gt;__defineGetter__()&lt;/code&gt;, and &lt;code&gt;__defineSetter__()&lt;/code&gt;). But what
if, in a very unlikely but still remotely possible scenario, malicious attacker
(or just some kid armed with too much free time and super-human curiosity)
manages to compromise the app that uses this API? In that case, it is quite
possible that the app is tricked into setting the &lt;code&gt;_prop&lt;/code&gt; instead of
&lt;code&gt;prop&lt;/code&gt;, and circumventing any carefully written validation logic in our
setter function.&lt;/p&gt;

&lt;p&gt;Naturally, our instinct tells us (or is it paranoia?) that we should tuck away
the &lt;code&gt;_prop&lt;/code&gt; property somewhere where nobody can play with it (not even the
kids). A good solution for this is to use closures.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function Constructor() {
    var self = this;

    (function(self) {
        var propVal;

        self.__defineSetter__('prop', function(val) {
            propVal = val;
        });

        self.__defineGetter__('prop', function() {
            return propVal;
        });

    }(self));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Before you go &amp;#8216;WTF&amp;#8217; on me, I&amp;#8217;ll explain what happened. So, first thing first:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(function(args) {

}(args));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This pattern is called immediate function invocation. What we do is, we define
a normal function, and then call it immediately. Note that the function we&amp;#8217;ve
defined has a closing curly bracket, followed immediately by a set of round
brackets with arguments in them (last line of the last snippet). This tells it
to immediately call itself with the specified arguments, which are passed to it
(surprised?). The whole thing is then wrapped in round brackets to signify that
it&amp;#8217;s an expression that has to be evaluated on the spot.&lt;/p&gt;

&lt;p&gt;One cool thing about this is that this function is sealed from the rest of the
world. What&amp;#8217;s uncool about it is that it&amp;#8217;s sealed from the rest of the world.
You can take that any way you want. What it means is that it cannot access
variables defined outside (like &lt;code&gt;self&lt;/code&gt; in our example), so you have to pass
them to it.&lt;/p&gt;

&lt;p&gt;Closure pattern is this one:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(function(args) {

    var someVar;

    return function() {
       // We can access someVar from here, but nobody else can!
    };

}(args));
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The outer function (the immediate function expression) closes over the one
defined inside it. Note that, as long as we have one function closing over the
other, we don&amp;#8217;t actually have to use the immediate function expression, but in
this case it came quite handy, because we needed a one-off function that won&amp;#8217;t
be used again.&lt;/p&gt;

&lt;p&gt;Now, the cool thing about closures is that they are so awesome. Seriously.
Anything defined in the outer function is accessible to the inner function even
after the outer function is done. The inner function can then be called at some
later stage in execution, while still maintaining the knowledge of the stuff
that was defined outside it.&lt;/p&gt;

&lt;p&gt;So, in our accessor example, we define the variable that will store the
property&amp;#8217;s value in the closing function, and the inner functions (accessor
functions) will use this variable to set and return the value of the property.
The variable is visible only to accessors, and nobody can tamper with them (not
even the kids).&lt;/p&gt;

&lt;p&gt;There&amp;#8217;s one exception to the above tamper-free claim. If the values are
objects, then they can still be tampered with, because, &lt;a href="http://www.brankovukelic.com/post/8820225542/passing-by-value-vs-passing-by-reference-in-javascript"&gt;as we&amp;#8217;ve seen
before&lt;/a&gt;,
objects are passed by reference, not by value. This allows anyone to manipulate
the properties of the value stored in the closure after it&amp;#8217;s returned by the
getter function. To avoid this, you need to return a cloned object. Code to do
that is available &lt;a href="https://gist.github.com/825253"&gt;in a Gist by Brian White&lt;/a&gt;,
so I won&amp;#8217;t go into details of how it works. As an aside, if it&amp;#8217;s a simple
object whose properties only contain non-object values, you can do this in your
getter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var clone = {};
Object.keys(valueInTheClosure).forEach(function(key) {
    clone[key] = valueInTheClosure[key];
});
return clone;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;#8217;s called shallow copying.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/9046993975</link><guid>http://www.brankovukelic.com/post/9046993975</guid><pubDate>Wed, 17 Aug 2011 21:27:00 +0200</pubDate><category>programming</category><category>javascript</category></item><item><title>Classic Web Form POST in AJAX apps</title><description>&lt;p&gt;So, you have an AJAX app that has to do a normal POST (not an AJAX post) using a regular web forms for whatever reason? While the solution outline here is not complete (it does &lt;em&gt;not&lt;/em&gt; cover doing cross-domain requests), here&amp;#8217;s a simple pattern I used to make &lt;a href="http://herdhound.github.com/Daimyo/example/ashigaru/"&gt;Ashigaru jQuery plugin&lt;/a&gt; work with the &lt;a href="http://feefighters.ca/samurai"&gt;Samurai payment gateway&lt;/a&gt;.&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;The problem I was facing was that Herd Hound is a single-page web application. You basically load a single page, and any change on that page is done using JavaScript. All requests to the backend are made via XHR (commonly known as AJAX), and the frontend can only talk to the backend (i.e., it has to talk to the same place from which the JavaScript was loaded). This restriction is known as &lt;a href="http://en.wikipedia.org/wiki/Same_origin_policy"&gt;same origin policy&lt;/a&gt;, and it&amp;#8217;s been giving pain to anyone wanting to do a mashup.&lt;/p&gt;

&lt;p&gt;The same origin policy lead to invention of various techniques to get data from other sites to the AJAX app, including some fancy stuff I&amp;#8217;ve only heard about in the newer versions of major browsers. One classic technique is JSONP. This technique has a major drawback in that it cannot be used for sensitive data. Because JSONP requests &lt;em&gt;must&lt;/em&gt; be GET requests, any parameters that you want to send must be sent as URL parameters which are &lt;em&gt;not&lt;/em&gt; encrypted even over SSL. Another solution was to POST a web form to a hidden iframe using the &lt;code&gt;target&lt;/code&gt; attribute.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;target&lt;/code&gt; attribute used to be deprecated in HTML 4.01, but in HTML 5, it is no longer deprecated, so you can safely use it knowing that it will be supported for quite some time. What this attribute does is it tells the browser to open the results of the form action in a different target, and not in the current page. The target can be an &lt;code&gt;iframe&lt;/code&gt;, so if you have a hidden &lt;code&gt;iframe&lt;/code&gt; on your page, the page will not be reloaded, and the user will never know what was loaded in the iframe.&lt;/p&gt;

&lt;p&gt;This behavior is what I expoloited for writing Ashigaru.&lt;/p&gt;

&lt;p&gt;Basically, you have a form, or you create one using JavaScript, and you add a &lt;code&gt;target&lt;/code&gt; attribute that has the same value as the &lt;code&gt;name&lt;/code&gt; attribute on the &lt;code&gt;iframe&lt;/code&gt;. You also make sure the &lt;code&gt;iframe&lt;/code&gt; is hidden. Ashigaru creates a form which has all &lt;code&gt;input&lt;/code&gt; elements of type &lt;code&gt;hidden&lt;/code&gt; so the form itself is also hiddent. It then takes an object with data that you want to POST, and it populates the form. You can either do that, for a generic solution, or you can use the existing form, and let it submit to the &lt;code&gt;iframe&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Once you submit the form to the &lt;code&gt;iframe&lt;/code&gt;, you can use the &lt;code&gt;load&lt;/code&gt; event on the &lt;code&gt;iframe&lt;/code&gt; to read the data from it once it&amp;#8217;s loaded.&lt;/p&gt;

&lt;p&gt;Before you attempt to use this technique, here&amp;#8217;s a few tips.&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;It doesn&amp;#8217;t matter what the &lt;code&gt;action&lt;/code&gt; URL is as long as what ends up in the &lt;code&gt;iframe&lt;/code&gt; is coming from your server. Otherwise you cannot access it.&lt;/li&gt;
&lt;li&gt;You can access data in the &lt;code&gt;iframe&lt;/code&gt;, but &lt;code&gt;iframe&lt;/code&gt; can also access data on the page, so beware of script injection attacks! Make sure there are no embedded malicious scripts.&lt;/li&gt;
&lt;li&gt;You cannot prevent scripts in the &lt;code&gt;iframe&lt;/code&gt; from executing.&lt;/li&gt;
&lt;li&gt;If you want to do cross-site requests, you can make a CNAME subdomain that points to that site, and then manipulate &lt;code&gt;window.document.domain&lt;/code&gt; on both the current page &lt;em&gt;and&lt;/em&gt; the &lt;code&gt;iframe&lt;/code&gt;, and strip out the subdomain parts so the browser thinks it&amp;#8217;s the same domain.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Here&amp;#8217;s the main function of the Ashigaru:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$.ashigaru = function(data, merchantKey, redirectURI, callback) {
  var form;

  var fullData = {
     // ... defaults
  };

  $.extend(fullData, data);

  var formHTML = '...';

  // Replace non-data field placeholders and form attribute placeholders
  formHTML = formHTML.replace('$requestURI', samuraiURI);
  // ....
  // Replace placeholders in form HTML with real data
  for (var key in fullData) {
    if (fullData.hasOwnProperty(key)) {
      formHTML = formHTML.replace('$' + key, fullData[key]);
    }
  }

  // Inject this into DOM
  form = $(formHTML);

  // Attach the form to body
  form.appendTo('body');

  // Submit the form
  form.unbind('submit');
  form.submit(function(e) {
    e.stopPropagation();
    return createIframe(callback);
  });

  form.submit();
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I&amp;#8217;ve stripped out a fair bit of error-handling and other little pieces that are not relevant to this post. A few things to note is &lt;code&gt;e.stopPropagation()&lt;/code&gt;, adding &lt;code&gt;iframe&lt;/code&gt; creation routine into form submit action (so the iframe is created on the fly when the form is submitted), and &lt;code&gt;form.submit()&lt;/code&gt; call, which forces form submission (form is not submitted manually by the user).&lt;/p&gt;

&lt;p&gt;To be honest, I saw &lt;code&gt;e.stopPropagation()&lt;/code&gt; used somewhere in a similar context, and I left it there because it works. I&amp;#8217;m slightly ashamed to say that I haven&amp;#8217;t tested the code without it. In theory, it will prevent the submit event from being handled by any handlers that are trying to do event delegation. Only the submit action on &lt;em&gt;this particular form&lt;/em&gt; will be handled. So I guess that&amp;#8217;s why we have it there. This should be a completely isolated form, created for the purpose of making this method of POSTing work, so we don&amp;#8217;t want anyone else on the page reacting to the event.&lt;/p&gt;

&lt;p&gt;Another thing I did was first make sure &lt;code&gt;submit&lt;/code&gt; event is not handled by anything other than my code. For the same reason as &lt;code&gt;e.stopPropagation()&lt;/code&gt;, obviously.&lt;/p&gt;

&lt;p&gt;Here&amp;#8217;s the &lt;code&gt;createIframe&lt;/code&gt; method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function createIframe(callback) {
  var iFrame = $('&amp;lt;iframe src="" name="samurai-iframe" '+
                 'style="display:none"&amp;gt;' +
                 '&amp;lt;/iframe&amp;gt;');
  // Attach iframe to &amp;lt;body&amp;gt;
  iFrame.appendTo('body');
  // Do the right thing when iframe loads
  iFrame.load(function() {
    onResultLoad(this, callback);
    removeForm();
  });
  return true;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Fairly simple. It creates the HTML for the &lt;code&gt;iframe&lt;/code&gt;, attaches it to &lt;code&gt;body&lt;/code&gt;, and adds the &lt;code&gt;load&lt;/code&gt; event handler whic extracts the data from the &lt;code&gt;iframe&lt;/code&gt; and deletes the form. I&amp;#8217;m not going to show you the code that removes the form. It&amp;#8217;s not relevant. You can check out the &lt;a href="https://github.com/HerdHound/Daimyo/blob/master/support/ashigaru.js"&gt;Ashigaru source&lt;/a&gt; if you want to know more.&lt;/p&gt;

&lt;p&gt;There&amp;#8217;s one thing to note here, and that&amp;#8217;s the fact that we &lt;code&gt;return true&lt;/code&gt; as the last thing in the &lt;code&gt;createIframe&lt;/code&gt; method. Remember that we said &lt;code&gt;return createIframe(callback)&lt;/code&gt; in the form&amp;#8217;s &lt;code&gt;submit&lt;/code&gt; handler? Well, this is the thing. If you return false in a handler, the event will be prevented from happening, and the form will not submit. I haven&amp;#8217;t written the code yet, but I will do basic sanity check: see if the iframe was created successfully, and return false if it wasn&amp;#8217;t (so that the form is not submitted).&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ll just show you one last snippet, and that&amp;#8217;s the &lt;code&gt;onResultLoad&lt;/code&gt; handler:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function onResultLoad(iFrame, callback) {
  var resultDocument = $(iFrame).contents();
  var jsonData;

  // Remove the form
  removeForm();

  // The result document should contain JSON data in a &amp;lt;script&amp;gt; tag
  jsonData = $.trim(resultDocument.find('body script').text());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To get the DOM tree of &lt;code&gt;iframe&lt;/code&gt; contents, you can use the &lt;code&gt;contents()&lt;/code&gt; method. It will return a &lt;code&gt;jQuery&lt;/code&gt; object that you can use to access the DOM inside the &lt;code&gt;iframe&lt;/code&gt;. Note that this only works if the &lt;code&gt;iframe&lt;/code&gt; satisifes the requirements of the same-origin policy. The reason this method works for Ashigaru is that Samurai redirects the user back to a page on &lt;em&gt;my&lt;/em&gt; server, so the final result of making the POST request always satisfies the same-origin policy.&lt;/p&gt;

&lt;p&gt;One you have access to the &lt;code&gt;iframe&lt;/code&gt;&amp;#8217;s DOM, it&amp;#8217;s a matter of doing your usual &lt;code&gt;$(..)&lt;/code&gt; to get whatever you want from it.&lt;/p&gt;

&lt;p&gt;Specifically in Ashigaru, I have a single &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag that contains JSON data enclosed in round brackets:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;script&amp;gt;({"status": "ok"})&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The round brackets are there to prevent the browser from thowing &lt;code&gt;SyntaxError&lt;/code&gt; exceptions because the object literal is required to be inside brackets.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/8878686327</link><guid>http://www.brankovukelic.com/post/8878686327</guid><pubDate>Sat, 13 Aug 2011 23:21:00 +0200</pubDate><category>ajax</category><category>jquery</category><category>Ashigaru</category><category>Samurai</category><category>xss</category></item><item><title>The Best Git UI for Vim: Fugitive</title><description>&lt;p&gt;Tim Pope, known to many Vim (and Rails) users as just &lt;a href="https://github.com/tpope"&gt;tpope&lt;/a&gt;, very well known for his many &lt;code&gt;vim-&lt;/code&gt; projects (including the infamous &lt;a href="https://github.com/tpope/vim-pathogen"&gt;pathogen&lt;/a&gt; plugin), has this to say about his &lt;a href="https://github.com/tpope/vim-fugitive"&gt;Fugitive&lt;/a&gt; plugin for Vim:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;I&amp;#8217;m not going to lie to you; fugitive.vim may very well be the best Git wrapper of all time. Check out these features: [&amp;#8230;]&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;And he didn&amp;#8217;t lie. Fugitive is so awesome it may well be &lt;em&gt;the&lt;/em&gt; reason for you to switch to Vim right fucking now. But of course, you are already using Vim, aren&amp;#8217;t you? Oh and if you&amp;#8217;re not using Git, you absolutely suck. :P&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;So, I&amp;#8217;m not going to go all in-dept. Instead, I&amp;#8217;ll point to you &lt;a href="http://vimcasts.org/"&gt;vimcasts.org&lt;/a&gt;, where &lt;a href="http://drewneil.com/"&gt;Drew&lt;/a&gt; is showing you how to use it in his typically thorough, and awesome style.&lt;/p&gt;

&lt;p&gt;What makes Fugitive really great is the fact that it actually does &lt;em&gt;more&lt;/em&gt; for you than what you&amp;#8217;d get using just Git.&lt;/p&gt;

&lt;p&gt;One of the awesome features that I enjoy using is the vimdiff view of unstaged changes. (I started using vimdiff because of Fugitive, too.) What Fugitive does is it gives you a side-by-side of changes that are staged, and the working version of your file. Not only can you clearly see what&amp;#8217;s changed since last &lt;code&gt;git commit&lt;/code&gt; (or &lt;code&gt;git add&lt;/code&gt;), you can also hand-pick changes you want to move into the staged version. Of course, just being able to preview the changes is quite awesome on its own.&lt;/p&gt;

&lt;p&gt;Another cool thing is it makes the &lt;code&gt;git-status&lt;/code&gt; output interacitve. So you can go to a file mentioned in &lt;code&gt;git-status&lt;/code&gt; output inside a Vim buffer, and you can press &lt;code&gt;-&lt;/code&gt; to stage or unstage it. And then you can just press &lt;code&gt;S-C&lt;/code&gt; (Shift + C) to commit the staged changes.&lt;/p&gt;

&lt;p&gt;Merge conflicsts have also been my pain point. It&amp;#8217;s quite easy to loose track of those markers, isn&amp;#8217;t it? Well, with Fugitive, you get a three-way vimdiff, with target on the left, and source on the right, and the conflict in the middle. You can pick and merge parts of the source or target just like when you want to stage small chunks of changes.&lt;/p&gt;

&lt;p&gt;Ok, so those are my three favorites, but Fugitive actually packs a whole lot more, so I encourage you to give it a spin.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/8876955950</link><guid>http://www.brankovukelic.com/post/8876955950</guid><pubDate>Sat, 13 Aug 2011 22:31:48 +0200</pubDate><category>scm</category><category>git</category><category>figutive</category><category>vim</category><category>software</category></item><item><title>Passing by Value vs Passing by Reference in JavaScript</title><description>&lt;p&gt;A thing that I&amp;#8217;ve heard desktop application developers say about web developers is that web developers don&amp;#8217;t know what phrases &lt;em&gt;passing by value&lt;/em&gt; and &lt;em&gt;passing by reference&lt;/em&gt; mean. I&amp;#8217;m sure most of us, web developers, know what those mean. If you don&amp;#8217;t, you should learn them ASAP!&lt;/p&gt;

&lt;p&gt;To recap, &lt;em&gt;passing by value&lt;/em&gt; means that the value that you pass to a function gets cloned and independent, and that changes to that value made within the function are not reflected on the original value. On the other hand, &lt;em&gt;passing by reference&lt;/em&gt; means that the object passed to a function is linked to the one that is passed, so the original is affected by any changes that happen in the function.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve done some testing to see when the values are passed by value, and when they are passed by reference in JavaScript, and here&amp;#8217;s what I&amp;#8217;ve found out.&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;&lt;strong&gt;tl;dr&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Literal values are always passed by value. Object properties are always passed by reference (including array members, because arrays in JavaScripts are objects with numerical properties).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Now the long version.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Suppose we have a few values assigned to a bunch of variables.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var int = 1;
var str = 'a';
var obj = {
    int: 1,
    str: 'a'
};
var arr = [1,2,3,4];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, suppose that we have a function like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function passme(passed) {
    passed = 'foo';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What this does is change the value of the incoming argument &lt;code&gt;passed&lt;/code&gt; to &lt;code&gt;'foo'&lt;/code&gt;. If we run &lt;code&gt;int&lt;/code&gt; through this, interesting thing happens:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;passme(int);
alert(int);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The value of &lt;code&gt;int&lt;/code&gt; before and after calling passme is still &lt;code&gt;1&lt;/code&gt;, and it will not change to &lt;code&gt;'foo'&lt;/code&gt;. The exact same thing applies to all other variables, inclluding &lt;code&gt;obj&lt;/code&gt;, and &lt;code&gt;arr&lt;/code&gt;. They are all passed in by value.&lt;/p&gt;

&lt;p&gt;So how do we get the new value assigned to the variable? We have to return it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function passme(passed) {
    passme = 'foo'
    return passme;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And then, we can assign the return value:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;int = passme(int); // int is now === 'foo'
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What would you expect to happen if we did this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var obj1 = {
    a: 'foo',
    b: 'bar'
};
var obj2 = {};

function cloneAndAddC(o) {
    o.c = 'baz';
    return o;
}

obj2 = cloneAndAddC(obj1);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Honestly, I expected &lt;code&gt;obj2&lt;/code&gt; to have proerty &lt;code&gt;c&lt;/code&gt;, and &lt;code&gt;obj1&lt;/code&gt; to not have it. But what happens in reality is that both have property &lt;code&gt;c&lt;/code&gt;. (You can see a &lt;a href="http://jsfiddle.net/foxbunny/WgdG7/"&gt;demo of failed object cloning in JSFiddle&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;To explain it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[obj1][.property]
  |            \------------&amp;gt; by reference
  |
  \------&amp;gt; by value
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So while the actual object is passed by value (if you assign something else to it, you won&amp;#8217;t kill the original), but the properties of the object are passed in by reference (if you modify a property, original property is modified). I hope that makes sense.&lt;/p&gt;

&lt;p&gt;So, what if an object&amp;#8217;s property is an object? I bet you can&amp;#8217;t guess unless you&amp;#8217;ve done tried this before! So check this out:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var obj1 = {
   a: 'foo'
};
var obj2 = {
   a: obj1
};

function modme(o) {
    o.a.a = 'bar'; // supposedly this is obj1.a
    o.a = 'bar'; // o.a should be obj2.a, meaning it's obj1
}

modme(obj2);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So what most of us though this would do is: 1. change &lt;code&gt;obj1.a&lt;/code&gt; to &lt;code&gt;'bar'&lt;/code&gt;, and then change &lt;code&gt;obj1&lt;/code&gt; itself to &lt;code&gt;'bar'&lt;/code&gt;. In fact, something else happens which is also very logical (and I seriously envy anyone who got this without peeking or knowing in advance): &lt;code&gt;obj1.a&lt;/code&gt; is &lt;code&gt;'bar'```, but instead of&lt;/code&gt;obj1&lt;code&gt;itself turning into&lt;/code&gt;&amp;#8216;bar&amp;#8217;&lt;code&gt;with the second statement,&lt;/code&gt;obj2.a&lt;code&gt;becomes&lt;/code&gt;&amp;#8216;bar&amp;#8217;&lt;code&gt;, and&lt;/code&gt;obj1&amp;#8220; is left intact. (There is a &lt;a href="http://jsfiddle.net/foxbunny/c2h72/"&gt;demo for this on JSFiddle&lt;/a&gt;, too.)&lt;/p&gt;

&lt;p&gt;So now, let&amp;#8217;s go back to our &lt;code&gt;cloneAndAddC&lt;/code&gt; example for a second. How do we make that one work? Before you can do that, you first need to add a bit of boilerplate code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// For browsers that don't support ECMA5
if (!Object.keys) {
    Object.keys = function(obj) {
        var keys = [];
        for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                keys.push(key);
            }
        }
        return keys;
    };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With the above snippets, all non-ECMA5-compliant browsers will get the &lt;code&gt;Object.keys&lt;/code&gt; function which can be used like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var obj1 = {a: 1, b:2};
Object.keys(obj1); // =&amp;gt; ['a', 'b']
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Up next, another piece of boilerplate:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(callback, thisObject) {
        for (var i = this.length, l = this.length; i; --i) {
            if (!thisObject) {
                callback(this[l - i]);
            } else {
                callback.apply(thisObject, [this[l-i]]);
            }
        }
    };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So, you now have access to &lt;code&gt;forEach&lt;/code&gt;, which loops thrhough array members and executes a &lt;code&gt;callback&lt;/code&gt; function on each element.&lt;/p&gt;

&lt;p&gt;Finally, we can define our clone function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function clone(obj) {
    var clone = {};
    Object.keys(obj).forEach(function(key) {
        clone[key] = obj[key];
    });
    return clone;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The above does shallow copying. You could do some type detection and do recursive cloning. In fact, that&amp;#8217;s just a few more lines at most, but I&amp;#8217;ll leave that to you.&lt;/p&gt;

&lt;p&gt;Now, we can make our clone thingy work:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var obj1 = {
    a: 'foo',
    b: 'bar'
};
var obj2 = {};

function cloneAndAddC(o) {
    var cloned = clone(o);
    cloned.c = 'baz';
    return cloned;
}

obj2 = cloneAndAddC(obj1);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now wasn&amp;#8217;t that fun? You can &lt;a href="http://jsfiddle.net/foxbunny/eETRn/"&gt;see it in action on JSFiddle&lt;/a&gt;. Happy hacking!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UPDATE:&lt;/strong&gt; You don&amp;#8217;t &lt;em&gt;really&lt;/em&gt; have to write the boilerplate code. There&amp;#8217;s this cool little thingy called &lt;a href="https://github.com/kriskowal/es5-shim"&gt;es5-shim&lt;/a&gt; (ECMAScript 5 shim) by &lt;a href="https://github.com/kriskowal"&gt;Kris Kowal&lt;/a&gt;. Just plug it in, and you&amp;#8217;re ready to rock. You can see the &lt;a href="http://jsfiddle.net/foxbunny/eETRn/1/"&gt;last example using this shim&lt;/a&gt; on JSFiddle.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/8820225542</link><guid>http://www.brankovukelic.com/post/8820225542</guid><pubDate>Fri, 12 Aug 2011 14:52:00 +0200</pubDate><category>javascript</category><category>value vs reference</category><category>programming</category><category>ECMA5</category></item><item><title>Profilejs: V8 profiling for Express framework</title><description>&lt;p&gt;I&amp;#8217;ve started using Danny Coates&amp;#8217; &lt;a href="https://github.com/dannycoates/node-inspector"&gt;node-inspector&lt;/a&gt; recently. It works very well as a graphical debugger (runs in a webkit browser), and it can also serve as a profiler in conjunction with &lt;a href="https://github.com/dannycoates/v8-profiler"&gt;v8-profiler&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I wanted a tool that would profile all requests for me, so I could browse and pick through the logs afterwards, but I couldn&amp;#8217;t find one. So I decided to write a middleware for &lt;a href="http://expressjs.com/"&gt;Express&lt;/a&gt; that would pipe all requests throug the v8-profiler. The result is &lt;a href="https://github.com/HerdHound/profilejs"&gt;Profilejs&lt;/a&gt;.&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;Currently at version 0.0.2, Profilejs is still immature and probably buggy, and most certainly underfeatured. But the good news is, it&amp;#8217;s not meant to replace node-inspector, and it works very well with it (for now).&lt;/p&gt;

&lt;p&gt;I won&amp;#8217;t detail installation and usage here, as it&amp;#8217;s documented on the &lt;a href="https://github.com/HerdHound/profilejs/blob/master/README.md"&gt;Github page&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Installation is fairly simple:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;npm install profilejs
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It will pull in v8-profiler as dependency, though, so be aware of that.&lt;/p&gt;

&lt;p&gt;Typical usage involves setting up the middleware, and starting the profiler:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var profilejs = require('profilejs');
app.use(profilejs.profiler);
profilejs.start();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can start either in silent mode or without the silent mode. The difference is you get a lot less noise in standard output in silent mode. Default is to run in extremely loud mode.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_lp9wywDE1u1qa7r0v.png" alt="Profilejs console output"/&gt;&lt;/p&gt;

&lt;p&gt;Each request results in a single profile. However, profiles are all named by the request URL that resulted in a call to the profiled handler. If the same URL gets hit multiple times, it will add runs to the profile with the same name. So you&amp;#8217;ll have 5 runs for the url &amp;#8216;/foo&amp;#8217; if you make 5 requests to &amp;#8216;/foo&amp;#8217;. In node-inspector UI, you will see a single profile named &amp;#8216;/foo&amp;#8217;, and five subitems under it which show different data from each run.&lt;/p&gt;

&lt;p&gt;Once your app is hooked up, you can sart it with the debug option:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;node --debug app.js
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Preferably, you will make a separate environment for your profiling needs, and run the app in that environment:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NODE_ENV=profiling node --debug app.js
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once your app is running, you can start the node-inspector:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;node-inspector --profile
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;--profile&lt;/code&gt; option enables profiling. Now, you can open your WebKit browser (I use Chromium), and direct it to &lt;a href="http://0.0.0.0:8080/"&gt;0.0.0.0:8080&lt;/a&gt;. Once there, you need to go over into the &lt;em&gt;Profiles&lt;/em&gt; tab and enable them.&lt;/p&gt;

&lt;p&gt;With profiles enabled, you can click the refresh icon in the bottom left corner, and your profiles will be loaded. There won&amp;#8217;t be any profiles until you actually inteact with the application, though.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_lp9xatAGYP1qa7r0v.png" alt="node-inspector running in Chromium on Arch Linux"/&gt;&lt;/p&gt;

&lt;p&gt;I hope this tool is useful to you. If you have any issues with this library, you can &lt;a href="https://github.com/HerdHound/profilejs/issues"&gt;file a bug&lt;/a&gt;, or drop by the &lt;a href="http://groups.google.com/group/nodejs"&gt;nodejs mailing list&lt;/a&gt;.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/8360829222</link><guid>http://www.brankovukelic.com/post/8360829222</guid><pubDate>Tue, 02 Aug 2011 02:01:04 +0200</pubDate><category>nodejs</category><category>V8</category><category>profiling</category><category>performance</category></item><item><title>Iframe ad killer</title><description>&lt;p&gt;Most ads I&amp;#8217;ve seen are inside an iframe. That makes them very easy to target and murder with a bit of JavaScript. Here&amp;#8217;s a small bookmarklet that will do just that:&lt;/p&gt;

&lt;p&gt;&lt;a href="javascript:(function()%7Bt=document.getElementsByTagName(" iframe&gt;iframe killer&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Drag that bookmarklet (link) to your bookmarks toolbar, and click it whenever you see too many flash or image banners on the page.&lt;/p&gt;

&lt;p&gt;Mind you, this also kills legitimate iframes, so it&amp;#8217;s not 100% clean. It will also miss any ads that are not inside iframes.&lt;/p&gt;

&lt;p&gt;This bookmarklet is provided to you on works-for-me basis, no guarantees, and no warranties. ;)&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;How it works is very simple. It fetches a list of all iframes in a document:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;t = document.getElementsByTagName('iframe');
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then it loops through them (in reverse for speed), and clears the &lt;code&gt;src&lt;/code&gt; attribute:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;for(i = t.length;i;--i) {
  t[i-1].src='';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(Keep in mind that removing the iframes breaks the page layout, which is not what we want. Clearing the &lt;code&gt;src&lt;/code&gt; attribute is enough.)&lt;/p&gt;

&lt;p&gt;The code is then wrapped in a closure so that it doesn&amp;#8217;t leak stuff (if it returns anything other than undefined, even by accident, the browser will try to go to the &amp;#8216;URL&amp;#8217; defined by that something).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(function() {
  t = document.getElementsByTagName('iframe');
  for(i = t.length;i;--i) {
    t[i-1].src='';
  }
}());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, to make a bookmarklet of this, just strip all spaces, and prepend &lt;code&gt;javascript:&lt;/code&gt; (see the bookmarklet link at the beginning of the article).&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/8238886979</link><guid>http://www.brankovukelic.com/post/8238886979</guid><pubDate>Sat, 30 Jul 2011 03:41:00 +0200</pubDate><category>javascript</category><category>web development</category></item><item><title>The Cost of User Input Sanitizing</title><description>&lt;p&gt;You might have heard of &amp;#8216;user input validation&amp;#8217;. That&amp;#8217;s all cool and dandy, but have you heard of &amp;#8216;user input sanitizing&amp;#8217;? It is a concept as important as validation. The former checks for validity of the user input, and the latter prepares the user input for further processing by the software.&lt;/p&gt;

&lt;p&gt;Now, you might think that proper validation might mostly eliminate the need for sanitizing. But that&amp;#8217;s the wrong mindset. In the age of UX, software is expected to fit human needs, and not other way around, so sanitizing input becomes even more important than just validating it. It&amp;#8217;s not only done for security reasons, but also to make users&amp;#8217; lives easier, too.&lt;/p&gt;

&lt;p&gt;Here I&amp;#8217;ll illustrate on a real-life example, why this is so important, and why it costs a lot if you do not care.&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;I use &lt;a href="http://www.moneygram.com/"&gt;Moneygram&lt;/a&gt; from time to time to receive money from friends and relatives.&lt;/p&gt;

&lt;p&gt;As with all money-related services, Moneygram uses software to manage the transactions. And software is operated by clerks. Now, clerks aren&amp;#8217;t exactly the brightest folks on the planet when it comes to working with software systems. They may or may not have read manuals, but they tend to make mistakes. And if the UX of the softwar is not top-notch, this can lead to unpleasant delays and mistakes that cost people time and money.&lt;/p&gt;

&lt;p&gt;Recently, I went to pick up some cash. I was asked to fill in a form that was otherwise printed out by the Moneygram software, because the clerk could not figure out error in data input. 15 minutes after I&amp;#8217;ve filled in the form, the clerk managed to get ahold of support staff and it turned out the error was software getting stuck on dashses entered into phone number field. It also has to be noted that the phone number is an optional field. I sometimes get asked for my phone number, and sometimes not. It should also be noted that clerk was not able to explain the problem to the support staff. The only reason they figured it out is that clerk spelled out the contents of each field to the support person.&lt;/p&gt;

&lt;p&gt;It all boils down to user input sanitizing. In most programming languages it takes one line of code to remove any non-digit characters (including spaces) from the form. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Python
&amp;gt;&amp;gt;&amp;gt; phone_number = '123-456-7890' 
&amp;gt;&amp;gt;&amp;gt; phone_number = re.sub('[^\d]+', '', phone_number) # this line
'1234567890'

#JavaScript
&amp;gt; phoneNumber = '123-456-7890'
&amp;gt; phoneNumber = phoneNumber.replace(/[^\d]+/g, '') # this line
'1234567890'
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Similar examples may include trimming input. I&amp;#8217;ve seen it too many times where leading and/or trailing space triggering all sorts of problems for the end user. Make it a habit to strip leading/trailing spaces.&lt;/p&gt;

&lt;p&gt;There are more common pitfalls, but they are outside this article&amp;#8217;s scope.&lt;/p&gt;

&lt;p&gt;It&amp;#8217;s unbelievable that the Moneygram software fails to do proper sanitizing. The above one-liners take 5 seconds to write with decent typing skills in &lt;em&gt;any&lt;/em&gt; language. And it saves customers anywhere from a minute (if clerk has seen it before but is confused again) to 15 minutes (if it happens for the first time and clerk needs to call support without any clue as to what the problem is) each time a clerk gets stuck on this. Moneygram is a world-wide service, so you can imagine how much time is lost on this single mistake word-wide every day.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/8211227510</link><guid>http://www.brankovukelic.com/post/8211227510</guid><pubDate>Fri, 29 Jul 2011 12:59:56 +0200</pubDate><category>ux</category><category>software design</category></item><item><title>Blocking vs Non-blocking: Node vs Bottle</title><description>&lt;p&gt;Node.js boasts real-time performance. Of course, depending on hardware, it may
show some level od delay in responses, but it is usually able to handle
requests as soon as they come in. I have built two simple hello world apps, one
running on top of Node.js, and one running on top of Bottle/Bjoern. Bjoern is a
non-blocking WSGI server written in C, and it should perform very well on its
own, but Python is blocking, so we want to see how it stacks up against a
pureluy non-blocking app written on Node.js.&lt;/p&gt;

&lt;!-- more --&gt;

&lt;h3&gt;Concept&lt;/h3&gt;

&lt;p&gt;We will use two applications, one written on Node.js, one written on
Bottle/Bjoern stack. Both applications will return a &amp;#8216;Hello World&amp;#8217; after a 1
second delay.&lt;/p&gt;

&lt;p&gt;If everything works fine, the apps should be able to serve an arbitrary number
of parallel requests in about one second total.&lt;/p&gt;

&lt;h3&gt;Bottle/Bjoern&lt;/h3&gt;

&lt;p&gt;Up first, Bottle/Bjoern. Bottle is version 0.9.6 (stable), and Bjoern is
version 1.2.0 (stable). The stack runs on top of Python 2.7.2. The code looks
like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;from bottle import run, route
from time import sleep

@route('/')
def hello():
    sleep(1)
    return 'Hello world'

if __name__ == '__main__':
    run(server='bjoern')
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Node.js&lt;/h3&gt;

&lt;p&gt;I won&amp;#8217;t introduce you to Node itself this time. You can read one of my previous
posts for that. Node is currently version 0.4.10. The test application looks 
like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var http = require('http');
http.createServer(function (req, res) {
    setInterval(function() {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Hello World\n');
    }, 1000);
}).listen(3000, "127.0.0.1");
console.log('Server running at &lt;a href="http://127.0.0.1:3000/'"&gt;http://127.0.0.1:3000/'&lt;/a&gt;);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Before jumping to conclusion about syntax, and other aesthetical issues, you
should be aware that Bottle is a web framework, whereas Node is a networked
application framework. They have different priorities and this reflects itself
in the API style used for our example code.&lt;/p&gt;

&lt;h3&gt;Testing tool&lt;/h3&gt;

&lt;p&gt;For this test, we are using &lt;code&gt;ab&lt;/code&gt; utility. If you don&amp;#8217;t have one on your
system, it&amp;#8217;s part of apache package. On some distros, it may be part of some
apache-related package, I&amp;#8217;m not sure. On Arch Linux, you should just install
&lt;code&gt;apache&lt;/code&gt; package, and you&amp;#8217;ll have the tool.&lt;/p&gt;

&lt;h3&gt;Let&amp;#8217;s get the show on the road&lt;/h3&gt;

&lt;p&gt;First, let&amp;#8217;s start Bottle/Bjoern combo. I&amp;#8217;ve put the test app inside a
virtualenv.&lt;/p&gt;

&lt;p&gt;So, we start the server and app with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(bottlehello) $ python helloworld.py
Bottle server starting up (using BjoernServer())...
Listening on &lt;a href="http://127.0.0.1:8080/"&gt;http://127.0.0.1:8080/&lt;/a&gt;
Use Ctrl-C to quit.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We will test with 10, 1000, and 1000 concurrent requests launched all at once.
If X is the number of requests, the command is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ab -c X -n X &lt;a href="http://127.0.0.1:8080/"&gt;http://127.0.0.1:8080/&lt;/a&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;At X=10, Bottle/Bjoern show appaling performance (average ms / request):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;10019.282 [ms] (mean)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;At X=100, Bottle/Bjoern fails, so we didn&amp;#8217;t even attempt X=1000.&lt;/p&gt;

&lt;p&gt;Let&amp;#8217;s move on to Node.js.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ node helloworld.js
Server running at &lt;a href="http://127.0.0.1:3000/"&gt;http://127.0.0.1:3000/&lt;/a&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Using the same &lt;code&gt;ab&lt;/code&gt; command as before but with port 3000, we get the
following results for X=10, X=100, X=1000 respectively:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;1011.443 [ms] (mean)
1029.896 [ms] (mean)
2148.086 [ms] (mean)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, at 1000 requests, it took 2 seconds for Node.js to handle the
requests on average, but it did not fail. (It also ran at 1.5s/req on some
earlier trials.)&lt;/p&gt;

&lt;h3&gt;Bottle/Cherrypy&lt;/h3&gt;

&lt;p&gt;To do Bottle some justice, we&amp;#8217;ll try the test again using Cherrypy server. We
will modify the &lt;code&gt;run()&lt;/code&gt; line like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;run(server='cherrypy')
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And install Cherripy, obviously. Unlike single-threaded bjoern, Cherrypy is
multithreaded, so it should be able to take advantage of all 8 cores on my
developer machine.&lt;/p&gt;

&lt;p&gt;And the test results for X=10, X=100, and X=1000 look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;1325.132 [ms] (mean)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&amp;#8230;well, it fails at 51 requests.&lt;/p&gt;

&lt;h3&gt;Bottle/Tornado&lt;/h3&gt;

&lt;p&gt;Just to be on the safe side, I&amp;#8217;ve also tested with Tornado, and got similar
results as in Bjoern&amp;#8217;s case: 10s request time with 10 concurrent requests, and
failed attempts to test X=100 and X=1000.&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;A single blocking call like &lt;code&gt;time.sleep&lt;/code&gt; can make all the difference between
scalability and failure. Now, you might argue that it is possible to make the
above work with Bjoern/Python, and you are, indeed correct. If you replace the
blocking &lt;code&gt;time.sleep&lt;/code&gt; call with something non-blocking. This demo was meant
to demonstrate the power of non-blocking, though, and I think the demo is
successful at that.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/8123248120</link><guid>http://www.brankovukelic.com/post/8123248120</guid><pubDate>Wed, 27 Jul 2011 10:50:00 +0200</pubDate><category>nodejs</category><category>python</category><category>performance</category><category>scalability</category><category>non-blocking</category></item><item><title>Serial Expresso Testing with Mongo Fixtures</title><description>&lt;p&gt;&lt;a href="http://tjholowaychuk.com/post/656851606/expresso-tdd-framework-for-nodejs"&gt;Expresso&lt;/a&gt; is a test runner for &lt;a href="http://nodejs.org/"&gt;Node.js&lt;/a&gt;. It boasts &amp;#8220;high speed parallel testing&amp;#8221;. It means it can run your whole test suite of a couple of thousands of tests in less than a second&amp;#8230; but this post is not about that. This post is about taking it slow, and running tests one by one like you might be used to from other environments (Python, anyone?).&lt;/p&gt;

&lt;!-- more --&gt;

&lt;h3&gt;Isn&amp;#8217;t slow&amp;#8230; err&amp;#8230; bad?&lt;/h3&gt;

&lt;p&gt;So, why use a &lt;em&gt;high-speed parallelized test runner&lt;/em&gt; to run tests slowly and serially? There are some cases where this might be useful.&lt;/p&gt;

&lt;p&gt;In particular, serial testing is very useful when running tests with database operations where you have no transaction support. In such a case, database operation in one test (for example, removal of a record) migth conflict with operation in another test (for example, fetching of a record that should have been removed). Database operations take time, and on a non-blocking platform such as Node.js, this leads all sorts of problems if you cannot allow operations to end before next ones are executed.&lt;/p&gt;

&lt;p&gt;Regardless of how much you value speed, sometimes hasty means wrong test results. For the past 4 or 5 days, I&amp;#8217;ve battled the non-blocking nature of Node.js to get a good work flow for testing database-related operations in an app that I&amp;#8217;m writing, and here I&amp;#8217;ll recap my final solution.&lt;/p&gt;

&lt;h3&gt;The basic setup&lt;/h3&gt;

&lt;p&gt;Here&amp;#8217;s a basic setup for the test module.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var mongoose = require('mongoose'),
    db = mongoose.connect('mongodb://localhost/mymodeltest'),
    fixture = require('../helpers/fixture'),
    MySchema = require('../../models/mymode).MySchema,
    Model,
    test = exports;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let&amp;#8217;s assume that tests are all located in &lt;code&gt;appdir/tests/unit&lt;/code&gt;. This test will be located in &lt;code&gt;appdir/tests/unit/mymodel.tests.js&lt;/code&gt;. I&amp;#8217;ll also use &lt;a href="http://mongoosejs.com/"&gt;Mongoose ORM&lt;/a&gt; for this test. If you don&amp;#8217;t use Mongoose, you will find the fixture module uninteresting, but it still might give you an idea about how to make your own setup.&lt;/p&gt;

&lt;p&gt;For the moment, ignore the &lt;code&gt;var&lt;/code&gt; statements above. You can look at it later as we progress to see what comes from where. Just note that we have aliased &lt;code&gt;exports&lt;/code&gt; as &lt;code&gt;test&lt;/code&gt; to make the module look a bit nicer, but that&amp;#8217;s completely optional.&lt;/p&gt;

&lt;p&gt;Also note that we are using a seaparate database for this unit test. I generally opt to use separate database for each unit, and only use a project-wide database for integration testing. This allows me to run multiple unit test modules at once in parallel (even though individual tests in each module are run serially), which speeds things up a little.&lt;/p&gt;

&lt;p&gt;First thing first:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Model = db.model('Model', MySchema);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This sets up the model to use the connection. Next, you need to add a few test fixtures. I usually specify fixtures as an array of objects. The objects are formulated in a way that will make a whole document if passed to the model constructor. In our example, if I pass such object as &lt;code&gt;new Model(testData[0])&lt;/code&gt;, it should be ready to save without any further intervention. So we specify the fixtures like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;testData = [
  { ... },
  { ... },
  { ... }
];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is the minimal setup that will get us started.&lt;/p&gt;

&lt;h3&gt;&lt;code&gt;fixture&lt;/code&gt; module&lt;/h3&gt;

&lt;p&gt;You can get the code for the fixture module &lt;a href="https://gist.github.com/1107335"&gt;from a gist&lt;/a&gt;. (I give you permission to use, modify, copy, and redistribute, yada yada&amp;#8230; IOW, I won&amp;#8217;t sue.) It&amp;#8217;s a single method which cleans up the database, loads the fixtures specified as an array (as discussed in previous section), and allows you to specify a callback that will be executed once all fixtures are loaded.&lt;/p&gt;

&lt;p&gt;Your callback may accept data, and another callback (I usually call it &lt;code&gt;next&lt;/code&gt; like in middlewares). Data is a collection of document objects that were inserted into the database. The &lt;code&gt;next&lt;/code&gt; callback cleans up the database once your tests are run, if you choose to call it when you&amp;#8217;re done testing. The &lt;code&gt;next&lt;/code&gt; callback will also take a callback that&amp;#8230; is it too confusing? Ok, let&amp;#8217;s just put down basics and move on.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fixture.load(Model, testData, function(data, next) {
  // Your tests go here
});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Oh, and the load path for this was &lt;code&gt;../helpers/fixture&lt;/code&gt;, because I keep the test helpers in &lt;code&gt;appdir/tests/helpers&lt;/code&gt; directory. You should adjust the path according to your situation.&lt;/p&gt;

&lt;h3&gt;Using &lt;code&gt;exports['test name'] = function() {...}&lt;/code&gt; format&lt;/h3&gt;

&lt;p&gt;As you know, Expresso allows you to specify tests in one of two ways. One way is to specify all your tests in an object literal:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;module.exports = {
  'test1': function() {...},
  'test2': function() {...},
  'test3': function() {...}
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But&amp;#8230; you cannot use this in this scenario. You have to use the other format:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;exports['test1'] = function() {...};
exports['test2'] = function() {...};
exports['test3'] = function() {...};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you rememeber we have aliased &lt;code&gt;exports&lt;/code&gt; as &lt;code&gt;test&lt;/code&gt;, so you can do this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;test['test1'] = function() {...};
test['test2'] = function() {...};
test['test3'] = function() {...};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you use the latter method, you can specify tests withing a callback of an asynchronous operation (such as inserting fixtures, right?), and that&amp;#8217;s exactly what we&amp;#8217;re aiming for.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fixture.load(Model, testData, function(data, next) {
  test['test1'] = function() {...};
  test['test2'] = function() {...};
  test['test3'] = function() {...};
});
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Using the before-exit hook&lt;/h3&gt;

&lt;p&gt;All test functions accept a before-exit callback that you can use to tell Expresso when your test is done. Do use them do this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;test['my asynchronous test'] = function(exit) {
  Model.find(function(err, docs) {
    // test data
    exit(); // Calls exit to signify that test is done.
  });
};
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Tearing down&lt;/h3&gt;

&lt;p&gt;Finally, after all your tests are run, it&amp;#8217;s time to destroy the test data and disconnect from the database. Disconnecting from the database allows Expresso to terminate correctly instead of you having to terminate it manually with Ctrl+C.&lt;/p&gt;

&lt;p&gt;Tear-down is done by adding one more test to the end of your test module that will call the &lt;code&gt;next&lt;/code&gt; callback from &lt;code&gt;fixture.load&lt;/code&gt; call, and disconnect the database. I usually call this last test simply &lt;code&gt;end&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;fixture.load(Model, testData, function(data, next) {
  test['test1'] = function() {...};
  test['test2'] = function() {...};
  test['test3'] = function() {...};
  // ... more tests, and finally:

  test.end = function(exit) {
    next(function() { // ``next`` is from the ``fixture.load`` call
      db.disconnect(exit); // We let ``db.disconnect`` call exit
    });
  };

});
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As noted in the comments next to the code, &lt;code&gt;db.disconnect&lt;/code&gt; call takes a callback which is called when the connection to database is closed. We conveniently pass the before-exit callback to it. This is done within a call to next. The callback function we passed to &lt;code&gt;next&lt;/code&gt; will be executed once all test fixtures are removed from the database.&lt;/p&gt;

&lt;h3&gt;Running the tests&lt;/h3&gt;

&lt;p&gt;To run the tests serially, you can use the &lt;code&gt;-s&lt;/code&gt; switch:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;expresso -s tests/unit/*.tests.js
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Aaand&amp;#8230; that&amp;#8217;s it. Happy serial killing&amp;#8230; err&amp;#8230; I mean testing.&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/8092747680</link><guid>http://www.brankovukelic.com/post/8092747680</guid><pubDate>Tue, 26 Jul 2011 20:07:54 +0200</pubDate><category>nodejs</category><category>expresso</category><category>testing</category><category>fixtures</category><category>mongoose</category><category>database</category></item><item><title>Mouse and Vim for the Lazy</title><description>&lt;p&gt;Have you ever noticed that, when you have line numbers enabled in Vim, you can&amp;#8217;t select just the code? You know, the numbers get selected as well. I was too lazy to fix that problem for a while now, and today I took a stab at it finally. Solution was deceivingly simple.&lt;/p&gt;

&lt;!-- more --&gt;

&lt;p&gt;One method mentioned involved adding mouse button bindings to &lt;code&gt;vimrc&lt;/code&gt;, and then adding more options to &lt;code&gt;Xdefaults&lt;/code&gt;, but I wanted none of that. So I found another solution:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;gvim -v
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Yup. Gvim. Invoking Gvim with the &lt;code&gt;-v&lt;/code&gt; switch makes it behave and look just like normal Vim, but with the awesome mouse support. Now you can scroll, select, copy, paste, and move separators with mouse, and still enjoy the text-version look and feel. How awesome is that! (^_^)&lt;/p&gt;</description><link>http://www.brankovukelic.com/post/7983117309</link><guid>http://www.brankovukelic.com/post/7983117309</guid><pubDate>Sat, 23 Jul 2011 23:17:22 +0200</pubDate><category>vim</category><category>tips</category></item></channel></rss>

