<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Small.JS</title>
  <link href="http://smalljs.org/feed.xml" rel="self"/>
  <link href="http://smalljs.org"/>
  <updated>2014-05-01T03:25:52.840Z</updated>
  <id>http://smalljs.org</id>
  
  <entry>
    <title>Debug</title>
    <author>Toby Ho</author>
    <link href="http://smalljs.org/logging/debug/"/>
    <updated>2014-04-30T00:00:00.000Z</updated>
    <id>http://smalljs.org/logging/debug/</id>
    <content>
      &lt;p&gt;&lt;a href=&quot;https://github.com/visionmedia/debug&quot;&gt;Debug&lt;/a&gt; is a small library for logging debug messages. Since it is just a wrapper around &lt;code&gt;console.log&lt;/code&gt;, it works in both Node and the Browser. It allows you to filter logging output without changing your source and it also outputs time differences which lets you easily tell how much time has elapsed between log messages.&lt;/p&gt;
&lt;h2 id=&quot;log-the-things&quot;&gt;Log The Things&lt;/h2&gt;
&lt;p&gt;To log messages using debug, first create a logger:&lt;/p&gt;
var Debug = require(&amp;#39;debug&amp;#39;);
var debug = Debug(&amp;#39;main&amp;#39;);&lt;p&gt;&lt;code&gt;require(&amp;#39;debug&amp;#39;)&lt;/code&gt; gets you the debug module - which is a function, I will call that capitalized &lt;code&gt;Debug&lt;/code&gt;. Calling &lt;code&gt;Debug&lt;/code&gt; with a name gives you a logger - which is also a function - we will call that lowercase &lt;code&gt;debug&lt;/code&gt;. Now you can use it to log messages:&lt;/p&gt;
debug(&amp;#39;Hello, world!&amp;#39;);
setTimeout(
debug(&amp;#39;Hello again!&amp;#39;);&lt;h2 id=&quot;seeing-the-logs&quot;&gt;Seeing The Logs&lt;/h2&gt;
&lt;p&gt;If you save the above example as &lt;code&gt;run.js&lt;/code&gt; and run it with Node:&lt;/p&gt;
$ node run.js&lt;p&gt;Nothing happens. &lt;em&gt;Don&amp;#39;t panic!&lt;/em&gt; It&amp;#39;s just that debug hides messages by default. You need to configure the logger to output messages from the logger(s) you want to see. For now we&amp;#39;ll set visibility to &lt;em&gt;everything&lt;/em&gt; by setting the &lt;code&gt;DEBUG&lt;/code&gt; environment variable to &lt;code&gt;*&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;terminal.png&quot; alt=&quot;Terminal Output&quot;&gt;&lt;/p&gt;
&lt;p&gt;Sweet! Notice that the output contains the logger name, the message, and the time difference between the current and previous log messages. Oh, and nice colored text output too.&lt;/p&gt;
&lt;p&gt;In the browser, configuration is done via the &lt;code&gt;Debug.enable()&lt;/code&gt; method, like so:&lt;/p&gt;
Debug.enable(&amp;#39;*&amp;#39;);&lt;p&gt;&lt;img src=&quot;browser.png&quot; alt=&quot;Browser Output&quot;&gt;&lt;/p&gt;
&lt;p&gt;The configuration setting is persisted across browser refreshes via localStorage, which is convinient for debugging.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;&amp;lt;side-note&amp;gt;&lt;/code&gt; Okay, this may be one of the very few times where something looks better in the terminal than it does it the browser. &lt;em&gt;What?!!&lt;/em&gt; Though I was told that on some browsers at least, you can now style console.log output - &lt;a href=&quot;https://github.com/visionmedia/debug&quot;&gt;pull request&lt;/a&gt; anyone? &lt;code&gt;&amp;lt;/side-note&amp;gt;&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Now lets look at different ways you can filter the log messages.&lt;/p&gt;
&lt;h2 id=&quot;filtering-the-logs&quot;&gt;Filtering The Logs&lt;/h2&gt;
&lt;p&gt;The wildcard &lt;code&gt;*&lt;/code&gt; is what to do if you want to see all the log messages going through debug, but debug is more useful when you want to filter down debug messages to specific modules you are having trouble with. So let&amp;#39;s say you have a calculator module that looks like this (&lt;code&gt;calculator.js&lt;/code&gt;):&lt;/p&gt;
module.exports = {
  add: function(one, other){
    return one + other;
  }
}&lt;p&gt;With the debug module, we can instrument it with debug statements like this:&lt;/p&gt;
var debug = require(&amp;#39;debug&amp;#39;)(&amp;#39;calculator&amp;#39;);

module.exports = {
  add: function(one, other){
    debug(&amp;#39;Adding numbers:&amp;#39;, one, other);
    var result = one + other;
    debug(&amp;#39;Result:&amp;#39;, result);
    return result;
  }
}&lt;p&gt;Then you have a &lt;code&gt;main.js&lt;/code&gt; script that uses &lt;code&gt;calculator.js&lt;/code&gt;:&lt;/p&gt;
var debug = require(&amp;#39;debug&amp;#39;)(&amp;#39;main&amp;#39;);
var calc = require(&amp;#39;./calculator&amp;#39;);

var num1 = prompt(&amp;#39;First number&amp;#39;);
var num2 = prompt(&amp;#39;Second number&amp;#39;);
var result = calc.add(num1, num2)
debug(&amp;#39;result:&amp;#39;, result);
alert(&amp;#39;Result is &amp;#39; + result);&lt;p&gt;We have a bug somewhere. Let say that we suspect the problem to be in &lt;code&gt;calculator.js&lt;/code&gt;, we can just turn on debug logging for it in the JS console:&lt;/p&gt;
&amp;gt; Debug.enable(&amp;#39;calculator&amp;#39;)&lt;p&gt;Now rerun the code and you shall see the log messages for &lt;code&gt;calculator.js&lt;/code&gt;. &lt;/p&gt;
&lt;p&gt;To see output for more than just one module, i.e. both &lt;code&gt;main.js&lt;/code&gt; and &lt;code&gt;calculator.js&lt;/code&gt;, use a comma to separate them:&lt;/p&gt;
&amp;gt; Debug.enable(&amp;#39;calculator,main&amp;#39;)&lt;p&gt;Debugging this code is left as an exercise for the reader ;)&lt;/p&gt;
&lt;h2 id=&quot;wildcards&quot;&gt;Wildcards&lt;/h2&gt;
&lt;p&gt;You can use the wildcard &lt;code&gt;*&lt;/code&gt; to pattern match module names - this is useful for modules that have submodules. For example, maybe your calculator module got complicated and you split the code into &lt;code&gt;calculator/add.js&lt;/code&gt; and &lt;code&gt;calculator/multiply.js&lt;/code&gt;. As a simple convention, both files can use the same prefix for their logger names:&lt;/p&gt;
// in calculator/add.js
var debug = require(&amp;#39;debug&amp;#39;)(&amp;#39;calculator:add&amp;#39;);

// in calculator/multiply.js
var debug = require(&amp;#39;debug&amp;#39;)(&amp;#39;calculator:multiply&amp;#39;);&lt;p&gt;Now, if you want to see only messages for &lt;code&gt;add.js&lt;/code&gt;, you can specify the specific logger as&lt;/p&gt;
&amp;gt; Debug.enable(&amp;#39;calculator:add&amp;#39;)&lt;p&gt;But, if you want to see the messages for either submodule, you can simply configure it using a wildcard&lt;/p&gt;
&amp;gt; Debug.enable(&amp;#39;calculator:*&amp;#39;)&lt;h2 id=&quot;bye-&quot;&gt;Bye!&lt;/h2&gt;
&lt;p&gt;To learn more about debug, check out the &lt;a href=&quot;https://github.com/visionmedia/debug&quot;&gt;readme&lt;/a&gt;, or just &lt;a href=&quot;https://github.com/visionmedia/debug/blob/master/debug.js&quot;&gt;read the source&lt;/a&gt;, cause seriously it&amp;#39;s tiny.&lt;/p&gt;

    </content>
  </entry>
  
  <entry>
    <title>Page</title>
    <author>Toby Ho</author>
    <link href="http://smalljs.org/client-side-routing/page/"/>
    <updated>2014-04-17T00:00:00.000Z</updated>
    <id>http://smalljs.org/client-side-routing/page/</id>
    <content>
      &lt;p&gt;&lt;a href=&quot;https://github.com/visionmedia/page.js&quot;&gt;Page&lt;/a&gt; is a small client-side routing library for use with building single page applications (SPAs). It has a simple API which is inspired by &lt;a href=&quot;http://expressjs.com/&quot;&gt;Express&lt;/a&gt;. It utilizes the &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history&quot;&gt;HTML5 history API&lt;/a&gt; under the hood, which is what allows you to build smooth user interfaces while still having linkable URLs for different pages of the app.&lt;/p&gt;
&lt;h2 id=&quot;routing&quot;&gt;Routing&lt;/h2&gt;
&lt;p&gt;Page supplies you a &lt;code&gt;page&lt;/code&gt; function which has a few different roles:&lt;/p&gt;
var page = require(&amp;#39;page&amp;#39;);&lt;p&gt;The first of those roles is specifying routes. If you&amp;#39;ve use Ruby on Rails or Express or a similar framework, this should look familiar:&lt;/p&gt;
page(&amp;#39;/&amp;#39;, function(){
  // Do something to set up the index page
});

page(&amp;#39;/about&amp;#39;, function(){
  // Set up the about page
});&lt;p&gt;Your routes can contain parameters, which you can assess through the &lt;code&gt;context&lt;/code&gt; parameter to your route handler&lt;/p&gt;
page(&amp;#39;/user/:id&amp;#39;, function(context){
  var userId = context.params.id;
  console.log(&amp;#39;Loading details for user&amp;#39;, userId);
});&lt;p&gt;You can use wildcards as parameters too, in which case you will need to use array indexing to access the parameters:&lt;/p&gt;
page(&amp;#39;/files/*&amp;#39;, function(context){
  var filePath = context.params[0];
  console.log(&amp;#39;Loading file&amp;#39;, filePath);
});&lt;p&gt;A key difference between using a wildcard vs a named parameter is that a wildcard can match the character &amp;quot;/&amp;quot;, while a named parameter cannot. In our file path example, using a wildcard allows &lt;code&gt;filePath&lt;/code&gt; to contain arbitrarily nested subdirectories. &lt;/p&gt;
&lt;p&gt;Another useful thing you can do with a wildcard is to define a fallback route:&lt;/p&gt;
page(&amp;#39;*&amp;#39;, function(){
  console.error(&amp;#39;Page not found :(&amp;#39;);
});&lt;h2 id=&quot;starting-the-router&quot;&gt;Starting The Router&lt;/h2&gt;
&lt;p&gt;Once you have all your routes defined, you need to start the router, which is done with another call to &lt;code&gt;page&lt;/code&gt;, but this time with no parameters:&lt;/p&gt;
page();&lt;p&gt;If you are weirded out by this, and prefer to be more explicit, you can instead write the equivalent:&lt;/p&gt;
page.start();&lt;p&gt;Both of these can take an optional &lt;code&gt;options&lt;/code&gt; object, containing the properties:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;click&lt;/code&gt; - whether to automatically bind to click events on the page and intercept link clicks and handle them using page&amp;#39;s router - defaults to true.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;popstate&lt;/code&gt; - whether to bind to and utilize the &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/API/Window.onpopstate&quot;&gt;popstate event&lt;/a&gt; - defaults to true.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;dispatch&lt;/code&gt; - whether to perform initial route dispatch based on the current url - defaults to true.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;programmatic-navigation&quot;&gt;Programmatic Navigation&lt;/h2&gt;
&lt;p&gt;As mentioned above, page will by default automatically intercept clicks on links on the page and try to handle it using the routes you&amp;#39;ve setup. Only if it can&amp;#39;t match the url with any of the define routes will it default back to the browser&amp;#39;s default behavior. Sometimes though, you may want to change the URL based on other events. Maybe the element clicked happens to be something other than a link. Or, if you are building a search page, you may want to allow users to share the URL to their search results. You can do this by just calling &lt;code&gt;page&lt;/code&gt; function with the page you want to navigate to:&lt;/p&gt;
$(form).on(&amp;#39;submit&amp;#39;, function(e){
  e.preventDefault();
  page(&amp;#39;/search?&amp;#39; + form.serialize());
});&lt;p&gt;If you prefer to be more explicit, you can use &lt;code&gt;page.show(path)&lt;/code&gt; instead.&lt;/p&gt;
&lt;h2 id=&quot;route-handler-chaining&quot;&gt;Route Handler Chaining&lt;/h2&gt;
&lt;p&gt;A cool feature of page is that it allows for route handler chaining, which is similar to Express&amp;#39;s middlewares. A route definition can take more than one handler:&lt;/p&gt;
page(&amp;#39;user/:id&amp;#39;, loadUser, showUser);&lt;p&gt;Here, when the path &lt;code&gt;user/1&lt;/code&gt; is navigated, page will first call the &lt;code&gt;loadUser&lt;/code&gt; handler. When the user is done loading, it will call the &lt;code&gt;showUser&lt;/code&gt; handler to display it. &lt;em&gt;How does it know when the user is done loading?&lt;/em&gt; A callback is provided to the handlers as the second parameter - here is what &lt;code&gt;loadUser&lt;/code&gt; might look like:&lt;/p&gt;
function loadUser(ctx, next){
  var id = ctx.params.id;
  $.getJSON(&amp;#39;/user/&amp;#39; + id + &amp;#39;.json&amp;#39;, function(user){
    ctx.user = user;
    next();
  });
}&lt;p&gt;Then, in &lt;code&gt;showUser&lt;/code&gt; you can get at the user through &lt;code&gt;ctx.user&lt;/code&gt;. Now this is nice because you can reuse the &lt;code&gt;loadUser&lt;/code&gt; function for, say, the &lt;code&gt;user/:id/edit&lt;/code&gt; route.&lt;/p&gt;
&lt;h2 id=&quot;states&quot;&gt;States&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history&quot;&gt;History API&lt;/a&gt; supports saving states along with each history entry. This allows you to cache information along with previously navigated URLs, so that if the user navigates back to them via the back button, you don&amp;#39;t have to to re-fetch the information, making the UI much smoother. Page exposes this via the &lt;code&gt;state&lt;/code&gt; property of the &lt;a href=&quot;https://github.com/visionmedia/page.js#context&quot;&gt;context object&lt;/a&gt;. To make the above &lt;code&gt;loadUser&lt;/code&gt; function utilize this cache, you would write this:&lt;/p&gt;
function loadUser(ctx, next){
  if (ctx.state.user){
    next();
  }else{
    var id = ctx.params.id;
    $.getJSON(&amp;#39;/user/&amp;#39; + id + &amp;#39;.json&amp;#39;, function(user){
      ctx.state.user = user;
      ctx.save();  // saves the state via history.replaceState()
      next();
    });
  }
}&lt;h2 id=&quot;putting-it-all-together&quot;&gt;Putting It All Together&lt;/h2&gt;
&lt;p&gt;Now that you know what you need to know about page, let&amp;#39;s build an example application. The app will render a list of the earliest Github users. You can click on an individual user and get more details about him or her. The back button should work seamlessly and should use caching. This will use the modules &lt;a href=&quot;https://github.com/visionmedia/page.js&quot;&gt;page&lt;/a&gt;, &lt;a href=&quot;https://github.com/visionmedia/superagent&quot;&gt;superagent&lt;/a&gt;, and &lt;a href=&quot;https://github.com/janl/mustache.js&quot;&gt;mustache&lt;/a&gt;.&lt;/p&gt;
var page = require(&amp;#39;page&amp;#39;);
var request = require(&amp;#39;superagent&amp;#39;);
var mustache = require(&amp;#39;mustache&amp;#39;);&lt;p&gt;These are route definitions:&lt;/p&gt;
page(&amp;#39;/&amp;#39;, loadUsers, showUsers);
page(&amp;#39;/user/:id&amp;#39;, loadUser, showUser);&lt;p&gt;The implementation of &lt;code&gt;loadUsers&lt;/code&gt; and &lt;code&gt;loadUser&lt;/code&gt; look like this, much like the previous state-caching example:&lt;/p&gt;
function loadUsers(ctx, next){
  if (ctx.state.users){
    // cache hit!
    next();
  }else{
    // not cached by state, make the request
    request(&amp;#39;https://api.github.com/users&amp;#39;, function(reply){
      var users = reply.body;
      ctx.state.users = users;
      ctx.save();
      next();
    });
  }
}

function loadUser(ctx, next){
  if (ctx.state.user){
    next();
  }else{
    var id = ctx.params.id;
    request(&amp;#39;https://api.github.com/user/&amp;#39; + id, function(reply){
      var user = reply.body;
      ctx.state.user = user;
      ctx.save();
      next();
    });
  }
}&lt;p&gt;For rendering the pages, this will use mustache, and I&amp;#39;ve made the following templates:&lt;/p&gt;
var listTemplate = 
  &amp;#39;&amp;lt;h1&amp;gt;Early Github Users&amp;lt;/h1&amp;gt;\
  &amp;lt;ul&amp;gt;\
    {{#.}}\
    &amp;lt;li&amp;gt;\
      &amp;lt;a href=&amp;quot;/user/{{id}}&amp;quot;&amp;gt;{{login}}&amp;lt;/a&amp;gt;\
    &amp;lt;/li&amp;gt;\
    {{/.}}\
  &amp;lt;/ul&amp;gt;&amp;#39;;


var showTemplate = 
  &amp;#39;&amp;lt;h1&amp;gt;User {{login}}&amp;lt;/h1&amp;gt;\
  &amp;lt;p&amp;gt;{{name}} is user number {{id}}. \
  He has {{followers}} followers, \
  {{public_repos}} public repos and writes a blog at\
  &amp;lt;a href=&amp;quot;{{blog}}&amp;quot;&amp;gt;{{blog}}&amp;lt;/a&amp;gt;.\
  &amp;lt;a href=&amp;quot;/&amp;quot;&amp;gt;Back to list&amp;lt;/a&amp;gt;.&amp;lt;/p&amp;gt;\
  &amp;#39;;&lt;p&gt;There are ways to lift the markup into .html files, but I&amp;#39;ll save that for another day. To render these templates is job of &lt;code&gt;showUser&lt;/code&gt; and &lt;code&gt;showUsers&lt;/code&gt;:&lt;/p&gt;
function showUsers(ctx){
  var users = ctx.state.users;

  content.innerHTML = 
      mustache.render(listTemplate, users);
}

function showUser(ctx){
  var user = ctx.state.user;
  content.innerHTML = 
    mustache.render(showTemplate, user);
};&lt;p&gt;And finally, we need to start the router:&lt;/p&gt;
page.start();&lt;p&gt;And there you have it! A multi-page single page application. If you want to poke around with this code, take a look at the &lt;a href=&quot;https://github.com/airportyh/page_demo&quot;&gt;full source code&lt;/a&gt;, which has been modularized into small files.&lt;/p&gt;

    </content>
  </entry>
  
  <entry>
    <title>JSDiff</title>
    <author>Toby Ho</author>
    <link href="http://smalljs.org/string/jsdiff/"/>
    <updated>2014-04-10T00:00:00.000Z</updated>
    <id>http://smalljs.org/string/jsdiff/</id>
    <content>
      &lt;p&gt;&lt;a href=&quot;https://github.com/kpdecker/jsdiff&quot;&gt;JSDiff&lt;/a&gt; is an implementing of text comparison in Javascript, it is used in Mocha to implement &lt;a href=&quot;http://visionmedia.github.io/mocha/#string-diffs&quot;&gt;colored diffs&lt;/a&gt;, and it&amp;#39;s fairly easy to use.&lt;/p&gt;
&lt;p&gt;Let&amp;#39;s say you have two strings: &lt;code&gt;oldString&lt;/code&gt; and &lt;code&gt;newString&lt;/code&gt;&lt;/p&gt;
var oldString = &amp;#39;beep boop&amp;#39;;
var newString = &amp;#39;beep boob blah&amp;#39;;&lt;p&gt;To compare them you may use the &lt;code&gt;diffChars&lt;/code&gt; method&lt;/p&gt;
var diff = JsDiff.diffChars(oldString, newString);&lt;p&gt;This gives you &lt;code&gt;diff&lt;/code&gt; which is an array of change objects. A change object represents a section of text which is has either been added, removed, or neither. It has the following properties&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;value&lt;/code&gt;: text content&lt;/li&gt;
&lt;li&gt;&lt;code&gt;added&lt;/code&gt;: whether the value was inserted into the new string&lt;/li&gt;
&lt;li&gt;&lt;code&gt;remove&lt;/code&gt;: whether the value was removed from the old string&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In the above example, if you&amp;#39;d log the &lt;code&gt;diff&lt;/code&gt; object, you&amp;#39;d see&lt;/p&gt;
[ { value: &amp;#39;beep boo&amp;#39;, added: undefined, removed: undefined },
  { value: &amp;#39;b blah&amp;#39;, added: true, removed: undefined },
  { value: &amp;#39;p&amp;#39;, added: undefined, removed: true } ]&lt;p&gt;To render this information visually, we can color code these text chunks. In Node, there&amp;#39;s a module &lt;a href=&quot;https://github.com/Marak/colors.js&quot;&gt;colors&lt;/a&gt; which makes outputing colors to the terminal easy.&lt;/p&gt;
diff.forEach(function(part){
  // green for additions, red for deletions
  // grey for common parts
  var color = part.added ? &amp;#39;green&amp;#39; :
    part.removed ? &amp;#39;red&amp;#39; : &amp;#39;grey&amp;#39;;
  process.stderr.write(part.value[color]);
});&lt;p&gt;If you run this program (&lt;a href=&quot;https://github.com/airportyh/jsdiff/blob/docs/examples/node_example.js&quot;&gt;see full source code&lt;/a&gt;) you should see&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;node_example.png&quot;&gt;&lt;/p&gt;
&lt;p&gt;You can also use &lt;a href=&quot;https://github.com/kpdecker/jsdiff&quot;&gt;JSDiff&lt;/a&gt; on a web page by using browserify or just via &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag. To render the same diff using DOM elements - using the raw DOM API would look like&lt;/p&gt;
var display = document.createElement(&amp;#39;pre&amp;#39;);
diff.forEach(function(part){
  // green for additions, red for deletions
  // grey for common parts
  var color = part.added ? &amp;#39;green&amp;#39; :
    part.removed ? &amp;#39;red&amp;#39; : &amp;#39;grey&amp;#39;;
  var span = document.createElement(&amp;#39;span&amp;#39;);
  span.style.color = color;
  span.appendChild(document
    .createTextNode(part.value));
  display.appendChild(span);
});
document.body.appendChild(display);&lt;p&gt;The result of that code (&lt;a href=&quot;https://github.com/airportyh/jsdiff/blob/docs/examples/web_example.html&quot;&gt;full source&lt;/a&gt;, or &lt;a href=&quot;http://requirebin.com/?gist=7325660&quot;&gt;on requirebin&lt;/a&gt;) would look like&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;web_example.png&quot;&gt;&lt;/p&gt;
&lt;p&gt;But wait, there&amp;#39;s more. Take a look at JsDiff&amp;#39;s &lt;a href=&quot;https://github.com/kpdecker/jsdiff#api&quot;&gt;API&lt;/a&gt;, it can also&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;compare by word.&lt;/li&gt;
&lt;li&gt;compare by line.&lt;/li&gt;
&lt;li&gt;compare CSS.&lt;/li&gt;
&lt;li&gt;create patch files for use with the &lt;a href=&quot;http://en.wikipedia.org/wiki/Patch_\(Unix\&quot;&gt;patch&lt;/a&gt;) program.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;This article was originally posted at &lt;a href=&quot;http://tobyho.com/2013/11/05/jsdiff-for-comparing-text/&quot;&gt;http://tobyho.com/2013/11/05/jsdiff-for-comparing-text/&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

    </content>
  </entry>
  
  <entry>
    <title>Browserify</title>
    <author>Toby Ho</author>
    <link href="http://smalljs.org/package-managers/npm/browserify/"/>
    <updated>2014-04-02T00:00:00.000Z</updated>
    <id>http://smalljs.org/package-managers/npm/browserify/</id>
    <content>
      &lt;p&gt;&lt;a href=&quot;http://browserify.org/&quot;&gt;Browserify&lt;/a&gt; is a build tool that lets you use Node&amp;#39;s CommonJS module system for frontend JavaScript development. It integrates seamlessly with &lt;a href=&quot;/package-managers/npm&quot;&gt;npm&lt;/a&gt;, and you can use the same smooth npm workflow for installing and publish modules. For this reason, we&amp;#39;ve seen the rise of frontend JavaScript modules being published to npm. Browserify also opens up the possibility of code reuse between the server and the client - if you have a Node backend.&lt;/p&gt;
&lt;p&gt;To learn more about using npm itself and using it to write server-side Node programs, check out the &lt;a href=&quot;/package-managers/npm/&quot;&gt;npm article&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id=&quot;the-gist&quot;&gt;The Gist&lt;/h2&gt;
&lt;p&gt;Pretend you are writing a Node program. You are probably doing these things:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Install some modules: &lt;code&gt;npm install a_module&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Write some code: &lt;code&gt;vi myprogram.js&lt;/code&gt; (or substitute your favorite editor in place of vi).&lt;/li&gt;
&lt;li&gt;Test some code: &lt;code&gt;node myprogram.js&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;With Browserify, you still have these same steps, but you also add a build step, and testing your code involves opening up a browser:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Install some modules: &lt;code&gt;npm install a_module&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Write some code: &lt;code&gt;vi myprogram.js&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Build the bundle: &lt;code&gt;browserify myprogram.js -o bundle.js&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Test some code: &lt;code&gt;&amp;lt;script src=&amp;quot;bundle.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;And that&amp;#39;s Browserify in a nutshell.&lt;/p&gt;
&lt;h2 id=&quot;the-walkthrough&quot;&gt;The Walkthrough&lt;/h2&gt;
&lt;p&gt;Now, a walkthrough for those who like to get their hands dirty. I will go quick because I will assume familiarity with npm.&lt;/p&gt;
&lt;h3 id=&quot;installing&quot;&gt;Installing&lt;/h3&gt;
&lt;p&gt;First, you&amp;#39;ll need to install Browserify, obviously:&lt;/p&gt;
npm install browserify -g&lt;p&gt;This should install the browserify executable. On some platforms, you may need to use &lt;code&gt;sudo&lt;/code&gt; i.e. &lt;code&gt;sudo npm install browserify -g&lt;/code&gt; if you are getting permission error issues.&lt;/p&gt;
&lt;h3 id=&quot;create-a-project&quot;&gt;Create A Project&lt;/h3&gt;
&lt;p&gt;Create a new project directory and create a &lt;code&gt;package.json&lt;/code&gt; file&lt;/p&gt;
mkdir browserify_hello
cd browserify_hello
npm init&lt;h3 id=&quot;grab-some-modules&quot;&gt;Grab Some Modules&lt;/h3&gt;
npm install lodash --save
npm install superagent --save
npm install spin --save
npm install dom-events --save&lt;h2 id=&quot;write-some-code&quot;&gt;Write Some Code&lt;/h2&gt;
&lt;p&gt;The following code will implement a Github repository search engine. First, make a &lt;code&gt;index.html&lt;/code&gt; that contains a basic search UI:&lt;/p&gt;
&amp;lt;!doctype html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
&amp;lt;title&amp;gt;Browserify Hello&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;label for=&amp;quot;search&amp;quot;&amp;gt;Search Github&amp;lt;/label&amp;gt;
  &amp;lt;input id=&amp;quot;search&amp;quot; name=&amp;quot;search&amp;quot; type=&amp;quot;search&amp;quot;&amp;gt;
  &amp;lt;button id=&amp;quot;button&amp;quot;&amp;gt;Search&amp;lt;/button&amp;gt;
  &amp;lt;div id=&amp;quot;results&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
  &amp;lt;script src=&amp;quot;bundle.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;p&gt;Next make an &lt;code&gt;index.js&lt;/code&gt;:&lt;/p&gt;
var Spinner = require(&amp;#39;spin&amp;#39;);
var request = require(&amp;#39;superagent&amp;#39;);
var event = require(&amp;#39;dom-events&amp;#39;);
var _ = require(&amp;#39;lodash&amp;#39;);

var button = document.getElementById(&amp;#39;button&amp;#39;);
var resultsDiv = document.getElementById(&amp;#39;results&amp;#39;);
var search = document.getElementById(&amp;#39;search&amp;#39;);

event.on(button, &amp;#39;click&amp;#39;, function(){
  var spinner = new Spinner({
    color: &amp;#39;#000&amp;#39;,
    lines: 12
  });
  spinner.spin(resultsDiv);
  request(&amp;#39;https://api.github.com/search/repositories&amp;#39;)
    .query({q: search.value})
    .end(function(reply){
      renderResults(reply.body);
      spinner.stop();
    });
})

function renderResults(results){
  var div = document.getElementById(&amp;#39;results&amp;#39;);
  var markup = _.template(&amp;#39;&amp;lt;ul&amp;gt;\
    &amp;lt;% _.forEach(items, function(repo){ %&amp;gt;\
      &amp;lt;li&amp;gt;&amp;lt;%= repo.full_name %&amp;gt;&amp;lt;/li&amp;gt;\
    &amp;lt;% }) %&amp;gt;\
  &amp;lt;/ul&amp;gt;&amp;#39;, results);
  resultsDiv.innerHTML = markup;
}&lt;h3 id=&quot;bundle-it&quot;&gt;Bundle It&lt;/h3&gt;
browserify index.js -o bundle.js&lt;h3 id=&quot;run-it&quot;&gt;Run It&lt;/h3&gt;
&lt;p&gt;Open &lt;code&gt;index.html&lt;/code&gt; in you browser, and test it out. You should now have a functioning Github repository search engine, and it even has a spinner while the results are loading!&lt;/p&gt;
&lt;h2 id=&quot;shimmed-node-js-environment&quot;&gt;Shimmed Node.js Environment&lt;/h2&gt;
&lt;p&gt;The above example used &lt;a href=&quot;http://lodash.com/&quot;&gt;lodash&lt;/a&gt;, &lt;a href=&quot;https://github.com/defunctzombie/dom-events&quot;&gt;dom-events&lt;/a&gt;, &lt;a href=&quot;https://github.com/visionmedia/superagent&quot;&gt;superagent&lt;/a&gt;, and &lt;a href=&quot;https://github.com/visionmedia/spin.js&quot;&gt;spin&lt;/a&gt;. But you might be wondering: can I use just &lt;em&gt;any&lt;/em&gt; module off of npm? The answer is: not exactly. Although, Browserify does make a valiant effort.&lt;/p&gt;
&lt;p&gt;Browserify makes some modifications to the browser environment to make it look like the Node environment. You have access to things like:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://nodejs.org/api/process.html#process_process_nexttick_callback&quot;&gt;process.nextTick()&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://nodejs.org/docs/latest/api/globals.html#globals_dirname&quot;&gt;__dirname&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://nodejs.org/docs/latest/api/globals.html#globals_filename&quot;&gt;__filename&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You can use Node core modules like:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://nodejs.org/docs/latest/api/events.html&quot;&gt;events&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://nodejs.org/docs/latest/api/stream.html&quot;&gt;stream&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://nodejs.org/docs/latest/api/path.html&quot;&gt;path&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://nodejs.org/docs/latest/api/assert.html&quot;&gt;assert&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://nodejs.org/docs/latest/api/querystring.html&quot;&gt;querystring&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://nodejs.org/docs/latest/api/http.html&quot;&gt;http&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;See &lt;a href=&quot;https://github.com/substack/node-browserify#compatibility&quot;&gt;the docs&lt;/a&gt; for the full list. For a given module, these shims make it much more likely for it to work in the browser, but it&amp;#39;s not a guarantee. In practice this is not a big problem, because frontend code and backend code generally do very different things anyway, so it&amp;#39;s actually a good idea to keep them separate where it makes sense. But this does present a challenge: &lt;em&gt;how does one find frontend modules on npm?&lt;/em&gt; Searching on &lt;a href=&quot;https://www.npmjs.org/&quot;&gt;npm&lt;/a&gt;, the only way to know for sure whether a module can work with browserify or not is by installing it and then running Browserify on it. Unfortunately, there&amp;#39;s no home-run solution to this yet, but people are working on it and this should get easier soon.&lt;/p&gt;
&lt;h2 id=&quot;source-maps&quot;&gt;Source Maps&lt;/h2&gt;
&lt;p&gt;Since Browserify transforms your source code and dependencies all into one single bundle, debugging can become difficult when you are stepping through the debugger and line numbers that don&amp;#39;t correspond to your actual source. Luckily, there&amp;#39;s &lt;a href=&quot;http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/&quot;&gt;source maps&lt;/a&gt;! To turn on source maps just use the &lt;code&gt;--debug&lt;/code&gt; option. However, last I checked in Chrome, line numbers in error stack traces still do not get remapped.&lt;/p&gt;
&lt;h2 id=&quot;transforms&quot;&gt;Transforms&lt;/h2&gt;
&lt;p&gt;Browserify also supports performing source transforms as part of the build process. Using source transforms, you can support preprocessor languages like CoffeeScript, EcmaScript 6 syntax, even markup templating languages like Jade and CSS preprocessor languages like Sass and Less.&lt;/p&gt;
&lt;p&gt;For example, to use CoffeeScript, just install the coffeeify module and pass it in via the &lt;code&gt;-t&lt;/code&gt; option:&lt;/p&gt;
npm install coffeeify
browserify -t coffeeify index.coffee -o bundle.js&lt;p&gt;Take a look at &lt;a href=&quot;https://github.com/substack/node-browserify/wiki/list-of-transforms&quot;&gt;the List of Transforms&lt;/a&gt; to see what else is possible with transforms.&lt;/p&gt;
&lt;h2 id=&quot;automation&quot;&gt;Automation&lt;/h2&gt;
&lt;p&gt;Having to do a manual compilation step every time you change a file gets old really fast. As you might have guessed, there are tools for that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/jmreidy/grunt-browserify&quot;&gt;Grunt-Browserify&lt;/a&gt;: there&amp;#39;s a Grunt plugin for that!&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/hughsk/vinyl-source-stream&quot;&gt;vinyl-source-stream&lt;/a&gt; appears to be the prefered solution for Gulp + Browserify.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/substack/watchify&quot;&gt;watchify&lt;/a&gt; - if you just want a standalone watcher.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/chrisdickinson/beefy&quot;&gt;beefy&lt;/a&gt; - spin up a development server that automatically Browserifies your entry point .js file on the fly.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/airportyh/bff&quot;&gt;bff&lt;/a&gt; - like beefy, but doesn&amp;#39;t require you to specify an entry point .js.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you prefer to build your own tooling, Browserify can be used as a Node module:&lt;/p&gt;
var browserify = require(&amp;#39;browserify&amp;#39;);
var fs = require(&amp;#39;fs&amp;#39;);

browserify([&amp;#39;./index.js&amp;#39;])
  .bundle(function(err, code){
    if (err) return console.error(err.message);
    fs.writeFile(&amp;#39;bundle.js&amp;#39;, code);
  });&lt;h2 id=&quot;requirebin-browserify-playground&quot;&gt;RequireBin: Browserify Playground&lt;/h2&gt;
&lt;p&gt;Okay, if you are too lazy to even use the automation tools, give &lt;a href=&quot;http://requirebin.com/&quot;&gt;requirebin.com&lt;/a&gt; a try. It is like a jsbin that integrates with Browserify and npm modules easily. Go there and you can start requiring npm modules right away, and run it. You don&amp;#39;t even have to &lt;code&gt;npm install&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id=&quot;jquery-and-mv-frameworks&quot;&gt;jQuery And MV* Frameworks&lt;/h2&gt;
&lt;p&gt;Although the premise of Small.js is to forego large frameworks in favor of building things from scratch using small modules, I recognize that you can get a lot of benefit from building in small modules atop a larger foundation as well. Plus, this seems to be a common issue people run into, so, I&amp;#39;ll cover how Browserify works/interacts with some of the popular frameworks.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;jQuery - &lt;code&gt;jquery&lt;/code&gt; became a proper npm package starting version 2.0, which means you can &lt;code&gt;npm install jquery&lt;/code&gt; and &lt;code&gt;var $ = require(&amp;#39;jquery&amp;#39;)&lt;/code&gt;, glorious!&lt;/li&gt;
&lt;li&gt;Backbone - &lt;code&gt;backbone&lt;/code&gt; has long been available on npm, in fact it has proved useful for server-side applications.&lt;/li&gt;
&lt;li&gt;AngularJS, Ember, Marionette and other frameworks not directly available on npm as client packages - I recommend downloading the framework separately either as a direct download or by using bower (to be covered in a separate episode). Include the scripts separately via script tags or via your build process. You can then manage the rest of your dependencies using npm and Browserify by adding another script tag for the browserify bundle.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;homework&quot;&gt;Homework&lt;/h2&gt;
&lt;p&gt;Yes, homework! I can tell you were hoping that I would forget about homework, but I didn&amp;#39;t, &lt;em&gt;ha&lt;/em&gt;!&lt;/p&gt;
&lt;p&gt;You homework is to find and discover a new module on npm - one that you did not already know about - install it, and use it with Browserify by building a simple toy application. Have fun!&lt;/p&gt;

    </content>
  </entry>
  
  <entry>
    <title>array</title>
    <author>Toby Ho</author>
    <link href="http://smalljs.org/collections/array/"/>
    <updated>2014-03-26T00:00:00.000Z</updated>
    <id>http://smalljs.org/collections/array/</id>
    <content>
      &lt;p&gt;If you are like me, you had a background in another programming language before getting familiar with JavaScript. Also, if you are like me, the thought &amp;quot;WTF&amp;quot; might have come up once or twice as you were learning JavaScript&amp;#39;s &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array&quot;&gt;array API&lt;/a&gt;. Gradually though, you&amp;#39;ve familiarized yourself with the array, and it has become second nature to you. The array API is actually not that bad, especially after the &lt;a href=&quot;http://www.jimmycuadra.com/posts/ecmascript-5-array-methods&quot;&gt;functional style methods&lt;/a&gt; were introduced in Ecmascript 5. But still, it &lt;em&gt;could&lt;/em&gt; be better - which is the aim of the module I am covering - simply called &lt;a href=&quot;https://github.com/matthewmueller/array&quot;&gt;array&lt;/a&gt;. array provides events that allow observers to be notified of changes in the array and adds convinient shorthands for functional style methods.&lt;/p&gt;
&lt;h2 id=&quot;the-constructor&quot;&gt;The Constructor&lt;/h2&gt;
&lt;p&gt;First things first: as a convention, we will aliase array&amp;#39;s constructor to &lt;code&gt;array&lt;/code&gt;:&lt;/p&gt;
var array = require(&amp;#39;array&amp;#39;);&lt;p&gt;To make a new array, call the constructor:&lt;/p&gt;
var arr = array();&lt;p&gt;Alternatively you can pass an existing native array as its argument and it will initialize to the contents of that array:&lt;/p&gt;
var numbers = array([1, 2, 3]);
// =&amp;gt; array instance representing [1, 2, 3]&lt;p&gt;Unlike the &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array&quot;&gt;native array constructor&lt;/a&gt;, you can&amp;#39;t pass a variable list of parameters to it or initialize it with a &amp;quot;size&amp;quot; argument:&lt;/p&gt;
var arrayOfNames = array(&amp;quot;Bob&amp;quot;, &amp;quot;Jen&amp;quot;, &amp;quot;Ben&amp;quot;);
// things will go horribly wrong
var arrayOf5Things = array(5);
// things will also go horribly wrong&lt;h2 id=&quot;array-methods&quot;&gt;Array Methods&lt;/h2&gt;
&lt;p&gt;array implements most of the &lt;a href=&quot;https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array&quot;&gt;native array methods&lt;/a&gt; you know and love. In most cases (with some caveat) it can be a drop-in replacement for the native array, but there are also some differences. Later in this article I will list its &lt;a href=&quot;#differences-to-native-array&quot;&gt;differences&lt;/a&gt; to native arrays.&lt;/p&gt;
&lt;h2 id=&quot;events&quot;&gt;Events&lt;/h2&gt;
&lt;p&gt;Events allow observers to be notified of changes to the contents of the array, which can be useful for building user interfaces. array is an &lt;a href=&quot;/object/events/event-emitter/&quot;&gt;event emitter&lt;/a&gt;, so you can register for change events using the &lt;code&gt;on()&lt;/code&gt; method&lt;/p&gt;
arr.on(&amp;#39;change&amp;#39;, function(){
  console.log(&amp;#39;Array has changed!&amp;#39;);
});&lt;p&gt;The following events are emitted:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;add&lt;/code&gt; (item, index) - when items are added to the array (&lt;code&gt;push&lt;/code&gt;, &lt;code&gt;unshift&lt;/code&gt;, &lt;code&gt;splice&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;remove&lt;/code&gt; (item, index) - when items are removed from the array (&lt;code&gt;pop&lt;/code&gt;, &lt;code&gt;shift&lt;/code&gt;, &lt;code&gt;splice&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;sort&lt;/code&gt; - when array is sorted.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;reverse&lt;/code&gt; - when array is reversed.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;change&lt;/code&gt; - whenever array is modified - emitted at most once for every mutating operation.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;functional-shorthands&quot;&gt;Functional Shorthands&lt;/h2&gt;
&lt;p&gt;Like the native array, array has the functional programming style helper methods like &lt;code&gt;map()&lt;/code&gt; and &lt;code&gt;filter()&lt;/code&gt;, etc (filter is also aliased to &lt;code&gt;select()&lt;/code&gt;). array adds a twist to them by allowing you to specify the criteria in shorter and more expressive ways than anonymous functions. So instead of writing&lt;/p&gt;
var firstNames = users.map(function(user){
  return user.name.first;
});&lt;p&gt;You can write&lt;/p&gt;
var firstNames = users.map(&amp;#39;name.first&amp;#39;);&lt;p&gt;You can use shorthands for filtering an array as well. Here&amp;#39;s the before:&lt;/p&gt;
users.select(function(user){
  return user.age &amp;gt; 20;
})&lt;p&gt;And here&amp;#39;s the after:&lt;/p&gt;
users.select(&amp;#39;age &amp;gt; 20&amp;#39;)&lt;p&gt;Another syntax is:&lt;/p&gt;
users.select({age: 14}) // this finds users whose age === 14&lt;p&gt;It does this using the &lt;a href=&quot;https://github.com/component/to-function&quot;&gt;to-function&lt;/a&gt; behind the scenes - so take a look at to-function to find out all the different ways you can write matchers. Some other methods that support shorthands are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;unique(fn|str)&lt;/code&gt; - return a new array whose items are unique wrt to the criteria.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;reject(fn|str)&lt;/code&gt; - return a new array with all items which match the criteria removed.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;none(fn|str)&lt;/code&gt; - returns true iff none of the items satisfy the criteria.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;any(fn|str)&lt;/code&gt; - returns true iff at least one of the items satisfy the criteria.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;find([fn|str])&lt;/code&gt; - returns the first item that satisfies the criteria or undefined.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;findLast([fn|str])&lt;/code&gt; - returns the last item that satisfies the criteria or undefined.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For refenence to all methods, take a look at &lt;a href=&quot;https://github.com/matthewmueller/array#iteration-methods&quot;&gt;the docs&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id=&quot;-sort-&quot;&gt;&lt;code&gt;sort()&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;The sort method adds some extra shorthand for easily sorting by a criteria. For example, with a native array, if you wanted to sort by the &lt;code&gt;calories&lt;/code&gt; property of the contained items, you would write a compare function:&lt;/p&gt;
function compareCalories(user1, user2){
  if (user1.calories &amp;gt; user2.calories){
    return 1;
  }else if (user1.calories &amp;lt; user2.calories){
    return -1;
  }else{
    return 0;
  }
}
users.sort(compareCalories);&lt;p&gt;With array, you can simply do this:&lt;/p&gt;
users.sort(&amp;#39;calories&amp;#39;);&lt;p&gt;If you want to sort in descending order instead, you can do:&lt;/p&gt;
users.sort(&amp;#39;calories&amp;#39;, &amp;#39;descending&amp;#39;);&lt;h2 id=&quot;differences-to-native-array&quot;&gt;Differences To Native Array&lt;/h2&gt;
&lt;p&gt;Although array&amp;#39;s interface mimics the native array for the most part, there are some differences. These are the differences I&amp;#39;ve found:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the &lt;code&gt;length&lt;/code&gt; property doesn&amp;#39;t auto-magically update when you set a index of the array beyond it&amp;#39;s current size. This shouldn&amp;#39;t be a problem because normally, the best practice is to avoid using this feature and use &lt;code&gt;push&lt;/code&gt; or &lt;code&gt;splice&lt;/code&gt; to add items.&lt;/li&gt;
&lt;li&gt;doesn&amp;#39;t skip holes properly - i.e. &lt;code&gt;[1, ,3]&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;more&quot;&gt;More&lt;/h2&gt;
&lt;p&gt;For more information about &lt;a href=&quot;https://github.com/matthewmueller/array&quot;&gt;array&lt;/a&gt;, visit the &lt;a href=&quot;https://github.com/matthewmueller/array&quot;&gt;project page&lt;/a&gt;.&lt;/p&gt;

    </content>
  </entry>
  
  <entry>
    <title>Introduction to npm</title>
    <author>Toby Ho</author>
    <link href="http://smalljs.org/package-managers/npm/"/>
    <updated>2014-03-19T00:00:00.000Z</updated>
    <id>http://smalljs.org/package-managers/npm/</id>
    <content>
      &lt;p&gt;This time on small.js: &lt;a href=&quot;https://www.npmjs.org/&quot;&gt;npm&lt;/a&gt; - the granddaddy of JavaScript package managers. npm is the beloved package manager for &lt;a href=&quot;http://nodejs.org/&quot;&gt;Node&lt;/a&gt;. It hosts over 64 thousand modules and counting. Based on data at &lt;a href=&quot;http://modulecounts.com/&quot;&gt;modulecounts.com&lt;/a&gt; - npm is by far the fastest growing package manager, that&amp;#39;s is compared to Ruby Gems, CPAN, PyPI, Maven plus a few others. I believe this tremendous rate of growth has everything to do with the ease with which you can write and publish an npm module - we will get to that.&lt;/p&gt;
&lt;p&gt;npm isn&amp;#39;t limited only to Node modules, however. Client-side JavaScript modules have also found a home on npm. In an upcoming article I will cover how to use client-side modules on npm with &lt;a href=&quot;http://browserify.org/&quot;&gt;Browserify&lt;/a&gt;, but I am getting ahead of myself. First, let&amp;#39;s start from the beginning.&lt;/p&gt;
&lt;h2 id=&quot;getting-npm&quot;&gt;Getting npm&lt;/h2&gt;
&lt;p&gt;npm comes preinstalled with Node. If you have node, you already have npm! If not, install &lt;a href=&quot;http://nodejs.org/&quot;&gt;Node&lt;/a&gt; - it&amp;#39;s as easy as downloading and then running an installer.&lt;/p&gt;
&lt;h2 id=&quot;installing-modules&quot;&gt;Installing Modules&lt;/h2&gt;
&lt;p&gt;npm wants to keep dependencies of different projects separate and isolated - this is a good thing. So first, make a project:&lt;/p&gt;
mkdir npm_hello
cd npm_hello&lt;p&gt;Now you are ready to install modules! Try this&lt;/p&gt;
npm install cheerio&lt;p&gt;That installs &lt;a href=&quot;https://github.com/MatthewMueller/cheerio&quot;&gt;cheerio&lt;/a&gt;. Cheerio is a fun module - it gives you a jQuery API for parsing and manipulating a HTML document in Node - without a real browser. For example, the following script (save it as &lt;code&gt;run.js&lt;/code&gt;) extracts the text within each &lt;code&gt;&amp;lt;li&amp;gt;&lt;/code&gt; in a HTML snippet:&lt;/p&gt;
var cheerio = require(&amp;#39;cheerio&amp;#39;);
var $ = cheerio.load(
  &amp;#39;&amp;lt;ul&amp;gt;\
    &amp;lt;li&amp;gt;Bob&amp;lt;/li&amp;gt;\
    &amp;lt;li&amp;gt;Benny&amp;lt;/li&amp;gt;\
  &amp;lt;/ul&amp;gt;&amp;#39;);

$(&amp;#39;li&amp;#39;).each(function(){
  console.log($(this).text());
});&lt;p&gt;If you run it, you should get this result:&lt;/p&gt;
$ node run.js
Bob
Benny&lt;p&gt;Note the thing that you require - the string &amp;quot;cheerio&amp;quot; - is the same as the thing you install on the command line. This is always the case with npm, and it is nice because it removes ambiguity - it&amp;#39;s one less thing you have to think about. It also means that if you are reading someone else&amp;#39;s script and see &lt;code&gt;require(&amp;#39;abc&amp;#39;)&lt;/code&gt;, they almost certainly got it from &lt;code&gt;npm install abc&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;We are off to a great start. Why not install another one? Let&amp;#39;s install &lt;a href=&quot;http://smalljs.org/ajax/superagent/&quot;&gt;superagent&lt;/a&gt; - which I covered previously.&lt;/p&gt;
npm install superagent&lt;p&gt;This following script fetchs and prints the titles of latest posts on Hackernews:&lt;/p&gt;
var cheerio = require(&amp;#39;cheerio&amp;#39;);
var request = require(&amp;#39;superagent&amp;#39;);

request.get(&amp;#39;https://news.ycombinator.com/&amp;#39;)
  .end(function(reply){
    var $ = cheerio.load(reply.text);
    $(&amp;#39;td.title a&amp;#39;).each(function(){
      console.log($(this).text());
    });
  });&lt;p&gt;Run that and I got (actual result may vary)&lt;/p&gt;
[Full-disclosure] Administrivia: The End
Tired of doing coding interviews on Skype? We&amp;#39;ve built this
The sierpinski triangle page to end most sierpinski triangle pages 
Nodemailer: Easy as cake e-mail sending from your Node.js applications
What Happens to Older Developers?
Needy robotic toaster sells itself if neglected
Cleaning up from an IMAP server failure
... goes on for about 30 more lines ...&lt;p&gt;Look, you just made a web scrapper! Easy right? Such is the power of modules - you can connect them together like legos to make something new and brilliant!&lt;/p&gt;
&lt;h2 id=&quot;a-closer-look-nested-dependencies&quot;&gt;A Closer Look: Nested Dependencies&lt;/h2&gt;
&lt;p&gt;If you&amp;#39;ve been following along, you probably noticed that npm has created a &lt;code&gt;node_modules&lt;/code&gt; directory inside the project directory. This is where the installed modules reside. A look inside the directory shouldn&amp;#39;t surprise you:&lt;/p&gt;
$ ls node_modules
cheerio
superagent&lt;p&gt;But, you might be wondering, do these modules have any dependencies? If so, where are they? You may remember from the &lt;a href=&quot;/package-managers/component-part-1/&quot;&gt;first Component tutorial&lt;/a&gt; that Component installs the dependencies of the requested module in the same directory as the requested module. npm does things differently - it installs the dependencies in yet another &lt;code&gt;node_modules&lt;/code&gt; directory within that module&amp;#39;s subdirectory, and this &amp;quot;module nesting&amp;quot; can keep going indefinitely. In our scenario, we have this directory structure:&lt;/p&gt;
npm_hello
  ├run.js
  └node_modules
    ├cheerio
    │ └node_modules
    │   ├CSSselect
    │   │ └node_modules
    │   │   ├CSSwhat
    │   │   └domutils
    │   │     └node_modules
    │   │       └domelementtype
    │   ├entities
    │   ├htmlparser2
    │   │ └node_modules
    │   │   ├domelementtype
    │   │   ├domhandler
    │   │   ├domutils
    │   │   └readable-stream
    │   │     └node_modules
    │   │       ├core-util-is
    │   │       ├debuglog
    │   │       └string_decoder
    │   └underscore
    └superagent
      └node_modules
        ├cookiejar
        ├debug
        ├emitter-component
        ├extend
        ├formidable
        ├methods
        ├mime
        ├qs
        └reduce-component&lt;p&gt;&lt;em&gt;That&amp;#39;s a lot of modules!&lt;/em&gt; You can also visualize the module dependency hierarchy using &lt;code&gt;npm list&lt;/code&gt;:&lt;/p&gt;
$ npm list
.../npm_hello
├─┬ cheerio@0.13.1
│ ├─┬ CSSselect@0.4.1
│ │ ├── CSSwhat@0.4.5
│ │ └─┬ domutils@1.4.0
│ │   └── domelementtype@1.1.1
│ ├── entities@0.5.0
│ ├─┬ htmlparser2@3.4.0
│ │ ├── domelementtype@1.1.1
│ │ ├── domhandler@2.2.0
│ │ ├── domutils@1.3.0
│ │ └─┬ readable-stream@1.1.11
│ │   ├── core-util-is@1.0.1
│ │   ├── debuglog@0.0.2
│ │   └── string_decoder@0.10.25-1
│ └── underscore@1.5.2
└─┬ superagent@0.17.0
  ├── cookiejar@1.3.0
  ├── debug@0.7.4
  ├── emitter-component@1.0.0
  ├── extend@1.2.1
  ├── formidable@1.0.14
  ├── methods@0.0.1
  ├── mime@1.2.5
  ├── qs@0.6.5
  └── reduce-component@1.0.1&lt;p&gt;Note that we can see the version number of each module too. One thing that&amp;#39;s interesting to note is that two of the modules installed - &lt;code&gt;domutils&lt;/code&gt; and &lt;code&gt;domelementtype&lt;/code&gt; - are duplicates: there are two copies of each of them. That seems redundant and inefficient. &lt;em&gt;Why does npm do that?&lt;/em&gt; There&amp;#39;s actually a good reason - this makes it possible for two or more parent modules to depend on different versions of the same child module. In our scenario, both &lt;code&gt;cheerio&lt;/code&gt; and &lt;code&gt;htmlparser2&lt;/code&gt; depend on &lt;code&gt;domutils&lt;/code&gt;, but &lt;code&gt;cheerio&lt;/code&gt; uses version 1.4.0 while &lt;code&gt;htmlparser2&lt;/code&gt; uses version 1.3.0. In general, this ability to load different versions of the same module in different contexts but still within the same app avoids a whole class of problems that have to do with version conflicts - sometimes referred to as &lt;a href=&quot;http://en.wikipedia.org/wiki/DLL_Hell&quot;&gt;DLL Hell&lt;/a&gt;. In the land of Node, there is no DLL Hell, and we all all happier for it. Is it a little less efficient in terms of disk usage? Yes, but disk is cheap, frustration is more expensive - I think this is a worthwhile tradeoff.&lt;/p&gt;
&lt;h2 id=&quot;making-it-your-own&quot;&gt;Making It Your Own&lt;/h2&gt;
&lt;p&gt;Now that you&amp;#39;ve gotten your feet wet, the next step is to write and publish your own module.&lt;/p&gt;
&lt;h3 id=&quot;setting-up-a-module&quot;&gt;Setting Up A Module&lt;/h3&gt;
&lt;p&gt;The one file every module needs is &lt;code&gt;package.json&lt;/code&gt;. Typing this file out by hand is a little tedious. Fortunately, &lt;code&gt;npm init&lt;/code&gt; semi-automates this by asking you a series of questions on the prompt. If you are following along, use &lt;code&gt;&amp;lt;your internet handle&amp;gt;-scrape&lt;/code&gt; as the module name. All fields except for &lt;code&gt;name&lt;/code&gt; are optional, and you can just hit ENTER to skip them. This is how I answered the prompts &lt;/p&gt;
name: (npm_hello) airportyh-scrape
version: (0.0.0) 
description: A simple web scraper.
entry point: (index.js) 
test command: 
git repository: 
keywords: webscrapping
author: Toby Ho
license: (ISC) MIT&lt;p&gt;At the end it displays the resulting &lt;code&gt;package.json&lt;/code&gt;, and you can go ahead with creating the file or abort. My file looked like this&lt;/p&gt;
{
  &amp;quot;name&amp;quot;: &amp;quot;airportyh-scrape&amp;quot;,
  &amp;quot;version&amp;quot;: &amp;quot;0.0.0&amp;quot;,
  &amp;quot;description&amp;quot;: &amp;quot;A simple webscrapper.&amp;quot;,
  &amp;quot;main&amp;quot;: &amp;quot;index.js&amp;quot;,
  &amp;quot;dependencies&amp;quot;: {
    &amp;quot;superagent&amp;quot;: &amp;quot;~0.17.0&amp;quot;,
    &amp;quot;cheerio&amp;quot;: &amp;quot;~0.13.1&amp;quot;
  },
  &amp;quot;devDependencies&amp;quot;: {},
  &amp;quot;scripts&amp;quot;: {
    &amp;quot;test&amp;quot;: &amp;quot;echo \&amp;quot;Error: no test specified\&amp;quot; &amp;amp;&amp;amp; exit 1&amp;quot;
  },
  &amp;quot;keywords&amp;quot;: [
    &amp;quot;webscrapping&amp;quot;
  ],
  &amp;quot;author&amp;quot;: &amp;quot;Toby Ho&amp;quot;,
  &amp;quot;license&amp;quot;: &amp;quot;MIT&amp;quot;
}&lt;p&gt;Note that npm automatically added &lt;code&gt;superagent&lt;/code&gt; and &lt;code&gt;cheerio&lt;/code&gt; as my module&amp;#39;s dependencies because it found them in &lt;code&gt;node_modules&lt;/code&gt;. &lt;em&gt;Gee, that&amp;#39;s swell, thanks npm!&lt;/em&gt; If you install a module after this point, and would like to add it as a dependency, simply use the &lt;code&gt;--save&lt;/code&gt; option, as in &lt;code&gt;npm install &amp;lt;a module&amp;gt; --save&lt;/code&gt;. If you deleted your &lt;code&gt;node_modules&lt;/code&gt; directory for some reason, you can get all your dependencies back with the command &lt;code&gt;npm install&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id=&quot;writing-the-module&quot;&gt;Writing The Module&lt;/h3&gt;
&lt;p&gt;npm also defined &lt;code&gt;main&lt;/code&gt; - the entry point of the module - to be &lt;code&gt;index.js&lt;/code&gt;. This is the file Node runs when someone requires the module. Using index.js to mean &amp;quot;top-level entry point&amp;quot; is a common convention, but you can use a different name if you wish. Before creating this file, consider what the API of the module would look like:&lt;/p&gt;
var scrape = require(&amp;#39;airportyh-scrape&amp;#39;);

var url = &amp;#39;https://news.ycombinator.com/&amp;#39;;
scrape(url, &amp;#39;td.title a&amp;#39;, function(err, data){
  // check for err and/or deal with data
});&lt;p&gt;The API should take 3 parameters:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;url&lt;/code&gt; - the web URL to scrape&lt;/li&gt;
&lt;li&gt;&lt;code&gt;selector&lt;/code&gt; - the CSS selector to use to find elements of interest on the page&lt;/li&gt;
&lt;li&gt;&lt;code&gt;callback(err, data)&lt;/code&gt; - a function to be called when the results are ready. It should adhere to Node&amp;#39;s &lt;a href=&quot;http://blog.gvm-it.eu/post/22040726249/callback-conventions-in-node-js-how-and-why&quot;&gt;callback convention&lt;/a&gt; of using the first parameter for errors. The second parameter in the callback is data found and should be an array of strings.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So, here&amp;#39;s the &lt;code&gt;index.js&lt;/code&gt; that implements this:&lt;/p&gt;
var cheerio = require(&amp;#39;cheerio&amp;#39;);
var request = require(&amp;#39;superagent&amp;#39;);

module.exports = function(url, selector, callback){
  request(url)
    .end(function(err, reply){
      // Node-style error handling and forwarding
      if (err) return callback(err);
      // Also handle/forward error if server returns error
      if (reply.error) return callback(new Error(reply.text));

      // Everything okay, load the HTML
      var $ = cheerio.load(reply.text);

      // Find interesting bits via selector and convert to array
      var data = $(selector).map(function(){
        return $(this).text();
      }).toArray();

      // Pass data back to the callback in second argument
      callback(null, data);
    });
}&lt;p&gt;To test that this worked, modify &lt;code&gt;run.js&lt;/code&gt; to use it:&lt;/p&gt;
var scrape = require(&amp;#39;./index&amp;#39;);

var url = &amp;#39;https://news.ycombinator.com/&amp;#39;;
var selector = &amp;#39;td.title a&amp;#39;;
scrape(url, selector, function(err, data){
  if (err) 
    console.error(err.message);
    return
  }
  console.log(data.join(&amp;#39;\n&amp;#39;));
});&lt;p&gt;Run to verify. Note that this time require is given a relative path: &lt;code&gt;./index&lt;/code&gt; - with Node/npm, this is how you require intra-project modules.&lt;/p&gt;
&lt;h3 id=&quot;go-forth-and-publish-&quot;&gt;Go Forth And Publish!&lt;/h3&gt;
&lt;p&gt;Now you are ready to publish the module! If you&amp;#39;ve never published a Node module before, you&amp;#39;ll need to register for an account on the npm registry, but that&amp;#39;s easy:&lt;/p&gt;
npm adduser&lt;p&gt;This command will ask you for a username, password and your email address. You&amp;#39;d also use this command to login to your existing account in the case that you are on a machine that does not have your npm user information yet.&lt;/p&gt;
&lt;p&gt;Next,&lt;/p&gt;
npm publish&lt;p&gt;Wait... Congratulations! You published your first npm module! If you check the &lt;a href=&quot;https://www.npmjs.org/&quot;&gt;npm website&lt;/a&gt;, you should see yours at or near the top of the &amp;quot;recently updated&amp;quot; list of modules. How does &lt;em&gt;that&lt;/em&gt; feel?&lt;/p&gt;
&lt;p&gt;Now, as an exercise for the reader: make a new test project; install your newly published module from npm, and then write or modify the existing &lt;code&gt;run.js&lt;/code&gt; to test it.&lt;/p&gt;
&lt;h2 id=&quot;homework&quot;&gt;Homework&lt;/h2&gt;
&lt;p&gt;What&amp;#39;s that look? You knew you had homework, right? Your assignment is to add a command line utility as part of the module. If a user installs your module globally&lt;/p&gt;
npm install &amp;lt;your module&amp;gt; -g&lt;p&gt;They should be able to run this command from the shell&lt;/p&gt;
scrape https://news.ycombinator.com/ &amp;quot;td.title a&amp;quot;&lt;p&gt;and see the results. You&amp;#39;ll need to create a &lt;code&gt;cli.js&lt;/code&gt; in the module, and tell &lt;code&gt;package.json&lt;/code&gt; about it via the &lt;code&gt;bin&lt;/code&gt; property. For more information run &lt;code&gt;npm help json&lt;/code&gt; and look for the &amp;quot;bin&amp;quot; section. You&amp;#39;ll also need to inspect the &lt;code&gt;process.argv&lt;/code&gt; array to get the command line arguments.&lt;/p&gt;
&lt;h2 id=&quot;more-info&quot;&gt;More Info&lt;/h2&gt;
&lt;p&gt;There&amp;#39;s actually a lot more to npm that I haven&amp;#39;t covered. Here are some good resources on npm:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://tobyho.com/2012/02/09/tour-of-npm/&quot;&gt;Tour of npm&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.devthought.com/2012/02/17/npm-tricks/&quot;&gt;npm Tricks&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://decodize.com/javascript/build-nodejs-npm-installation-package-scratch/&quot;&gt;How to Build a Node npm Package From Scratch&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

    </content>
  </entry>
  
  <entry>
    <title>Reactive</title>
    <author>Toby Ho</author>
    <link href="http://smalljs.org/ui/view/reactive/"/>
    <updated>2014-03-11T00:00:00.000Z</updated>
    <id>http://smalljs.org/ui/view/reactive/</id>
    <content>
      &lt;p&gt;Knockout and AngularJS have popularized the concept of declarative data binding in UI views. &lt;a href=&quot;https://github.com/component/reactive&quot;&gt;Reactive&lt;/a&gt; is a library that gives you this convinience in à la carte fashion.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note: reactive does 1-way data binding: from the model to the view - it does not support 2-way binding. It can be made to approach 2-way binding behavior by declaring custom bindings.&lt;/em&gt;&lt;/p&gt;
&lt;h2 id=&quot;basic-example&quot;&gt;Basic Example&lt;/h2&gt;
&lt;p&gt;Supposed you have the following &amp;quot;view&amp;quot; in your HTML page, which displays information about a person. It uses string interpolation to substitute in the &lt;code&gt;name&lt;/code&gt; and &lt;code&gt;age&lt;/code&gt; properties of said person:&lt;/p&gt;
&amp;lt;div id=&amp;quot;person-view&amp;quot;&amp;gt;
  &amp;lt;label&amp;gt;Name:&amp;lt;/label&amp;gt;
  &amp;lt;span&amp;gt;{ name }&amp;lt;/span&amp;gt;
  &amp;lt;label&amp;gt;Age:&amp;lt;/label&amp;gt;
  &amp;lt;span&amp;gt;{ age }&amp;lt;/span&amp;gt;
&amp;lt;/div&amp;gt;&lt;p&gt;You have a person object:&lt;/p&gt;
var bob = {
  name: &amp;#39;Bob&amp;#39;,
  age: 38
};&lt;p&gt;To wire up the view to the object:&lt;/p&gt;
var elm = document.getElementById(&amp;#39;person-view&amp;#39;);
reactive(elm, bob);&lt;p&gt;Bam! Now the view is populated with the values from the object.&lt;/p&gt;
&lt;p&gt;Alternatively, the first argument can also be a string containing the template markup.&lt;/p&gt;
reactive(&amp;#39;&amp;lt;div id=&amp;quot;person-view&amp;quot;&amp;gt;...&amp;lt;/div&amp;gt;&amp;#39;, bob);&lt;p&gt;But, since &lt;code&gt;bob&lt;/code&gt; is a plain object, there is no way to tell the view that its value has updated. What we need is something that fires events - we can use an &lt;a href=&quot;/object/events/event-emitter/&quot;&gt;event emitter&lt;/a&gt; for this.&lt;/p&gt;
&lt;h2 id=&quot;event-emitter&quot;&gt;Event Emitter&lt;/h2&gt;
&lt;p&gt;An &lt;code&gt;Person&lt;/code&gt; object that emits events can be written as:&lt;/p&gt;
function Person(name, age){
  this.name = name;
  this.age = age;
}
Person.prototype = new EventEmitter; // or substitute your preferred
                                     // method of inheritance here.&lt;p&gt;&lt;code&gt;bob&lt;/code&gt; can be instantiated as&lt;/p&gt;
var bob = new Person(&amp;#39;Bob&amp;#39;, 38);&lt;p&gt;And now, it can emit events to tell the view when its properties has changed:&lt;/p&gt;
bob.age = 39;
bob.emit(&amp;#39;change age&amp;#39;);&lt;p&gt;At this point the age value in the view&amp;#39;s display will update. Note that the name of the event reactive looks for by default is &lt;code&gt;change &amp;lt;name of property&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id=&quot;backbone-model&quot;&gt;Backbone Model&lt;/h2&gt;
&lt;p&gt;If you use Backbone, I know what you are saying: &lt;em&gt;why trigger the event manually? Backbone models will do that for you!&lt;/em&gt; Valid point. Reactive can do that! Reactive is pluggable and can be made to work with a variety of model implementations, including Backbone models. To do this, we need an adapter for backbone models. A model adapter is a constructor that takes a model object and implements the following methods:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;subscribe&lt;/li&gt;
&lt;li&gt;unsubscribe&lt;/li&gt;
&lt;li&gt;unsubscribeAll&lt;/li&gt;
&lt;li&gt;set&lt;/li&gt;
&lt;li&gt;get&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;See the &lt;a href=&quot;https://github.com/component/reactive#adapters&quot;&gt;adapters documentation&lt;/a&gt; for more details on how to implement your own adapter. I&amp;#39;ve made it easy for you, here&amp;#39;s the code for the Backbone adapter:&lt;/p&gt;
function BackboneAdapter(model){
  if (!(this instanceof BackboneAdapter)){
    return new BackboneAdapter(model);
  }
  this.model = model;
}

BackboneAdapter.prototype = {
  subscribe: function(prop, fn){
    // This tells it how to bind a property change event
    this.model.on(&amp;#39;change:&amp;#39; + prop, fn);
  },
  unsubscribe: function(prop, fn){
    // This tells it how to unbind a property change event
    this.model.off(&amp;#39;change:&amp;#39; + prop, fn);
  },
  unsubscribeAll: function(){
    // This tells it how to unbind all events
    this.model.off();
  },
  set: function(prop, value){
    // This tells it how to set a property on a model
    this.model.set(prop, value);
  },
  get: function(prop, value){
    // This tells it how to get a property on a model
    return this.model.get(prop);
  }
}&lt;p&gt;&lt;em&gt;Note: I&amp;#39;ve put the Backbone adapter on github as a &lt;a href=&quot;https://github.com/airportyh/reactive-backbone&quot;&gt;separate project&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Now, to test it out, first make a backbone model instance:&lt;/p&gt;
var bob = new Backbone.Model({name: &amp;#39;Bob&amp;#39;, age: 35});&lt;p&gt;Bind the backbone model to the view using reactive, supplying the backbone adapter&lt;/p&gt;
reactive(elm, bob, {adapter: BackboneAdapter});&lt;p&gt;And voila! Now the view will automatically update when the model&amp;#39;s attributes are set - such as &lt;code&gt;bob.set(&amp;#39;name&amp;#39;, &amp;#39;Robert&amp;#39;)&lt;/code&gt;. &lt;/p&gt;
&lt;p&gt;Everyone loves Backbone, right? If Backbone is not your thing though, that&amp;#39;s okay too! For alternative model implementations, have a look at &lt;a href=&quot;https://github.com/defunctzombie/bamboo&quot;&gt;Bamboo&lt;/a&gt; and &lt;a href=&quot;https://github.com/modella/modella&quot;&gt;Modella&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id=&quot;string-interpolation&quot;&gt;String Interpolation&lt;/h2&gt;
&lt;p&gt;Now you are ready to take a closer look at Reactive&amp;#39;s the string interpolation feature. Take this example:&lt;/p&gt;
&amp;lt;article&amp;gt;
  &amp;lt;h2&amp;gt;{ name }&amp;lt;/h2&amp;gt;
&amp;lt;/article&amp;gt;&lt;p&gt;Reactive interpolates expressions between &lt;code&gt;{&lt;/code&gt; and &lt;code&gt;}&lt;/code&gt;. The syntax can be simple properties, but can also be more complex JavaScript expressions, such as method calls:&lt;/p&gt;
{ name.toUpperCase() }&lt;p&gt;and string concatenation:&lt;/p&gt;
{ firstName + &amp;#39; &amp;#39; + lastName }&lt;p&gt;The properties used in these expressions will be bound automatically so that if they change, the view updates correctly.&lt;/p&gt;
&lt;h2 id=&quot;declarative-bindings&quot;&gt;Declarative Bindings&lt;/h2&gt;
&lt;p&gt;In addition to string interpolation, Reactive also provides declarative bindings - which are written as attributes of DOM elements. I&amp;#39;ll walk through the most useful ones.&lt;/p&gt;
&lt;h3 id=&quot;event-bindings&quot;&gt;Event Bindings&lt;/h3&gt;
&lt;p&gt;You can use an event binding to delegate event handling to your code. To specify a handler for a &lt;code&gt;click&lt;/code&gt; event on an element, you&amp;#39;d use the &lt;code&gt;on-click&lt;/code&gt; binding:&lt;/p&gt;
&amp;lt;button on-click=&amp;quot;save&amp;quot;&amp;gt;Save&amp;lt;/button&amp;gt;&lt;p&gt;The value specified - in this case: &lt;code&gt;save&lt;/code&gt; - maps to a method in the delegate object, which you&amp;#39;ll need to specify as an option to reactive. For example:&lt;/p&gt;
var delegate = {
  save: function(e, view){
    var model = view.model;
    request.post(&amp;#39;/api/person/&amp;#39;, model.serialize());
  }
}

reactive(elm, bob, {
  delegate: delegate
});&lt;p&gt;All the common DOM events are supported, via &lt;code&gt;on-&amp;lt;event name&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;h3 id=&quot;-each-binding&quot;&gt;&lt;code&gt;each&lt;/code&gt; Binding&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;each&lt;/code&gt; gives you the ability to iterate an array of objects. It binds a model property - the value of which should be an array - and renders the original contents of the element once for each item in the array. Example:&lt;/p&gt;
&amp;lt;ul each=&amp;quot;children&amp;quot;&amp;gt;
  &amp;lt;li&amp;gt;{last}, {first}&amp;lt;/li&amp;gt;
&amp;lt;/ul&amp;gt;&lt;p&gt;&lt;em&gt;Note: in order to be notified of changes in the array, the &lt;code&gt;each&lt;/code&gt; binding &lt;a href=&quot;http://www.paulirish.com/2010/duck-punching-with-jquery/&quot;&gt;duck punches&lt;/a&gt; the instance of array that&amp;#39;s in use.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;If you use Backbone, you might be wondering whether this can iterate a &lt;code&gt;Backbone.Collection&lt;/code&gt;. Currently the answer is no.&lt;/p&gt;
&lt;h3 id=&quot;-data-attr-binding&quot;&gt;&lt;code&gt;data-&amp;lt;attr&amp;gt;&lt;/code&gt; Binding&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;data-&amp;lt;attr&amp;gt;&lt;/code&gt; binds a model property to an attribute of the element. &lt;/p&gt;
&amp;lt;a data-href=&amp;quot;download_url&amp;quot;&amp;gt;Download&amp;lt;/a&amp;gt;&lt;h3 id=&quot;-data-visible-and-data-hidden-bindings&quot;&gt;&lt;code&gt;data-visible&lt;/code&gt; and &lt;code&gt;data-hidden&lt;/code&gt; Bindings&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;data-visible&lt;/code&gt; binds a boolean model property. If the value is true, it adds the class &lt;code&gt;visible&lt;/code&gt; to the element, otherwise, it addes the class &lt;code&gt;hidden&lt;/code&gt; to the element. This allows for conviniently showing or hiding it - note that you&amp;#39;ll need to write CSS rules to instruct the browser how you want to show or hide the element based on these classes (you could use CSS animations or simply display: none). &lt;code&gt;data-hidden&lt;/code&gt; does the opposite of &lt;code&gt;data-visible&lt;/code&gt;.&lt;/p&gt;
&amp;lt;p data-hidden=&amp;quot;hasItems&amp;quot;&amp;gt;no items&amp;lt;/p&amp;gt;
&amp;lt;ul data-visible=&amp;quot;hasItems&amp;quot;&amp;gt;
  &amp;lt;li each=&amp;quot;items&amp;quot;&amp;gt;{name}&amp;lt;/li&amp;gt;
&amp;lt;/ul&amp;gt;&lt;h3 id=&quot;-data-checked-binding&quot;&gt;&lt;code&gt;data-checked&lt;/code&gt; Binding&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;data-checked&lt;/code&gt; binds a model property to the &lt;code&gt;checked&lt;/code&gt; property of a checkbox.&lt;/p&gt;
&amp;lt;input type=&amp;quot;checkbox&amp;quot; data-checked=&amp;quot;agreed_to_terms&amp;quot;&amp;gt;&lt;h3 id=&quot;-data-append-binding&quot;&gt;&lt;code&gt;data-append&lt;/code&gt; Binding&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;data-append&lt;/code&gt; appends a new DOM element.&lt;/p&gt;
&amp;lt;div data-append=&amp;quot;histogram&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;&lt;p&gt;The &lt;code&gt;histogram&lt;/code&gt; property of the model is expected to contain a DOM element containing the desired widget.&lt;/p&gt;
&lt;h3 id=&quot;more-on-bindings&quot;&gt;More On Bindings&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/component/reactive#declarative-bindings&quot;&gt;Read the docs&lt;/a&gt; for refenences on all the bindings. It is also possible to write your own &lt;a href=&quot;https://github.com/component/reactive#writing-bindings&quot;&gt;custom bindings&lt;/a&gt; that do amazing things! I&amp;#39;ll leave that as an exercise for the reader.&lt;/p&gt;
&lt;h2 id=&quot;a-view-pattern&quot;&gt;A View Pattern&lt;/h2&gt;
&lt;p&gt;There is a view pattern that works well for applications that use Reactive. It looks like this&lt;/p&gt;
function UserView(user){
  this.user = user;
  this.view = reactive(html, user, {
    delegate: this // event delegate is set to the instance itself
  });
}

// Event handlers via event binding can simply be written as methods
UserView.prototype.edit = function(evt){
  ...
}
    </content>
  </entry>
  
  <entry>
    <title>Event Emitter</title>
    <author>Toby Ho</author>
    <link href="http://smalljs.org/object/events/event-emitter/"/>
    <updated>2014-02-18T00:00:00.000Z</updated>
    <id>http://smalljs.org/object/events/event-emitter/</id>
    <content>
      &lt;div class=&quot;summary&quot;&gt;
  &lt;h3&gt;Module Summary&lt;/h3&gt;
  &lt;dl&gt;
    &lt;dt&gt;Node.js:&lt;/dt&gt;
    &lt;dd&gt;&lt;a href=&quot;http://nodejs.org/api/events.html&quot;&gt;events&lt;/a&gt;&lt;/dd&gt;
    &lt;dt&gt;Component:&lt;/dt&gt;
    &lt;dd&gt;&lt;a href=&quot;https://github.com/component/emitter&quot;&gt;component/emitter&lt;/a&gt;&lt;/dd&gt;
    &lt;dt&gt;Bower:&lt;/dt&gt;
    &lt;dd&gt;&lt;a href=&quot;https://github.com/Wolfy87/EventEmitter&quot;&gt;eventEmitter&lt;/a&gt;&lt;/dd&gt;
    &lt;dt&gt;Dependencies:&lt;/dt&gt;
    &lt;dd&gt;None&lt;/dd&gt;
    &lt;dt title=&quot;lines of code with comments and empty lines stripped&quot;&gt;LOC:&lt;/dt&gt;
    &lt;dd title=&quot;lines of code with comments and empty lines stripped&quot;&gt;
      &lt;span title=&quot;Node built-in version&quot;&gt;302&lt;/span&gt;/&lt;span title=&quot;Component version&quot;&gt;112&lt;/span&gt;/&lt;span title=&quot;Bower/Wolfy87 version&quot;&gt;308&lt;/span&gt;
    &lt;/dd&gt;
    &lt;dt&gt;File size minified:&lt;/dt&gt;&lt;br&gt;    &lt;dd&gt;
      &lt;span title=&quot;Node built-in version&quot;&gt;4.2k&lt;/span&gt;/&lt;span title=&quot;Component version&quot;&gt;1.3k&lt;/span&gt;/&lt;span title=&quot;Bower/Wolfy87 version&quot;&gt;2.8k&lt;/span&gt;
    &lt;/dd&gt; 
  &lt;/dl&gt;
&lt;/div&gt;

&lt;p&gt;Today I am going to cover the &lt;em&gt;event emitter&lt;/em&gt;. What is an event emitter? Well, it&amp;#39;s a simple library for attaching events to JavaScript objects. &lt;/p&gt;
&lt;h2 id=&quot;a-little-history&quot;&gt;A Little History&lt;/h2&gt;
&lt;p&gt;Event emitter first appeared as a &lt;a href=&quot;http://nodejs.org/api/events.html&quot;&gt;core library&lt;/a&gt; in Node where it has proven to be a useful pattern. Since the library itself is not specific to Node at all, it has found uses in the browser as well. There are now many implementations of event emitter - partly due to how easy it is to implement its API. Here, I am going to cover the event emitter API that is common to most implementations.&lt;/p&gt;
&lt;h2 id=&quot;registering&quot;&gt;Registering&lt;/h2&gt;
&lt;p&gt;Let&amp;#39;s say there is &lt;code&gt;job&lt;/code&gt; object which happens to be an event emitter. To register an event handler for the event &lt;code&gt;done&lt;/code&gt;, you&amp;#39;d use the &lt;code&gt;on&lt;/code&gt; method like so:&lt;/p&gt;
job.on(&amp;#39;done&amp;#39;, function(){
  console.log(&amp;#39;The job is done!&amp;#39;);
});&lt;h2 id=&quot;emitting&quot;&gt;Emitting&lt;/h2&gt;
&lt;p&gt;Now if you are writing the code responsible for actually performing the job, you&amp;#39;ll need to notify all the handlers that the job was done at the end. How do you do that?&lt;/p&gt;
job.emit(&amp;#39;done&amp;#39;);&lt;p&gt;You can also pass arguments to the event, for example the time when the job was done.&lt;/p&gt;
var timeDone = new Date();
job.emit(&amp;#39;done&amp;#39;, timeDone);&lt;p&gt;The arguments will passed in the same order to all the handlers.&lt;/p&gt;
job.on(&amp;#39;done&amp;#39;, function(timeDone){
  console.log(&amp;#39;Job was pronounced done at&amp;#39;, timeDone);
});&lt;h2 id=&quot;removing-handlers&quot;&gt;Removing Handlers&lt;/h2&gt;
&lt;p&gt;To remove an active event handler from an event emitter, you&amp;#39;d use the &lt;code&gt;removeListener&lt;/code&gt; method&lt;/p&gt;
function onDone(timeDone){
  console.log(&amp;#39;Job was pronounced done at&amp;#39;, timeDone);
}
job.on(&amp;#39;done&amp;#39;, onDone);
...
job.removeListener(&amp;#39;done&amp;#39;, onDone);&lt;p&gt;Or you could use the &lt;code&gt;removeAllListeners&lt;/code&gt; method to remove all handlers associated with an event:&lt;/p&gt;
job.removeAllListeners();&lt;h2 id=&quot;fire-just-once&quot;&gt;Fire Just Once&lt;/h2&gt;
&lt;p&gt;The event emitter API also has a convinient shorthand for registering a handler to be called once, and once only, it&amp;#39;s called &lt;code&gt;once()&lt;/code&gt;.&lt;/p&gt;
job.once(&amp;#39;done&amp;#39;, function(){
  // This callback will only be called the
  // first time &#x60;done&#x60; is fired.
});&lt;h2 id=&quot;make-your-own-event-emitter&quot;&gt;Make Your Own Event Emitter&lt;/h2&gt;
&lt;p&gt;So, that&amp;#39;s great, but how do you make an event emitter of your own? You inherit EventEmitter.&lt;/p&gt;
function Job(){
  EventEmitter.call(this);
  // custom initialization here
}
Job.prototype = new EventEmitter;&lt;p&gt;I find that this is the simplest way to inherit EventEmitter without using any utilities. To make it even simpler, the line &lt;code&gt;EventEmitter.call(this)&lt;/code&gt; is not strictly necessary since EventEmitter&#x60;s constructor doesn&amp;#39;t do anything - but people have been told to add this in just in case it ever does in the future.&lt;/p&gt;
&lt;p&gt;There are other flavors of inheriting EventEmitter. I will list them here in case you encounter them and get confused. So, in place of &lt;code&gt;Job.prototype = new EventEmitter&lt;/code&gt;, you could also:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Use an inheritance function like &lt;a href=&quot;http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor&quot;&gt;Node&amp;#39;s util.inherits&lt;/a&gt; or &lt;a href=&quot;https://github.com/component/inherit&quot;&gt;component/inherit&lt;/a&gt;: inherit(Job, EventEmitter)&lt;/li&gt;
&lt;li&gt;Use &lt;code&gt;__proto__&lt;/code&gt; but this is is not supported in IE 10 and older (I am partial to this one if I am doing Node-only stuff): Job.prototype.__proto__ = EventEmitter.prototype&lt;/li&gt;
&lt;li&gt;Mixin instead of inherit, i.e. copy over the methods, with an extend function like &lt;a href=&quot;https://github.com/Raynos/xtend&quot;&gt;xtend&lt;/a&gt; or &lt;a href=&quot;http://underscorejs.org/#extend&quot;&gt;_.extend&lt;/a&gt; or just write your own: extend(Job.prototype, EventEmitter.prototype)&lt;/li&gt;
&lt;li&gt;Built-in mixin capability as implemented by &lt;a href=&quot;https://github.com/component/inherit&quot;&gt;component/inherit&lt;/a&gt; EventEmitter(Job.prototype)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Regardless of which of the above you use, you can create a job with the &lt;code&gt;new&lt;/code&gt; operator&lt;/p&gt;
var job = new Job&lt;p&gt;and it is indeed an event emitter!&lt;/p&gt;
&lt;h2 id=&quot;where-to-get-it-&quot;&gt;Where To Get It?&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Node/Browserify - it&amp;#39;s built in.  var EventEmitter = require(&amp;#39;events&amp;#39;).EventEmitter&lt;/li&gt;
&lt;li&gt;Component - use &lt;a href=&quot;https://github.com/component/emitter&quot;&gt;component/emitter&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Bower or standalone - use &lt;a href=&quot;https://github.com/Wolfy87/EventEmitter&quot;&gt;Wolfy87/EventEmitter&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Some implementations have more extra features, but they will all support the basic features covered above.&lt;/p&gt;

    </content>
  </entry>
  
  <entry>
    <title>Component Part 2: Making Your Own</title>
    <author>Toby Ho</author>
    <link href="http://smalljs.org/package-managers/component-part-2/"/>
    <updated>2014-02-10T00:00:00.000Z</updated>
    <id>http://smalljs.org/package-managers/component-part-2/</id>
    <content>
      &lt;p&gt;This is our second &lt;a href=&quot;https://github.com/component/component/&quot;&gt;Component&lt;/a&gt; tutorial - a follow up to the &lt;a href=&quot;/package-managers/component-part-1&quot;&gt;first&lt;/a&gt;. This article will walk through how to make a component. There is a &lt;a href=&quot;#screencast&quot;&gt;screencast&lt;/a&gt; for this post as well for those who prefer watching over reading.&lt;/p&gt;
&lt;h2 id=&quot;why-make-a-component-&quot;&gt;Why Make A Component?&lt;/h2&gt;
&lt;p&gt;Why would one want to make a component? There are mainly two reasons:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;em&gt;Code organization&lt;/em&gt; - breaking up your application into small logical pieces allows other team members and future you navigate the code base more easily.&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Code sharing&lt;/em&gt; - if you find that an existing component in your application is applicable in another application you are building, it reduces the build cost of the new application. Furthermore, open sourcing the component opens up the possibility of code reuse with anyone in the world.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;With that, let&amp;#39;s make a &lt;em&gt;local component&lt;/em&gt; - for the purpose of code organization; and then we&amp;#39;ll make the component public - to share it with the world.&lt;/p&gt;
&lt;h2 id=&quot;setting-up&quot;&gt;Setting Up&lt;/h2&gt;
&lt;p&gt;To set up the project, create a new directory and within it create a &lt;code&gt;component.json&lt;/code&gt; file with these contents&lt;/p&gt;
{
  &amp;quot;name&amp;quot;: &amp;quot;My App&amp;quot;,
  &amp;quot;local&amp;quot;: [],
  &amp;quot;paths&amp;quot;: [&amp;quot;mycomponents&amp;quot;]
}&lt;p&gt;The &lt;code&gt;paths&lt;/code&gt; property tells Component where to search for local components. We&amp;#39;ve defined &lt;code&gt;mycomponents&lt;/code&gt; as the subdirectory where they will be located. Let&amp;#39;s create this directory:&lt;/p&gt;
mkdir mycomponents&lt;p&gt;The &lt;code&gt;local&lt;/code&gt; property is an explicit list of the local components which will be included in the build when we rebuild the components via &lt;code&gt;component build&lt;/code&gt;. It&amp;#39;s empty now because we don&amp;#39;t have any yet, so let&amp;#39;s make one.&lt;/p&gt;
&lt;h2 id=&quot;making-a-local-component&quot;&gt;Making A Local Component&lt;/h2&gt;
&lt;p&gt;In the &lt;a href=&quot;/package-managers/component-part-1&quot;&gt;last article&lt;/a&gt;, we created a &amp;quot;hello world button&amp;quot; - which when clicked, opens up a dialog box that says &amp;quot;Hello, world!&amp;quot;. To refresh your memory, we ended up with this code&lt;/p&gt;
&amp;lt;!doctype html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;Hello Dialog&amp;lt;/title&amp;gt;
  &amp;lt;link href=&amp;quot;build/build.css&amp;quot; rel=&amp;quot;stylesheet&amp;quot;&amp;gt;
  &amp;lt;script src=&amp;quot;build/build.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;h1&amp;gt;Hello Dialog&amp;lt;/h1&amp;gt;
  &amp;lt;button id=&amp;quot;button&amp;quot;&amp;gt;Open&amp;lt;/button&amp;gt;
  &amp;lt;script&amp;gt;
  var Dialog = require(&amp;#39;dialog&amp;#39;);
  var dom = require(&amp;#39;dom&amp;#39;);
  dom(&amp;#39;#button&amp;#39;).on(&amp;#39;click&amp;#39;, openDialog);

  function openDialog(){
    var dialog = new Dialog(&amp;#39;Hello World&amp;#39;, &amp;#39;Welcome human!&amp;#39;)
      .closable()
      .modal();
    dialog.show();
  }
  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;p&gt;The goal is to extract the button into a library so that we can require it, initialize it and attach it to the DOM, like this:&lt;/p&gt;
var HelloButton = require(&amp;#39;hello_button&amp;#39;);
var aButton = HelloButton();
aButton.appendTo(document.body);&lt;p&gt;We will create a skeleton for the component, use the &lt;code&gt;component create&lt;/code&gt; command with the &lt;code&gt;-l&lt;/code&gt; flag - for local.&lt;/p&gt;
component create mycomponents/hello_button -l&lt;p&gt;This will prompt you for a name, description and a whether it contains JS, CSS, and HTML - we&amp;#39;ll say yes to all three.&lt;/p&gt;
$ component create mycomponents/hello_button -l
name: hello_button
description: A hello world button.
does this component have js? ye 
does this component have css? y
does this component have html? y

  create : mycomponents/hello_button
  create : mycomponents/hello_button/index.js
  create : mycomponents/hello_button/template.html
  create : mycomponents/hello_button/hello_button.css
  create : mycomponents/hello_button/component.json&lt;p&gt;Note that some files have been created for you, including a JS file, a CSS file and an HTML file. It also created &lt;code&gt;mycomponents/hello_button/component.json&lt;/code&gt;. Open it up and we see this&lt;/p&gt;
{
  &amp;quot;name&amp;quot;: &amp;quot;hello_button&amp;quot;,
  &amp;quot;description&amp;quot;: &amp;quot;A hello world button.&amp;quot;,
  &amp;quot;dependencies&amp;quot;: {},
  &amp;quot;development&amp;quot;: {},
  &amp;quot;main&amp;quot;: &amp;quot;index.js&amp;quot;,
  &amp;quot;scripts&amp;quot;: [
    &amp;quot;index.js&amp;quot;
  ],
  &amp;quot;templates&amp;quot;: [
    &amp;quot;template.html&amp;quot;
  ],
  &amp;quot;styles&amp;quot;: [
    &amp;quot;hello_button.css&amp;quot;
  ]
}&lt;p&gt;The &lt;code&gt;scripts&lt;/code&gt;, &lt;code&gt;templates&lt;/code&gt; and &lt;code&gt;styles&lt;/code&gt; properties contain the paths to each file of interest - this is important. A component must explicitly list each Javascript file, template file, and stylesheet file that it needs.&lt;/p&gt;
&lt;p&gt;We will put the button&amp;#39;s markup in &lt;code&gt;template.html&lt;/code&gt;.&lt;/p&gt;
&amp;lt;button class=&amp;quot;hello_button&amp;quot;&amp;gt;Click me!&amp;lt;/button&amp;gt;&lt;p&gt;In &lt;code&gt;index.js&lt;/code&gt; we will &amp;quot;require&amp;quot; this template file:&lt;/p&gt;
var markup = require(&amp;#39;./template.html&amp;#39;);&lt;p&gt;&lt;em&gt;What?&lt;/em&gt; You can require an HTML file? Why yes. &lt;em&gt;Yes you can.&lt;/em&gt; During the build step, Component converts HTML files listed as templates to Javascript modules which returns a string containing the markup in the file. The idea is that you can use any templating engine you want to - simply an a build step to compile the template, but component has built-in support for the simplest templating engine of all: plain HTML. Also note that we are using a relative path to require the template - this is necessary when requiring another file within the same component.&lt;/p&gt;
&lt;p&gt;To create the button, we use the &lt;a href=&quot;https://github.com/component/dom&quot;&gt;dom component&lt;/a&gt;:&lt;/p&gt;
var dom = require(&amp;#39;dom&amp;#39;);
...
var button = dom(markup);&lt;p&gt;We now implement the component by extracting code from the previous example into &lt;code&gt;index.js&lt;/code&gt;, and exporting a function which creates and returns the button - in the CommonJS module system, this is done by assigning a value to &lt;code&gt;module.exports&lt;/code&gt;.&lt;/p&gt;
var template = require(&amp;#39;./template.html&amp;#39;);
var Dialog = require(&amp;#39;dialog&amp;#39;);
var dom = require(&amp;#39;dom&amp;#39;);

module.exports = function(){
  var button = dom(template)
    .on(&amp;#39;click&amp;#39;, openDialog);
  return button;
}

function openDialog(){
  var dialog = new Dialog(&amp;#39;Hello World&amp;#39;, &amp;#39;Welcome human!&amp;#39;)
    .closable()
    .modal();
  dialog.show();
}&lt;p&gt;Create a new test page&lt;/p&gt;
&amp;lt;!doctype html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;Hello Dialog&amp;lt;/title&amp;gt;
  &amp;lt;link href=&amp;quot;build/build.css&amp;quot; rel=&amp;quot;stylesheet&amp;quot;&amp;gt;
  &amp;lt;script src=&amp;quot;build/build.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;h1&amp;gt;Hello Dialog&amp;lt;/h1&amp;gt;
  &amp;lt;script&amp;gt;
  var HelloButton = require(&amp;#39;hello_button&amp;#39;);
  var aButton = HelloButton();
  aButton.appendTo(document.body);
  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;p&gt;If you rebuild and load the page now, you&amp;#39;ll get errors. There are two issue. First we need to specify the parent project&amp;#39;s dependency on &amp;quot;hello_button&amp;quot;. Also since it no longer directly require component/dom and component/dialog - those can be removed. Add &amp;quot;hello_button&amp;quot; to the main project&amp;#39;s &amp;quot;local&amp;quot; property, like so:&lt;/p&gt;
{
  &amp;quot;name&amp;quot;: &amp;quot;hello_component&amp;quot;,
  &amp;quot;paths&amp;quot;: [&amp;quot;mycomponents&amp;quot;],
  &amp;quot;local&amp;quot;: [&amp;quot;hello_button&amp;quot;],
  &amp;quot;dependencies&amp;quot;: {}
}&lt;p&gt;Next, establish hello_button&amp;#39;s dependency on component/dom and component/dialog: in &lt;code&gt;mycomponents/hello_button/component.json&lt;/code&gt; make sure you have:&lt;/p&gt;
...
&amp;quot;dependencies&amp;quot;: {
  &amp;quot;component/dom&amp;quot;: &amp;quot;*&amp;quot;,
  &amp;quot;component/dialog&amp;quot;: &amp;quot;*&amp;quot;
},
...&lt;p&gt;Re-install and then rebuild everything in the parent project directory&lt;/p&gt;
component install
component build&lt;p&gt;Reload the page and thing should work just like before.&lt;/p&gt;
&lt;p&gt;We have yet to make use of the CSS file in the hello_button component, so let&amp;#39;s do that. Let&amp;#39;s make this button fancy! In &lt;code&gt;mycomponents/hello_button/styles.css&lt;/code&gt; put&lt;/p&gt;
button.hello_button{
  color: red;
  font-family: Impact;
  font-size: 2em;
  background-color: green;
  border: 5px solid red;
}&lt;p&gt;Rebuild&lt;/p&gt;
component build&lt;p&gt;Aaaand BAM! Colors.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;./button.png&quot; alt=&quot;Hello Button&quot;&gt;&lt;/p&gt;
&lt;h2 id=&quot;auto-rebuilding&quot;&gt;Auto-Rebuilding&lt;/h2&gt;
&lt;p&gt;During the course of building this component, you might have had to type &lt;code&gt;component build&lt;/code&gt; quite a few times. This gets tedious, doesn&amp;#39;t it? Tj recommends using a C program called &lt;a href=&quot;https://github.com/visionmedia/watch&quot;&gt;watch&lt;/a&gt;, which simply reruns a supplied command every second. To install it&lt;/p&gt;
git clone git@github.com:visionmedia/watch.git
cd watch
make install&lt;p&gt;This installs the &lt;code&gt;watch&lt;/code&gt; command, and you can now do &lt;code&gt;watch component build&lt;/code&gt; from the project directory in a separate terminal, and not have to manually rebuild.&lt;/p&gt;
&lt;h2 id=&quot;making-it-public&quot;&gt;Making It Public&lt;/h2&gt;
&lt;p&gt;If you had wanted to make a public component in the beginning, you would have used the &lt;code&gt;component create&lt;/code&gt; command without the &lt;code&gt;-l&lt;/code&gt; flag - which will scaffold out some extra things for you in the project. But since we already have a working local component, we&amp;#39;ll just convert it to a public component.&lt;/p&gt;
&lt;p&gt;The main things you need for a public component which are not already present in a local component are&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&amp;quot;repo&amp;quot; property in &lt;code&gt;component.json&lt;/code&gt; - the Github repo path of the component.&lt;/li&gt;
&lt;li&gt;&amp;quot;version&amp;quot; property in &lt;code&gt;component.json&lt;/code&gt; - a version number becomes important when code becomes public and others depend on it.&lt;/li&gt;
&lt;li&gt;&amp;quot;license&amp;quot; property in &lt;code&gt;component.json&lt;/code&gt; - the open source license the component is under.&lt;/li&gt;
&lt;li&gt;A README.md file.&lt;/li&gt;
&lt;li&gt;All dependencies of the component must also be public components.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;We&amp;#39;ll move the component outside of the parent project:&lt;/p&gt;
mv mycomponents/hello_button ../hello_button
cd ../hello_button&lt;p&gt;Edit the &lt;code&gt;component.json&lt;/code&gt; to add some fields to it (replace &lt;code&gt;&amp;lt;github user&amp;gt;&lt;/code&gt; with your own Github username):&lt;/p&gt;
...
  &amp;quot;repo&amp;quot;: &amp;quot;&amp;lt;github user&amp;gt;/hello_button&amp;quot;,
  &amp;quot;version&amp;quot;: &amp;quot;0.0.1&amp;quot;,
  &amp;quot;license&amp;quot;: &amp;quot;MIT&amp;quot;,
...&lt;p&gt;Next add a &lt;code&gt;README.md&lt;/code&gt; (follow this or use your imagination):&lt;/p&gt;
Hello Button
============

A hello world button.

## Install

    component install &amp;lt;github user&amp;gt;/hello_button

## Usage

&#x60;&#x60;&#x60; js
var HelloButton = require(&amp;#39;hello_button&amp;#39;);
var button = HelloButton();
button.appendTo(document.body);
&#x60;&#x60;&#x60;&lt;p&gt;All dependencies of the button component are already public (component/dialog and component/dom), so we are good there. Now we are ready to publish! &lt;a href=&quot;https://github.com/new&quot;&gt;Create a new repo&lt;/a&gt; on Github and call it &lt;code&gt;hello_button&lt;/code&gt;. Then back in the terminal:&lt;/p&gt;
git init
git add .
git commit -m &amp;quot;First commit&amp;quot;
git remote add origin git@github.com:&amp;lt;github user&amp;gt;/hello_button.git
git push -u origin master&lt;p&gt;Voila! You&amp;#39;ve created your first component. But let&amp;#39;s make sure it works okay by installing within the parent project. Go back to the parent project, and remove &amp;quot;hello_button&amp;quot; from the &amp;quot;local&amp;quot; property of &lt;code&gt;component.json&lt;/code&gt;. If you &lt;code&gt;component build&lt;/code&gt; and reload the page, it should fail. Now, install your new public component&lt;/p&gt;
component install &amp;lt;github user&amp;gt;/hello_button
component build&lt;p&gt;Reload the page now, and it should work as before!&lt;/p&gt;
&lt;h2 id=&quot;adding-it-to-the-registry&quot;&gt;Adding It To The Registry&lt;/h2&gt;
&lt;p&gt;If this component were any useful, the next step would be to add it to the &lt;a href=&quot;https://github.com/component/component/wiki/Components&quot;&gt;Components Registry&lt;/a&gt; so that other people can find it. The registry is nothing but a wiki, so to add an entry amounts to clicking &amp;quot;Edit Page&amp;quot;, adding a link to your component&amp;#39;s project repo, and writing a brief description.&lt;/p&gt;
&lt;h2 id=&quot;screencast&quot;&gt;Screencast&lt;/h2&gt;
&lt;p&gt;Here&amp;#39;s this post in screencast form - &lt;em&gt;get your popcorn&lt;/em&gt;!&lt;/p&gt;
&lt;p&gt;&lt;iframe src=&quot;//player.vimeo.com/video/86339228&quot; width=&quot;500&quot; height=&quot;281&quot; frameborder=&quot;0&quot; webkitallowfullscreen mozallowfullscreen allowfullscreen&gt;&lt;/iframe&gt; &lt;p&gt;&lt;a href=&quot;http://vimeo.com/86339228&quot;&gt;Component Part 2&lt;/a&gt; from &lt;a href=&quot;http://vimeo.com/user1147567&quot;&gt;Toby Ho&lt;/a&gt; on &lt;a href=&quot;https://vimeo.com&quot;&gt;Vimeo&lt;/a&gt;.&lt;/p&gt;&lt;/p&gt;

    </content>
  </entry>
  
  <entry>
    <title>SuperAgent</title>
    <author>Toby Ho</author>
    <link href="http://smalljs.org/ajax/superagent/"/>
    <updated>2014-02-03T00:00:00.000Z</updated>
    <id>http://smalljs.org/ajax/superagent/</id>
    <content>
      &lt;p&gt;&lt;a href=&quot;http://visionmedia.github.io/superagent/&quot;&gt;SuperAgent&lt;/a&gt; is a light-weight, flexible and expressive Ajax library.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Note: SuperAgent has been loaded on this page! You can open up the dev console to try out the examples. The &lt;a href=&quot;http://developer.github.com/v3/&quot;&gt;Github APIs&lt;/a&gt; support CORS and so you can make Ajax requests to them directly from here.&lt;/em&gt;&lt;/p&gt;
&lt;h2 id=&quot;the-basics&quot;&gt;The Basics&lt;/h2&gt;
&lt;p&gt;All of the examples in SuperAgent&amp;#39;s documentation alias SuperAgent to &lt;code&gt;request&lt;/code&gt;, so I will follow suit. If you are using npm or component&lt;/p&gt;
var request = require(&amp;#39;superagent&amp;#39;);&lt;p&gt;If you are using it &lt;a href=&quot;https://github.com/visionmedia/superagent/blob/master/superagent.js&quot;&gt;standalone&lt;/a&gt;&lt;/p&gt;
var request = window.superagent;&lt;p&gt;Now, to make a simple &lt;code&gt;GET&lt;/code&gt; request&lt;/p&gt;
var url = &amp;#39;https://api.github.com/repos/visionmedia/superagent&amp;#39;;
request.get(url, function(response){
  console.log(&amp;#39;Response ok:&amp;#39;, response.ok);
  console.log(&amp;#39;Response text:&amp;#39;, response.text);
});&lt;p&gt;The response object is what you get back from the callback.&lt;/p&gt;
&lt;h2 id=&quot;response-object&quot;&gt;Response Object&lt;/h2&gt;
&lt;p&gt;The response object contains everything you&amp;#39;d need to know about what came back, including:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;status&lt;/code&gt; - HTTP status, plus meaningful boolean attributes based on it:&lt;ul&gt;
&lt;li&gt;&lt;code&gt;ok&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;clientError&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;serverError&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;accepted&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;noContent&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;badRequest&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;unauthorized&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;notAcceptable&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;notFound&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;forbidden&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;statusType&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;code&gt;text&lt;/code&gt; - unparsed response body string&lt;/li&gt;
&lt;li&gt;&lt;code&gt;body&lt;/code&gt; - parsed body, only present if response &lt;code&gt;Content-Type&lt;/code&gt; is &amp;quot;application/json&amp;quot; or &amp;quot;application/x-www-form-urlencoded&amp;quot;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;header&lt;/code&gt; or &lt;code&gt;headers&lt;/code&gt; - a map of response headers, note that header names are lowercased&lt;/li&gt;
&lt;li&gt;&lt;code&gt;error&lt;/code&gt; - an error object if not ok, with details&lt;/li&gt;
&lt;li&gt;&lt;code&gt;charset&lt;/code&gt; - character set of the response&lt;/li&gt;
&lt;li&gt;&lt;code&gt;req&lt;/code&gt; - the request object that originated this&lt;/li&gt;
&lt;li&gt;&lt;code&gt;xhr&lt;/code&gt; - the raw XMLHttpRequest object&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Having visited the response object, now let&amp;#39;s get into the meat of the library - the &lt;em&gt;request object&lt;/em&gt;.&lt;/p&gt;
&lt;h2 id=&quot;request-object&quot;&gt;Request Object&lt;/h2&gt;
&lt;p&gt;Let&amp;#39;s step back and look at the request object. A request object is returned by any call to the &lt;code&gt;request&lt;/code&gt; function or one of its convinience methods - consisting of &amp;quot;get&amp;quot;, &amp;quot;post&amp;quot;, and other HTTP verbs.&lt;/p&gt;
var req = request.get(url);&lt;p&gt;If you don&amp;#39;t supply a callback function, the request will not be sent out until you called the &lt;code&gt;end()&lt;/code&gt; method later&lt;/p&gt;
req.end(function(resp){
  console.log(&amp;#39;Got response&amp;#39;, resp.text);
});&lt;p&gt;There are a number of convinience methods too, let&amp;#39;s start with query parameters.&lt;/p&gt;
&lt;h2 id=&quot;query-parameters&quot;&gt;Query Parameters&lt;/h2&gt;
&lt;p&gt;The &lt;code&gt;query()&lt;/code&gt; method sets query parameters on the URL of the request.&lt;/p&gt;
req.query({id: 8});&lt;p&gt;or set it in string format&lt;/p&gt;
req.query(&amp;#39;id=8&amp;#39;);&lt;p&gt;You can call it multiple times and it will combine all of the parameters. This makes easy to set parameters conditionally - which is harder to do in jQuery:&lt;/p&gt;
if (search.category){
  req.query({category: search.category});
}
if (search.searchTerm){
  req.query({searchTerm: search.searchTerm});
}&lt;h2 id=&quot;method-chaining&quot;&gt;Method Chaining&lt;/h2&gt;
&lt;p&gt;In the tradition of jQuery, all methods on the request object are chainable (they return back the request object) to allow for a sort of &amp;quot;fluent syntax&amp;quot;.&lt;/p&gt;
request
  .get(&amp;#39;/post&amp;#39;)
  .query({id: 8})
  .end(function(resp){
    console.log(&amp;#39;Got post&amp;#39;, resp.body)
  });&lt;h2 id=&quot;sending-parameters&quot;&gt;Sending Parameters&lt;/h2&gt;
&lt;p&gt;Setting parameters on POST or PUT requests works similarly to query parameters, except you use the &lt;code&gt;send()&lt;/code&gt; method to do it:&lt;/p&gt;
request
  .post(&amp;#39;/submit&amp;#39;)
  .send({name: &amp;#39;tj&amp;#39;, pet: &amp;#39;tobi&amp;#39;})
  .end(function(resp){
    // ...
  });&lt;p&gt;By default, SuperAgent encodes the request body in JSON, which means in this case, you would see a request like&lt;/p&gt;
POST /submit HTTP/1.1
Host: somesite.com
Connection: keep-alive
Content-Length: 26
...
Content-Type: application/json

{&amp;quot;name&amp;quot;:&amp;quot;tj&amp;quot;,&amp;quot;pet&amp;quot;:&amp;quot;tobi&amp;quot;}&lt;p&gt;You can alternatively use form encoding to mimic submitting an HTML form&lt;/p&gt;
request
  .post(&amp;#39;/submit&amp;#39;)
  .type(&amp;#39;form&amp;#39;)
  .send({name: &amp;#39;tj&amp;#39;, pet: &amp;#39;tobi&amp;#39;})
  .end(function(resp){
    // ...
  });&lt;p&gt;then the request would be like&lt;/p&gt;
POST /submit HTTP/1.1
Host: somesite.com
Connection: keep-alive
Content-Length: 16
...
Content-Type: application/x-www-form-urlencoded

name=tj&amp;amp;pet=tobi&lt;h2 id=&quot;setting-headers&quot;&gt;Setting Headers&lt;/h2&gt;
&lt;p&gt;Setting a header is done with the &lt;code&gt;set()&lt;/code&gt; method&lt;/p&gt;
req.set(&amp;#39;Content-Type&amp;#39;, &amp;#39;application/json&amp;#39;);&lt;p&gt;but if you are setting the &lt;code&gt;Content-Type&lt;/code&gt;, there&amp;#39;s shorthand for that&lt;/p&gt;
req.type(&amp;#39;application/json&amp;#39;)&lt;p&gt;there&amp;#39;s also a shorthand for setting the &lt;code&gt;Accept&lt;/code&gt; header&lt;/p&gt;
req.accept(&amp;#39;application/json&amp;#39;)&lt;h2 id=&quot;aborting-and-timeouts&quot;&gt;Aborting and Timeouts&lt;/h2&gt;
&lt;p&gt;You can abort an in-flight request with the &lt;code&gt;abort()&lt;/code&gt; method. Or more conveniently, the &lt;code&gt;timeout(ms)&lt;/code&gt; method will abort a request after the specified number of milliseconds has passed without getting a response back.&lt;/p&gt;
&lt;h2 id=&quot;server-side-capabilities&quot;&gt;Server-Side Capabilities&lt;/h2&gt;
&lt;p&gt;SuperAgent also works on the server-side. In addition, it has some server-side specific features such as&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Handling redirects&lt;/li&gt;
&lt;li&gt;Piping to streams&lt;/li&gt;
&lt;li&gt;Multipart requests&lt;/li&gt;
&lt;li&gt;Handling attachments&lt;/li&gt;
&lt;li&gt;Compression&lt;/li&gt;
&lt;li&gt;CORS&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;learning-more&quot;&gt;Learning More&lt;/h2&gt;
&lt;p&gt;To learn more about SuperAgent, the best way is to check out &lt;a href=&quot;http://visionmedia.github.io/superagent/&quot;&gt;the docs&lt;/a&gt;.&lt;/p&gt;
&lt;script src=&quot;superagent.js&quot;&gt;&lt;/script&gt;
    </content>
  </entry>
  
  <entry>
    <title>Introduction to Component</title>
    <author>Toby Ho</author>
    <link href="http://smalljs.org/package-managers/component-part-1/"/>
    <updated>2014-01-24T00:00:00.000Z</updated>
    <id>http://smalljs.org/package-managers/component-part-1/</id>
    <content>
      &lt;p&gt;Hello, and welcome to the first post of Small.js! This post will cover the basics of &lt;a href=&quot;https://github.com/component/component&quot;&gt;Component&lt;/a&gt;. Component is a frontend Javascript package manager developed by the prolific Tj Holowaychuk. It embodies the philosophy of small modules and is designed to manage assets as well as Javascript. Currently, there exists over 1600 &amp;quot;components&amp;quot;. Although there are more popular JS package managers than Component, I chose to cover it first because I &lt;em&gt;love&lt;/em&gt; an underdog.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Update: There is a &lt;a href=&quot;#screencast&quot;&gt;screencast&lt;/a&gt; for this post as well for those who prefer watching over reading.&lt;/strong&gt;&lt;/p&gt;
&lt;h2 id=&quot;installing&quot;&gt;Installing&lt;/h2&gt;
&lt;p&gt;Before getting started, you&amp;#39;ll need to install &lt;a href=&quot;http://nodejs.org&quot;&gt;Node&lt;/a&gt; - which is a prerequisite of Component. Installing Node is as simple as clicking on &amp;quot;Download&amp;quot; on the Node website, and then running the installer. To verify you have successfully installed Node, run &lt;code&gt;node&lt;/code&gt; from the command line and see that the executable exists.&lt;/p&gt;
&lt;p&gt;Next, install Component using npm (sudo is required on some platforms)&lt;/p&gt;
npm install component -g&lt;p&gt;Component is installed! If you type &lt;code&gt;component&lt;/code&gt; you should see its usage info&lt;/p&gt;
&lt;p&gt;  Usage: component &lt;command&gt; [options]&lt;/p&gt;
&lt;p&gt;  Options:&lt;/p&gt;
-h, --help     output usage information
-V, --version  output the version number&lt;p&gt;  Commands:&lt;/p&gt;
install [name ...]      install one or more components
create [dir]            create a component skeleton
search [query]          search with the given query
convert &amp;lt;file ...&amp;gt;      convert html files to js modules
info &amp;lt;name&amp;gt; [prop]      output json component information
changes &amp;lt;name&amp;gt;          output changelog contents
wiki                    open the components list wiki page
build                   build the component
ls                      list installed components&lt;p&gt;Component has several commands. For this tutorial we&amp;#39;ll cover only &lt;code&gt;install&lt;/code&gt;, and &lt;code&gt;build&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id=&quot;create-a-project&quot;&gt;Create a Project&lt;/h2&gt;
&lt;p&gt;To create an application which uses components, all that&amp;#39;s required is that the root directory of the project contains a valid &lt;code&gt;component.json&lt;/code&gt; file. So let&amp;#39;s set these up&lt;/p&gt;
mkdir hello_component
cd hello_component&lt;p&gt;Next, create a file &lt;code&gt;component.json&lt;/code&gt; with the following content&lt;/p&gt;
{
  &amp;quot;name&amp;quot;: &amp;quot;hello_component&amp;quot;
}&lt;p&gt;Congratulations! Now, we can start installing components.&lt;/p&gt;
&lt;h2 id=&quot;installing-a-component&quot;&gt;Installing a Component&lt;/h2&gt;
&lt;p&gt;For demostration purposes, we&amp;#39;ll install the &lt;a href=&quot;https://github.com/component/dialog&quot;&gt;dialog component&lt;/a&gt;:&lt;/p&gt;
component install component/dialog&lt;p&gt;&lt;code&gt;component/dialog&lt;/code&gt; is simply an alias to the Github url: &lt;code&gt;https://github.com/component/dialog&lt;/code&gt;. All components are identified by their Github URL. Once you&amp;#39;ve installed dialog, you&amp;#39;ll notice that a &lt;code&gt;components&lt;/code&gt; directory was created, and that it contains a &lt;code&gt;component-dialog&lt;/code&gt; subdirectory plus a bunch of others&lt;/p&gt;
$ ls components
component-classes          component-indexof
component-css              component-matches-selector
component-delegate         component-overlay
component-dialog           component-query
component-dom              component-sort
component-domify           component-type
component-emitter          component-value
component-event&lt;p&gt;All the other components that were installed were installed because they are either a direct dependency or a transitive dependency of &lt;code&gt;component/dialog&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Also note that your &lt;code&gt;component.json&lt;/code&gt; has been doctored - a &amp;quot;dependencies&amp;quot; field has been added containing &lt;code&gt;component/dialog&lt;/code&gt;&lt;/p&gt;
&amp;quot;dependencies&amp;quot;: {
  &amp;quot;component/dialog&amp;quot;: &amp;quot;*&amp;quot;
}&lt;p&gt;keeping the dependencies in &lt;code&gt;component.json&lt;/code&gt; allows you to easily get back all the components you need even if you&amp;#39;ve deleted the &lt;code&gt;components&lt;/code&gt; directory, via the command: &lt;code&gt;component install&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Next, to test out the dialog, we need to build it.&lt;/p&gt;
&lt;h2 id=&quot;build-it&quot;&gt;Build It&lt;/h2&gt;
&lt;p&gt;In order to consume any components, you will need build them - which combines all of the components you&amp;#39;ve currently installed into a .js file and a .css file. Why CSS? Because components can contain CSS - dialog does.&lt;/p&gt;
component build&lt;p&gt;Now you should see a &lt;code&gt;build&lt;/code&gt; directory which contains a &lt;code&gt;build.js&lt;/code&gt; as well as a &lt;code&gt;build.css&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id=&quot;test-it&quot;&gt;Test It&lt;/h2&gt;
&lt;p&gt;The only other thing we need to do now is to create a test page that links these files&lt;/p&gt;
&amp;lt;!doctype html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;Hello Dialog&amp;lt;/title&amp;gt;
  &amp;lt;link href=&amp;quot;build/build.css&amp;quot; rel=&amp;quot;stylesheet&amp;quot;&amp;gt;
  &amp;lt;script src=&amp;quot;build/build.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;h1&amp;gt;Hello Dialog&amp;lt;/h1&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;p&gt;Sweet! Open it up in your browser, but nothing happens. Oops, we still need to write some Javascript. First let&amp;#39;s bring in the dialog component using the &lt;code&gt;require&lt;/code&gt; function&lt;/p&gt;
var Dialog = require(&amp;#39;dialog&amp;#39;);&lt;p&gt;Then make an &lt;code&gt;openDialog&lt;/code&gt; function which calls the dialog component API&lt;/p&gt;
function openDialog(){
  var dialog = new Dialog(&amp;#39;Hello World&amp;#39;, &amp;#39;Welcome human!&amp;#39;)
    .closable() // this adds an &#x60;x&#x60; button on the top right
    .modal()    // makes it a modal dialog

  dialog.show()
}&lt;p&gt;To activate this function, put a button on a page, and &lt;em&gt;just for now&lt;/em&gt;, use an onclick attribute&lt;/p&gt;
&amp;lt;button id=&amp;quot;button&amp;quot; onclick=&amp;quot;openDialog()&amp;quot;&amp;gt;Open&amp;lt;/button&amp;gt;&lt;p&gt;Refresh the page, click the button you should see a modal dialog!&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;dialog.png&quot; alt=&quot;Dialog Screenshot&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/airportyh/hello_component/blob/master/example1.html&quot;&gt;Full Source&lt;/a&gt;&lt;/p&gt;
&lt;h2 id=&quot;do-some-dom&quot;&gt;Do Some DOM&lt;/h2&gt;
&lt;p&gt;Using the &lt;code&gt;onclick&lt;/code&gt; attribute is ok for a quick toy example, but would be unsanitary for a real app, so let&amp;#39;s rewrite that in a cleaner way. jQuery time, right? &lt;em&gt;Not so fast!&lt;/em&gt; In the land of Component, instead of jQuery, we can use the much more light-weight &lt;a href=&quot;https://github.com/component/dom&quot;&gt;dom component&lt;/a&gt;&lt;/p&gt;
component install component/dom&lt;p&gt;Check your &lt;code&gt;component.json&lt;/code&gt; and make sure it contains &amp;quot;component/dom&amp;quot; as a dependency. There&amp;#39;s currently a &lt;a href=&quot;https://github.com/component/component/issues/465&quot;&gt;bug&lt;/a&gt; in Component that causes a dependency not to get added if it already exists in the &lt;code&gt;components&lt;/code&gt; directory. If it&amp;#39;s not there, just add it manually - so we should have&lt;/p&gt;
&amp;quot;dependencies&amp;quot;: {
    &amp;quot;component/dialog&amp;quot;: &amp;quot;*&amp;quot;,
    &amp;quot;component/dom&amp;quot;: &amp;quot;*&amp;quot;
}&lt;p&gt;rebuild the components&lt;/p&gt;
component build&lt;p&gt;Now, we can do this&lt;/p&gt;
var dom = require(&amp;#39;dom&amp;#39;);
...
dom(&amp;#39;#button&amp;#39;).on(&amp;#39;click&amp;#39;, openDialog);&lt;p&gt;Same result, but cleaner code! Very jQuery-like, no?&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/airportyh/hello_component/blob/master/example2.html&quot;&gt;Full Source&lt;/a&gt;&lt;/p&gt;
&lt;h2 id=&quot;finding-components&quot;&gt;Finding Components&lt;/h2&gt;
&lt;p&gt;How to know what components exist? You can peruse the &lt;a href=&quot;https://github.com/component/component/wiki/Components&quot;&gt;components wiki page&lt;/a&gt; - which in fact &lt;em&gt;is&lt;/em&gt; the official registry for components. Alternatively you can also use the &lt;code&gt;component search&lt;/code&gt; command, for example&lt;/p&gt;
component search dom&lt;p&gt;to search for all dom-related components.&lt;/p&gt;
&lt;h2 id=&quot;homework&quot;&gt;Homework&lt;/h2&gt;
&lt;p&gt;What&amp;#39;s that? &lt;em&gt;Ohhhh yes!&lt;/em&gt; Of course there&amp;#39;s homework! Don&amp;#39;t look so surprised. What? &lt;em&gt;Yes&lt;/em&gt;, you have to do it. If you don&amp;#39;t, everything you&amp;#39;ve learned thus far will be lost.&lt;/p&gt;
&lt;p&gt;Your homework is to browse the &lt;a href=&quot;https://github.com/component/component/wiki/Components&quot;&gt;registry&lt;/a&gt; and pick one that looks interesting to you. Then, you are going to install it and incorporate it into your code. Good luck!&lt;/p&gt;
&lt;h2 id=&quot;screencast&quot;&gt;Screencast&lt;/h2&gt;
&lt;p&gt;&lt;iframe src=&quot;//player.vimeo.com/video/86336598&quot; width=&quot;500&quot; height=&quot;281&quot; frameborder=&quot;0&quot; webkitallowfullscreen mozallowfullscreen allowfullscreen&gt;&lt;/iframe&gt; &lt;p&gt;&lt;a href=&quot;http://vimeo.com/86336598&quot;&gt;Component Part 1&lt;/a&gt; from &lt;a href=&quot;http://vimeo.com/user1147567&quot;&gt;Toby Ho&lt;/a&gt; on &lt;a href=&quot;https://vimeo.com&quot;&gt;Vimeo&lt;/a&gt;.&lt;/p&gt;&lt;/p&gt;

    </content>
  </entry>
  
</feed>