<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Brit Gardner &#187; javascript</title>
	<atom:link href="http://britg.com/topics/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://britg.com</link>
	<description>The big yellow one&#039;s the sun.</description>
	<lastBuildDate>Thu, 15 Mar 2012 14:33:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>SPDY and Its Relation to WebSockets</title>
		<link>http://britg.com/2012/03/15/spdy-and-its-relation-to-websockets/</link>
		<comments>http://britg.com/2012/03/15/spdy-and-its-relation-to-websockets/#comments</comments>
		<pubDate>Thu, 15 Mar 2012 13:58:50 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[html/css]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[spdy]]></category>
		<category><![CDATA[websockets]]></category>

		<guid isPermaLink="false">http://britg.com/?p=28393</guid>
		<description><![CDATA[When SPDY was first announced I didn&#8217;t pay too much attention as history has shown it takes years before these things become widely adopted, if ever. Recently though, Twitter launched support for the protocol and I noticed (via this Chrome plugin) that quite a few of the sites I visit on a regular basis (mostly [...]]]></description>
			<content:encoded><![CDATA[<p>When <a href="http://en.wikipedia.org/wiki/SPDY">SPDY</a> was first announced I didn&#8217;t pay too much attention as history has shown it takes years before these things become widely adopted, if ever. Recently though, <a href="http://www.webmonkey.com/2012/03/twitter-catches-the-spdy-train/">Twitter launched support</a> for the protocol and I noticed (via <a href="https://chrome.google.com/webstore/detail/mpbpobfflnpcgagjijhmgnchggcjblin">this Chrome plugin</a>) that quite a few of the sites I visit on a regular basis (mostly Google properties) are actually using SPDY in production.</p>
<p>Interesting. I guess it&#8217;s time to pay attention.</p>
<h3>But, WebSockets!</h3>
<p>My first question, without knowing too much about SPDY, was what its relation was to <a href="http://en.wikipedia.org/wiki/WebSocket">WebSockets</a> &#8212; are they two competing implementations solving the same problem? The short of it is: <em>No, they are complimentary and will coexist</em>. Here&#8217;s my best attempt to relate the two:</p>
<p><strong>SPDY</strong> is an augmentation to HTTP with the goal of making synchronous HTTP requests faster.</p>
<p><strong>WebSockets</strong> is an alternative to HTTP with the goal of facilitating <em>real time</em> communication.</p>
<p>The big point here being that SPDY shouldn&#8217;t require too much application-level refactoring, whereas supporting WebSockets means building an application specifically for bi-directional communication.</p>
<h3>Push</h3>
<p>A word often bandied about is <strong>push</strong> and it has two different meanings with these technologies.</p>
<p><strong>SPDY Push</strong> is a technique where more than just the requested resource is sent down the pipe to a browser, but within the context of a single request. Example: on a given HTML page there&#8217;s a good assumption that the corresponding .js and .css and a few images will be requested. SPDY can send all of these in a single request, eliminating quite a bit of RTT (round trip time).</p>
<p><strong>WebSockets Push</strong> facilitates asynchronous communication between the server and browser. The server receives new data from another source and rather than waiting for the browser to request the new data, it is simply pushed through an already-open connection.</p>
<h3>Complimentary</h3>
<p>The two protocols are actually complimentary. WebSockets makes its initial handshake with servers over HTTP to discover if the <code>ws://</code> protocol is supported, and one of SPDY&#8217;s primary methods of optimization is compressing and caching HTTP request headers.</p>
<p>From the <a href="http://www.chromium.org/spdy/spdy-whitepaper">SPDY Whitepaper</a></p>
<blockquote><p>Header compression resulted in an ~88% reduction in the size of request headers and an ~85% reduction in the size of response headers… We found a reduction of 45 &#8211; 1142 ms in page load time simply due to header compression.</p></blockquote>
<p>So, in an ideal future the RESTful request-based web is driven by SPDY, and all of the real-time communication and &#8220;app-ifying&#8221; is handled via WebSockets. Two peas in a pod!</p>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2012/03/15/spdy-and-its-relation-to-websockets/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Forging Forgecraft: Integrating CSS3 Transitions with Javascript</title>
		<link>http://britg.com/2012/01/15/forging-forgecraft-integrating-css3-transitions-with-javascript/</link>
		<comments>http://britg.com/2012/01/15/forging-forgecraft-integrating-css3-transitions-with-javascript/#comments</comments>
		<pubDate>Sun, 15 Jan 2012 16:01:01 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[gaming]]></category>
		<category><![CDATA[html/css]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[css3]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[forgecraft]]></category>

		<guid isPermaLink="false">http://britg.com/?p=26688</guid>
		<description><![CDATA[Forgecraft is a game currently in development using Ruby on Rails, Backbone.js, and all sorts of HTML5 buzzwords. Read an introduction here, and play the demo here. With Forgecraft, and any game really, there are usually quite a few animations running concurrently. I found these moments to be choppy, unresponsive and frustrating when they were [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://playforgecraft.com"><img src="http://britg.com.s3.amazonaws.com/forgecraft/logo-shadow.jpg" style="float: right; margin-left: 10px; margin-bottom: 10px; height: 45px;" /></a><em><a href="http://playforgecraft.com">Forgecraft</a> is a game currently in development using Ruby on Rails, Backbone.js, and all sorts of HTML5 buzzwords. Read an introduction <a href="http://britg.com/2011/12/29/forging-forgecraft-part-1-introduction/">here</a>, and play the demo <a href="http://playforgecraft.com">here</a>.</em></p>
<p>With Forgecraft, and any game really, there are usually quite a few animations running concurrently. I found these moments to be choppy, unresponsive and frustrating when they were implemented in javascript (especially on lower CPU environments like the iPad) and needed another solution. <a href="http://www.alistapart.com/articles/understanding-css3-transitions/">CSS3 transitions</a> were an obvious choice to check out, as they&#8217;ve been shown to be a great way to add a little pizzazz to a modern web app and can be executed natively (and even <a href="http://www.html5rocks.com/en/tutorials/speed/html5/#transanim">GPU accelerated</a>).</p>
<p><strong>But, can they provide the technical underpinnings for an interactive gamely element?</strong> To be effective in this context, they&#8217;d have to be:</p>
<ul>
<li>responsive, consistent and reliable</li>
<li>noticeably smoother than their javascript counterparts</li>
<li>simple to integrate with scripting</li>
</ul>
<p>Regarding the first 2 points, CSS3 transitions&#8217; effectiveness will really depend on your particular use-case. With Forgecraft they were definitely response, reliable, and smoother than javascript and I decided early on to use them in lieu of javascript wherever I could. But, I won&#8217;t go into the benchmarks and A/B comparisons in this article… perhaps later. Let&#8217;s just skip straight to the useful part:</p>
<h3>Product Intergortion <span style="font-size:12px"><em><a href="http://www.youtube.com/watch?v=CurP0BRHT9Y&#038;feature=endscreen&#038;NR=1" target="_blank">obscure 30 Rock reference &rarr;</a></em></span></h3>
<p>Integrating CSS3 transitions with the game&#8217;s scripting is pretty straight forward:</p>
<ul>
<li>Define transitions in CSS on your master element</li>
<li>Define classes with resulting properties changed</li>
<li>Trigger a class change using javascript</li>
<li>Listen for the transition-end event with javascript</li>
</ul>
<p>Of course, there are a few pitfalls with each of these steps that I&#8217;ll go into here. Let&#8217;s take an example from Forgecraft: the Bonus Strike event. Randomly while forging the player will see a bar pop-up like this:</p>
<p><img src="http://britg.com.s3.amazonaws.com/forgecraft/active-forge.jpg" style="width: 500px;" /></p>
<p>The bar moves from left-to-right and the player&#8217;s goal is to click the icon when the moving bar is directly under the target (large white) bar. The moving bar is animated with CSS3 transitions.</p>
<h4>Defining the CSS:</h4>
<p>We have a bar that needs an initial negative offset (the start position) that transitions to its final position. Simple enough: we define the base CSS on the <code>#bar</code> element and give it two classes (.new and .activated) defining each of its states. We also define the transition between the two states:</p>
<p><script src="https://gist.github.com/1616386.js?file=bar.css"></script><br />
<noscript><br />
#bar {<br />
  width: 600px;<br />
  height: 60px;</p>
<p>  position: relative;</p>
<p>  background-color: rgba(153, 153, 153, 0.3);<br />
  border-right: solid 5px white;</p>
<p>  -moz-transition-property: left;<br />
  -webkit-transition-property: left;<br />
  -o-transition-property: left;<br />
  transition-property: left;<br />
  -moz-transition-duration: 1.5s;<br />
  -webkit-transition-duration: 1.5s;<br />
  -o-transition-duration: 1.5s;<br />
  transition-duration: 1.5s;</p>
<p>}</p>
<p>#bar.new {<br />
  left: 0px;<br />
}</p>
<p>#bar.activated {<br />
  left: 600px;<br />
}<br />
</noscript></p>
<p><strong>One pitfall you may run into:</strong> for the animations to work in Firefox, you have to explicitly define the initial state for whatever property you are transitioning. In this example we are transitioning the <code>left</code> property of the <code>#bar</code> element. You normally wouldn&#8217;t define <code>left: 0;</code> &#8212; that&#8217;s the default! But Firefox requires this to trigger the transition when that property changes.</p>
<h4>Triggering the Animation in Javascript</h4>
<p>Using jQuery, we simply apply the classes that we defined in the CSS when we want to trigger the transition.</p>
<p><script src="https://gist.github.com/1616386.js?file=activate.js"></script><br />
<noscript><br />
$(&#8216;#bar&#8217;).removeClass(&#8216;new&#8217;).addClass(&#8216;activated&#8217;);<br />
</noscript></p>
<h4>Listening for the transition-end event</h4>
<p>CSS3 Transitions would be useless if we couldn&#8217;t get their context from within our scripting. Luckily, a series of events are fired in javascript while the transitions are running, just like you&#8217;d expect in a javascript-based animation. The primary event we care about is when the transition ends as you&#8217;ll most likely want to trigger callbacks.</p>
<p>Unfortunately, each browser vendor has decided to name these events differently… typical huh. <a href="http://www.modernizr.com/">Modernizr</a> to the rescue! (If you&#8217;re not using Modernizr, you should be. But that&#8217;s another blog post altogether).</p>
<p>There&#8217;s a hidden gem in the comments in the source code of Modernizr that explains how to use its <code><a href="http://www.modernizr.com/docs/#prefixed">.prefixed()</a></code> API to make a simple wrapper around the browser-specific transition event names. Here&#8217;s how I implemented it for the transition-end event. Feel free to use this wherever you need it:</p>
<p><script src="https://gist.github.com/1616386.js?file=transitionend.js"></script><br />
<noscript><br />
// Adapted from the Modernizer source comments</p>
<p>var transEndEventNames = {<br />
  &#8216;WebkitTransition&#8217; : &#8216;webkitTransitionEnd&#8217;,<br />
  &#8216;MozTransition&#8217;    : &#8216;transitionend&#8217;,<br />
  &#8216;OTransition&#8217;      : &#8216;oTransitionEnd&#8217;,<br />
  &#8216;msTransition&#8217;     : &#8216;msTransitionEnd&#8217;, // maybe?<br />
  &#8216;transition&#8217;       : &#8216;transitionEnd&#8217;<br />
}, </p>
<p>CSS3_TRANSITION_END = transEndEventNames[ Modernizr.prefixed('transition') ];<br />
</noscript></p>
<p>Bam, now we can use one simple event binding to handle all browsers:</p>
<p><script src="https://gist.github.com/1616386.js?file=listen.js"></script><br />
<noscript><br />
$(&#8216;#bar&#8217;).bind(CSS3_TRANSITION_END, function() {<br />
  //&#8230; do stuff<br />
});<br />
</noscript></p>
<h4>Stopping a Transition Early</h4>
<p>When the player hits the hammer-and-anvil icon during the Bonus Strike event, I needed to stop the animation early. The easiest way I found to do this, was to just set the animating property to its current value. The transition delta becomes 0, so the animation stops:</p>
<p><script src="https://gist.github.com/1616386.js?file=stop.js"></script><br />
<noscript><br />
$(&#8216;#bar&#8217;)css({ left: $(&#8216;#bar&#8217;).css(&#8216;left&#8217;) });<br />
</noscript></p>
<h3>Transition: End</h3>
<p>You may find that integrating CSS3 Transitions into your game makes your interactions smoother and more responsive, and with a simple API for scripting against transition events, developing against them should look and feel a lot like working in pure javascript.</p>
<hr />
<p><em>More Forging Forgecraft:</em></p>
<ul>
<li> <a href="http://britg.com/2011/12/29/forging-forgecraft-part-1-introduction/">Introducing Forgecraft</a></li>
<li> <a href="http://britg.com/2012/01/07/forging-forgecraft-a-hybrid-sql-mongodb-data-solution/">A Hybrid SQL MongoDB Data Solution</a></li>
</ul>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2012/01/15/forging-forgecraft-integrating-css3-transitions-with-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick Look: WebGL and Web Sockets</title>
		<link>http://britg.com/2010/01/10/quick-look-webgl-and-web-sockets/</link>
		<comments>http://britg.com/2010/01/10/quick-look-webgl-and-web-sockets/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 17:07:11 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[webgl]]></category>
		<category><![CDATA[websockets]]></category>

		<guid isPermaLink="false">http://britg.com/?p=1303</guid>
		<description><![CDATA[The internet is still a very young ecosystem of immature techn&#8230; Woah, the BS meter pegged there for a second. Forget the pontification, let me just spit out the two technologies that get me excited about billing myself as a Web Developer. WebGL This is a new spec that&#8217;s being developed by the Khronos Group [...]]]></description>
			<content:encoded><![CDATA[<p><strike>The internet is still a very young ecosystem of immature techn&#8230;</strike> Woah, the BS meter pegged there for a second.  Forget the pontification, let me just spit out the two technologies that get me excited about billing myself as a Web Developer.</p>
<h3>WebGL</h3>
<p>This is a new spec that&#8217;s being developed by the <a href="http://www.khronos.org/webgl/">Khronos Group</a> (the group behind OpenGL) to expose OpenGL to browsers through the canvas element.</p>
<p>Why is it exciting? Three words: <strong>Javascript</strong>. <strong>Hardware</strong>. <strong>Acceleration</strong>.  Damn, I need three more: <strong>In</strong>. <strong>The</strong>. <strong>Browser</strong>.</p>
<p>The concepts should speak for themselves, but if you still need some convincing follow the steps below and be sure to take a look at your CPU usage while running these demos.  (Hint: CPU usage will be very low because you&#8217;re riding your GPU).</p>
<ul>
<li>Grab the latest nighly of Chromium <a href="http://build.chromium.org/buildbot/snapshots/chromium-rel-xp/?C=M;O=D">here</a> if you are not already running it.</li>
<li>Start Chromium via the command line:
<ul>
<li>Windows: <code>chrome.exe --no-sandbox --enable-webgl</code></li>
<li>OSX: <code>Chromium.app/Contents/MacOS/Chromium --no-sandbox --enable-webgl</code></li>
<li>Linux: <code>./chrome --no-sandbox --enable-webgl</code></li>
</ul>
</li>
<li>Follow <a href="http://hacks.mozilla.org/2009/09/three-more-webgl-demos/">this link</a> to some examples of WebGL in action.</li>
</ul>
<p>Again, check your CPU usage while running the demos. It should be very low (if you have a GPU) as the demos should be hardware accelerated.</p>
<h3>Web Sockets</h3>
<p>Comet? Long-Polling? Forever Frame? In two years we will all be sitting around a trash barrel fire laughing about the days of yore when we had to use such hacks. </p>
<p>Why are we huddled around a trash barrel fire? Because it&#8217;s post-apocolyptic New Zealand, the last bastion of humanity. Anyways, that&#8217;s another &#8220;In This Decade&#8221; blog post&#8230;</p>
<p>From <a href="http://www.websockets.org/">websockets.org</a>:</p>
<blockquote><p>[The Web Socket Interface] defines a full-duplex communications channel that operates over a single socket and is exposed via a JavaScript interface in compliant browsers</p></blockquote>
<p>Here&#8217;s the <a href="http://www.w3.org/TR/2009/WD-websockets-20091222/">spec</a> in case you want to read it&#8230; haha, me neither.</p>
<p>Again, the concept here should speak for itself.  Two-way communication with web servers in an easy-to-use interface.</p>
<pre class="brush: jscript; title: ;">

var websock = new WebSocket(&amp;quot;ws://www.websocket.org&amp;quot;);

websock.onopen = function(evt) {
  console.log(evt)
  websock.send(&amp;quot;Hello Web Socket!&amp;quot;);
};
websock.onmessage = function(evt) {
  console.log(evt)
};
websock.onclose = function(evt) {
  console.log(evt)
};
websock.close();
</pre>
<p>Fortunately, there are already many projects implementing the web sockets protocol.  To name a few,</p>
<ul>
<li><a href="http://github.com/guille/node.websocket.js/">node.websocket.js</a></li>
<li><a href="http://github.com/igrigorik/em-websocket">em-websocket (Ruby)</a></li>
<li><a href="http://code.google.com/p/pywebsocket/">pywebsocket</a></li>
</ul>
<p>One thing to note is that the web socket protocol will adhere to the cross-domain security restriction that XHR has.  The good news is it will ship with support for server-side origin discretion using the same Origin headers in <a href="http://britg.com/2009/12/02/cross-origin-resource-sharing/">CORS</a>.</p>
<h3>It&#8217;s all about the gaming, stupid</h3>
<p>I&#8217;m going to predict that in 2 years, we will see current A quality games developed in-browser ontop of these two technologies.  Don&#8217;t get me wrong, AAA quality console and PC titles won&#8217;t be disrupted like the music and print industries any time soon.  But, the &#8220;casual&#8221; label on browser games will go away.</p>
<p>This is what has me really excited about being a web developer in this decade.  Parity with desktop development is inching closer, and all ontop of open technologies.</p>
<p>No plugins.  No corporate owner.</p>
<p>Win. Win.</p>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2010/01/10/quick-look-webgl-and-web-sockets/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Cross Origin Resource Sharing with Sinatra</title>
		<link>http://britg.com/2009/12/29/cross-origin-resource-sharing-with-sinatra/</link>
		<comments>http://britg.com/2009/12/29/cross-origin-resource-sharing-with-sinatra/#comments</comments>
		<pubDate>Tue, 29 Dec 2009 15:46:45 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[cors]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[sinatra]]></category>

		<guid isPermaLink="false">http://britg.com/?p=1282</guid>
		<description><![CDATA[It&#8217;s no lie that I think highly of the potential of Cross Origin Resource Sharing. One of the great things about it is that it doesn&#8217;t take much re-wiring of existing server (or client-side) apps to start working cross domain. Enabling your server app is as simple as including a few extra headers when you [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s no lie that <a href="http://britg.com/2009/12/02/cross-origin-resource-sharing/">I think highly</a> of the potential of Cross Origin Resource Sharing.  One of the great things about it is that it doesn&#8217;t take much re-wiring of existing server (or client-side) apps to start working cross domain.</p>
<p>Enabling your server app is as simple as including a few extra headers when you detect a cross origin request.  How do you know it&#8217;s a cross origin request?  You&#8217;ll see the <code>Origin:</code> header &#8212; all CORS requests will have it.  From there, response headers depend on the specifics of the request, but I won&#8217;t go over those here &#8212; check out the <a href="https://developer.mozilla.org/En/HTTP_access_control">Mozilla Developer Center treatment</a> for in-depth information.</p>
<p>I&#8217;ve been working with Sinatra a lot lately, so I put together <a href="http://github.com/britg/sinatra-cross_origin">an extension for Sinatra</a> that makes enabling Cross Origin requests even easier.</p>
<p><code>sudo gem install sinatra-cross_origin</code></p>
<p>There are two ways to use the extension: globally or per-route.</p>
<h3>Global</h3>
<p>For when you want to share all your endpoints cross-domain.</p>
<pre class="brush: ruby; title: ;">

require 'sinatra/base'
require 'sinatra/cross_origin'

class MyApp &amp;lt; Sinatra::Base
  register Sinatra::CrossOrigin

  enable cross_origin

  get '/' do
    &amp;quot;This is available to cross domain javascript requests automatically&amp;quot;
  end
end
</pre>
<h3>Per Route</h3>
<p>For when you want to share only some of your routes cross-domain.</p>
<pre class="brush: ruby; title: ;">

require 'sinatra/base'
require 'sinatra/cross_origin'

class MyApp &amp;lt; Sinatra::Base
  register Sinatra::CrossOrigin

  get '/' do
    cross_origin
    &amp;quot;This is available to cross domain javascript requests&amp;quot;
  end
end
</pre>
<h3>Configuration</h3>
<p>You can mix and match app-wide config and request specific config.</p>
<pre class="brush: ruby; title: ;">

require 'sinatra/base'
require 'sinatra/cross_origin'

class MyApp &amp;lt; Sinatra::Base
  register Sinatra::CrossOrigin

  configure do
    # Comma separate list of remote hosts that are allowed.
    # :any will allow any host
    set :allow_origin, :any

    # HTTP methods allowed
    set :allow_methods, [:get, :post]

    # Allow cookies to be sent with the requests
    set :allow_credentials, true
  end

  get '/' do
    # Only available to GET requests originating from
    # <a href="http://example.com" rel="nofollow">http://example.com</a>.  No cookies allowed.
    cross_origin :allow_origin =&amp;gt; '<a href="http://example.com&#039;" rel="nofollow">http://example.com&#039;</a>,
      :allow_methods =&amp;gt; [:get],
      :allow_credentials =&amp;gt; false
    &amp;quot;This is available to cross domain javascripts&amp;quot;
  end
end
</pre>
<p>Grab the source at Github: <a href="http://github.com/britg/sinatra-cross_origin">britg/sinatra-cross_origin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2009/12/29/cross-origin-resource-sharing-with-sinatra/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Scriptstack &#8211; Organize and Share Javascripts</title>
		<link>http://britg.com/2009/12/17/scriptstack-organize-and-share-javascripts/</link>
		<comments>http://britg.com/2009/12/17/scriptstack-organize-and-share-javascripts/#comments</comments>
		<pubDate>Thu, 17 Dec 2009 05:11:57 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[featured]]></category>

		<guid isPermaLink="false">http://britg.com/?p=1263</guid>
		<description><![CDATA[I&#8217;ve been hacking on a small project in my free time that I uploaded today: scriptstack. What is scriptstack? Well, if you&#8217;re like me you probably have 4 or 5 javascript files you include in just about every new project or site your start. jQuery. Tooltips. Lightbox. qTip. Or, you just put together a nice [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://scriptstack.com"><img src="http://britg.com/blog/wp-content/uploads/2009/12/scriptstack.png" alt="scriptstack" title="scriptstack" width="163" height="36" class="alignright size-full wp-image-1266" /></a>I&#8217;ve been hacking on a small project in my free time that I uploaded today: <a href="http://scriptstack.com">scriptstack</a>.</p>
<h3>What is scriptstack?</h3>
<p>Well, if you&#8217;re like me you probably have 4 or 5 javascript files you include in just about every new project or site your start.  jQuery.  Tooltips.  Lightbox. <a href="http://britg.com/2009/12/06/qtip-jquery-tooltip-plugin-with-excellent-docs/">qTip</a>. Or, you just put together a nice portfolio site for a client and you want to save that specific set of javascript plugins for the next time you do something similar.</p>
<p>Scriptstack aims to be an easy and social way to organize your &#8220;stacks&#8221; of scripts.  You can:</p>
<ul>
<li>Upload scripts.</li>
<li>Click and drag them into the order they should be loaded in the browser.</li>
<li>Tag them with a few keywords to make them indexable for future search.</li>
<li>Download the concatenated stack in minified or raw format.</li>
</ul>
<p>That&#8217;s about it for now, haha. Release early, release often, right?  I should note that there&#8217;s no permissions on the stacks.  If you create one, it&#8217;s editable by anyone right now.  I plan to add User accounts and ownership soon.</p>
<p><strong>Warning:</strong> the site probably only works in Firefox.</p>
<h3>Under the hood</h3>
<p>I took this opportunity to expand my horizons as far as the technology under the hood.  I&#8217;ll go in-depth on these as I continue to develop, but a quick rundown of the tech stack (<em>pun intended but probably shouldn&#8217;t be</em>):</p>
<ul>
<li><a href="http://mongodb.org">MongoDB</a> (via <a href="http://mongohq.com">MongoHQ</a>)</li>
<li><a href="http://github.com/jnunemaker/mongomapper">MongoMapper</a></li>
<li><a href="http://heroku.com">Heroku</a></li>
<li><a href="http://sinatrarb.com">Sinatra</a></li>
<li><a href="http://haml-lang.com">Haml</a></li>
<li><a href="http://compass-style.org/">Compass</a></li>
</ul>
<p>I also open sourced all the code that runs the site <a href="http://github.com/britg/scriptstack">here</a> incase you are interested in what poorly written Ruby looks like.</p>
<p>If you happen to check it out, let me know what you think!  And as I said, I will expand on different parts of it here in the near future, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2009/12/17/scriptstack-organize-and-share-javascripts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ajax Uploading Plus JSON Response Plus JSONView = Disaster</title>
		<link>http://britg.com/2009/12/11/ajax-uploading-plus-json-response-plus-jsonview-disaster/</link>
		<comments>http://britg.com/2009/12/11/ajax-uploading-plus-json-response-plus-jsonview-disaster/#comments</comments>
		<pubDate>Sat, 12 Dec 2009 04:17:51 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[ajax upload]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[jsonview]]></category>

		<guid isPermaLink="false">http://britg.com/?p=1249</guid>
		<description><![CDATA[So, I&#8217;ve spend the last few hours debugging what seemed to be a tear in the fabric of the universe. I&#8217;m working this excellent javascript library, AjaxUpload, that, as the name implies, creates a no-pageload form upload. It&#8217;s easy to implement and makes an upload infinitely more usable in my opinion; definitely check it out. [...]]]></description>
			<content:encoded><![CDATA[<p>So, I&#8217;ve spend the last few hours debugging what seemed to be a tear in the fabric of the universe.  I&#8217;m working this excellent javascript library, <a href="http://valums.com/ajax-upload/">AjaxUpload</a>, that, as the name implies, creates a no-pageload form upload.  It&#8217;s easy to implement and makes an upload infinitely more usable in my opinion; definitely check it out.</p>
<p>The upload works by pointing the <code>target</code> attribute of a multipart form at a hidden iframe.  When the iframe updates with the results of the upload, an event listener reports the response to the parent page, and voila &#8212; you have an upload without a page refresh.</p>
<p>The only problem with this iframe approach is that your response is being fully rendered by the browser instead of passed in the response body of an XMLHttpRequest like most ajax interactions.  Combine this with a server-side upload script that returns JSON and here&#8217;s where the fun starts.  </p>
<p>If you&#8217;re using the <a href="https://addons.mozilla.org/en-US/firefox/addon/10869">JSONView</a> Firefox plugin (and why the hell aren&#8217;t you!?) the JSON gets rendered with some wrapper html and styling to create an interactive and human readable version of the JSON.</p>
<p>See the problem here?  What gets reported to your upload-complete event listener isn&#8217;t the original JSON, but the HTML-wrapped JSON.  This can lead to what can only be described as multiple hours of FAIL in which you try and figure out why your JSON response can&#8217;t be parsed and used in your javascript.</p>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2009/12/11/ajax-uploading-plus-json-response-plus-jsonview-disaster/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>qTip &#8211; jQuery Tooltip Plugin with Excellent Docs</title>
		<link>http://britg.com/2009/12/06/qtip-jquery-tooltip-plugin-with-excellent-docs/</link>
		<comments>http://britg.com/2009/12/06/qtip-jquery-tooltip-plugin-with-excellent-docs/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 17:22:19 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[javascripts]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[tooltips]]></category>

		<guid isPermaLink="false">http://britg.com/?p=1189</guid>
		<description><![CDATA[The bar has been set on jQuery plugins by this simple yet very robust project: qTip. What is it? An easy way to create fancy tooltips that has (optional) customization options for just about anything you want to do. I had been using a pretty old and bland library before, so I was excited to [...]]]></description>
			<content:encoded><![CDATA[<p><div id="attachment_1191" class="wp-caption alignleft" style="width: 102px"><a href="http://craigsworks.com/projects/qtip/"><img src="http://britg.com/blog/wp-content/uploads/2009/12/logo_small.png" alt="qTip - jQuery Tooltips" title="logo_small" width="92" height="99" class="size-full wp-image-1191" /></a><p class="wp-caption-text">qTip - jQuery Tooltips</p></div>The bar has been set on jQuery plugins by this simple yet very robust project: <a href="http://craigsworks.com/projects/qtip/">qTip</a>.</p>
<p>What is it?  An easy way to create fancy tooltips that has (optional) customization options for just about anything you want to do.  I had been using a pretty old and bland library before, so I was excited to stumble on this one.</p>
<p>Example: a tooltip positioned at the bottom left of a selector, with a green color scheme and a little tip pointing to the selector.</p>
<pre class="brush: jscript; title: ;">
    $('#myselector').qtip({
        content: 'Eat my tooltip, sucker!',
        position: {
            corner: {
                target: &amp;quot;bottomLeft&amp;quot;,
                tooltip: &amp;quot;topLeft&amp;quot;
            },
            adjust: {
                x: 10,
                y: 10
            }
        },
        style: {
            name: &amp;quot;green&amp;quot;,
            tip: &amp;quot;topLeft&amp;quot;
        }
    });
</pre>
<p>Perhaps the best part of this plugin is the documentation.  Just <a href="http://craigsworks.com/projects/qtip/docs/">check them out</a> and tell me that&#8217;s not the most well-documented library you&#8217;ve ever seen.</p>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2009/12/06/qtip-jquery-tooltip-plugin-with-excellent-docs/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cross Origin Resource Sharing &#8211; AKA The Holy Grail</title>
		<link>http://britg.com/2009/12/02/cross-origin-resource-sharing/</link>
		<comments>http://britg.com/2009/12/02/cross-origin-resource-sharing/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 13:10:23 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[cors]]></category>
		<category><![CDATA[cross-domain]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[featured]]></category>
		<category><![CDATA[XHR]]></category>

		<guid isPermaLink="false">http://britg.com/?p=1106</guid>
		<description><![CDATA[Cross Origin Resource Sharing (CORS) is an emerging spec from the W3C that allows for cross-site XMLHTTPRequests.]]></description>
			<content:encoded><![CDATA[<p>The other day I was chatting with a guy about the overly restrictive <a href="http://en.wikipedia.org/wiki/Same_origin_policy">cross-domain request policy</a> and how silly it is given the pervasiveness of cross-domain apps on the web today. Most devs get around this restriction with hacks like jsonp or nested iframes anyways.  I told him that it&#8217;s high time we move past this archaic security measure and take web apps to the next level!</p>
<p>He just said, &#8220;Uh&#8230; do you want to upgrade your coffee to a venti for only 35 cents more?&#8221;  Always the salesman that guy&#8230;</p>
<h3>Cross Origin Resource Sharing</h3>
<p>Recently I stumbled across <a href="http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/">this article</a> on the excellent <a href="http://hacks.mozilla.org/">Mozilla Hacks</a> blog.  Cross Origin Resource Sharing (CORS). Sweet!  Finally a <em>true</em> implementation of cross-site XMLHttpRequests.</p>
<blockquote><p>The CORS standard works by adding new HTTP headers that allow servers to serve resources to permitted origin domains.</p></blockquote>
<p>They&#8217;re getting everything right with this one:</p>
<ul>
<li>it&#8217;s completely opt-in server-side, so browsers can implement CORS without opening up a bunch of security holes,</li>
<li>it uses the existing XMLHttpRequest object so current code can easily start working cross-domain,</li>
<li>and it&#8217;s totally transparent to the client-side developer &#8212; validation, pre-flighting, and access control is all handled within the XMLHttpRequest object without any additional code!</li>
</ul>
<p>Apparently it&#8217;s been in the works at the W3C for a couple of years (formerly known as &#8216;<a href="http://dev.w3.org/2006/waf/access-control/">Access Control</a>&#8216;). But only the most recent versions of Firefox and webkit based browsers are starting to support it.  Of course Microsoft, in their infinite wisdom, decided it would be best to implement their own spec, <a href="http://msdn.microsoft.com/en-us/library/cc288060%28VS.85%29.aspx">XDomainRequest</a>.  Some things never change&#8230;</p>
<h3>The Holy Grail</h3>
<p><div id="attachment_1114" class="wp-caption alignright" style="width: 160px"><img src="http://britg.com/blog/wp-content/uploads/2009/12/holy-grail-150x150.jpg" alt="Not the knights who say Ni" title="holy-grail" width="150" height="150" class="size-thumbnail wp-image-1114" /><p class="wp-caption-text">Not the knights who say Ni</p></div>Is this a big deal?  I&#8217;m going to go out on a limb here and say this is the holy grail of web development!</p>
<p>Why?  For one, there isn&#8217;t a good, non flash-based way to implement cross-domain long-polling/comet.  If there&#8217;s one thing that&#8217;s going to define the next generation of the web, it&#8217;s real-time apps.  CORS enables efficient real-time &#8220;mashups&#8221; (hate that term) that don&#8217;t rely on iframe hacks or flash.</p>
<p>Psh&#8230; cross-domain, real-time? Nothing more than a niche application, right?  Not so fast.  </p>
<p>The web will soon (if not already) start its industrial revolution.  A &#8220;building up&#8221; versus the &#8220;building out&#8221; if you will.  New web development will progressively become based around existing sites, rather than the creation of new sites.  A true cross-domain solution is vitally important to this.  </p>
<p>No, no, I&#8217;m not saying that people will stop creating new sites &#8212; that will always happen.  I&#8217;m saying startups will turn more and more to building apps targeted at sites users are already invested in instead of trying to get them to some new property.  </p>
<p>Examples:</p>
<ul>
<li>The <a href="http://disqus.com">Disqus</a> comment app on this blog.</li>
<li>The <a href="http://business.meebo.com/publishers/">Meebo Bar</a></li>
<li>Those little &#8216;Feedback&#8217; widgets you see all over sites now.</li>
</ul>
<p>A new ecosystem is emerging: apps built with web technologies that run on other sites.  But they&#8217;re mostly iframe based with all the restrictions that iframes have (no access to the DOM, slow, etc).  With CORS, developers can almost seemlessly develop apps cross-domain with all the power of same-domain scripting, making it the most important development to come along since the XMLHttpRequest!</p>
<p>In future posts I&#8217;ll delve into this &#8220;industrial revolution&#8221; of the web, but for now&#8230; back to that grail.</p>
<p><object width="445" height="364"><param name="movie" value="http://www.youtube.com/v/fIXByCAIzos&#038;hl=en_US&#038;fs=1&#038;color1=0x2b405b&#038;color2=0x6b8ab6&#038;border=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/fIXByCAIzos&#038;hl=en_US&#038;fs=1&#038;color1=0x2b405b&#038;color2=0x6b8ab6&#038;border=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="445" height="364"></embed></object></p>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2009/12/02/cross-origin-resource-sharing/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Server Side Javascript Continued &#8211; Node.js (plus example)</title>
		<link>http://britg.com/2009/07/01/server-side-javascript-continued-node-js-plus-example/</link>
		<comments>http://britg.com/2009/07/01/server-side-javascript-continued-node-js-plus-example/#comments</comments>
		<pubDate>Wed, 01 Jul 2009 13:00:50 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[comet]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[featured]]></category>
		<category><![CDATA[long-polling]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[server-side javascript]]></category>

		<guid isPermaLink="false">http://britg.com/?p=1025</guid>
		<description><![CDATA[Node's goal is to provide an easy way to build scalable network programs. ... Each connection is only a small heap allocation. This is in contrast to today's more common model where OS threads are employed for concurrency.]]></description>
			<content:encoded><![CDATA[<p><strong>Update:</strong> <em>Node&#8217;s APIs have change quite a bit since this post was made.  Check out the latest stuff at <a href="http://nodejs.org">nodejs.org</a>!</em></p>
<p>In my <a href="http://britg.com/2009/06/08/the-brave-new-world-of-server-side-javascript/">previous post on server-side javascript</a> (SSJ) I took a quick look at <a href="http://jackjs.org/">Jack</a>, a project that aims to implement the Rack/WSGI pattern for javascript. I still think this approach is great as it opens the door for more traditional Rails/Django-esque frameworks for SSJ.</p>
<p>But, lets face it, the next gen web is all about real-time interactivity, and current popular environments and servers just aren&#8217;t ideal for that.  It&#8217;s not their fault, up until recently we only cared about getting that request handled and out the door as quickly as possible with nothing shared between requests.  Unfortunately, it&#8217;s no longer just about number of requests/sec &#8212; we now need high concurrency, long-lasting connections, and shared persistence over these connections.</p>
<h3>Node.js</h3>
<p>Enter <a href="http://tinyclouds.org/node/">node.js</a> &#8211; a high performance javascript project built ontop of Google&#8217;s V8 runtime.  From the author&#8217;s description:</p>
<blockquote><p>Node&#8217;s goal is to provide an easy way to build scalable network programs. &#8230; Each connection is only a small heap allocation. This is in contrast to today&#8217;s more common model where OS threads are employed for concurrency.</p></blockquote>
<p>Nice, but does this pan out in implementation?  After spending a few days with Node, I truly believe that this will be the go-to project for the future of the real-time web.</p>
<h3>A Simple Game Lobby</h3>
<p>Let&#8217;s take a look at a simple example I put together.  The following is a very basic game lobby that is based on a more complex project I&#8217;m working on with node.  (You can checkout this script from <a href="http://github.com/britg/node-simple-lobby/tree/master">github</a> as well).</p>
<p>The script accepts new players through a url like <code>/join?player=joebob</code>.  Then, the client can long-poll the URL <code>/wait</code> and receive a notification in real-time when new players join!</p>
<p>First, lets define a couple of Arrays that will hold our persistence in-memory.</p>
<pre class="brush:js">// our in-memory list of player
var players = [];

// our in-memory list of players waiting
var waiting = [];</pre>
<p>Next, lets define a set of URLs our server will respond to.  Notice that the <code>/wait</code> response does not take place immediately.   Instead, the response is captured in a callback function that is held in-memory until it is called.  These callbacks are called whenever a new player hits the <code>/join</code> URL.</p>
<pre class="brush: jscript; title: ;">// define a set of paths that respond to requests
var paths = {

  /**
   * Requests to /join add players to our
   * player list, and fire off a notification
   * to all our waiting players
   **/
  &amp;quot;/join&amp;quot;: function(req, res) {

    // extract the player from the request
    var newPlayer = req.uri.params.player;

    // respond to this request with a list of players
    // already in the lobby
    server.respond(200, players);

    // add this player to list of players
    players.push(newPlayer);

    // notify all of our waiting players that
    // a new player has joined
    while(waiting.length &amp;amp;gt; 0) {
      waiting.shift().callback.apply(this, [newPlayer]);
    }
  },

  /**
   * Requests to /wait holds the connection
   * open until another player joins
   **/
  &amp;quot;/wait&amp;quot;: function(req, res) {

    // define our waiting player and the notification
    // callback to trigger when another player joins
    var waitingPlayer = {
      &amp;quot;player&amp;quot;: req.uri.params.player,
      &amp;quot;callback&amp;quot;: function(newPlayer) {
         server.respond(200, newPlayer);
       }
    };

    waiting.push(waitingPlayer);
  }
};</pre>
<p>Finally, we define our server.  We tell the server to map requests to the paths we defined above, and to listen on port 8000.</p>
<pre class="brush: jscript; title: ;">// Define a new HTTP Server
var server = node.http.createServer(function (req, res) {

  // tell our server to look at the paths definition above
  // for a responder to the request
  paths[req.uri.path].apply(this, [req, res]);

  // respond to a request
  function respond(status, obj) {
    var body = JSON.stringify(obj);
    res.sendHeader(status, [ [&amp;quot;Content-Type&amp;quot;, &amp;quot;text/json&amp;quot;]
                         , [&amp;quot;Content-Length&amp;quot;, body.length]
                         ]);
    res.sendBody(body);
    res.finish();
  }
});
server.listen(8000);
puts(&amp;quot;The game lobby has started!&amp;quot;);</pre>
<p>To run the script, first <a href="http://tinyclouds.org/node/#download">download and build node</a>, and then <a href="http://github.com/britg/node-simple-lobby/tree/master">download this script</a> from my repo.  Execute the script with:</p>
<p><code>&gt; node gamelobby.js</code></p>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2009/07/01/server-side-javascript-continued-node-js-plus-example/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>The Brave New World of Server-Side Javascript</title>
		<link>http://britg.com/2009/06/08/the-brave-new-world-of-server-side-javascript/</link>
		<comments>http://britg.com/2009/06/08/the-brave-new-world-of-server-side-javascript/#comments</comments>
		<pubDate>Mon, 08 Jun 2009 12:00:45 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[featured]]></category>
		<category><![CDATA[jack]]></category>
		<category><![CDATA[javscript]]></category>
		<category><![CDATA[jaxer]]></category>
		<category><![CDATA[narwhal]]></category>
		<category><![CDATA[server-side javascript]]></category>

		<guid isPermaLink="false">http://britg.com/?p=947</guid>
		<description><![CDATA[Every once in a while I hear whispers of server-side javascript and I get just as excited as the next person. But, I'll admit that until recently a phrase like "Javascript on Rails" was on the same level as a phrase like "McGyver vs. The A Team - The Movie." Fictonal. But awesome in theory.]]></description>
			<content:encoded><![CDATA[<div id="attachment_961" class="wp-caption alignright" style="width: 220px"><img class="size-medium wp-image-961" title="key_art_the_a_team" src="http://britg.com/blog/wp-content/uploads/2009/06/key_art_the_a_team-300x116.jpg" alt="Not the B Team" width="210" height="81" /><p class="wp-caption-text">Not the B Team</p></div>
<p>Every once in a while I hear whispers of server-side javascript and I get just as excited as the next person.  But, I&#8217;ll admit that until recently a phrase like &#8220;<em>Javascript on Rails</em>&#8221; was on the same level as a phrase like &#8220;<em>McGyver vs. The A Team &#8211; The Movie</em>.&#8221;  Fictonal.  But awesome in theory.</p>
<p>(<em>Don&#8217;t worry, they eventually join forces in the sequel</em>)</p>
<h3>But what about Jaxer?</h3>
<p>My limited experience with server-side javascript (SSJ) has been through <a href="http://aptana.com/jaxer">Jaxer</a>, from Aptana.  It touts some cool functionality, like loading the DOM server-side and built-in database drivers for MySQL, with the former allowing for DOM manipulation and integration with libraries like jQuery.</p>
<div id="attachment_968" class="wp-caption alignleft" style="width: 210px"><img class="size-full wp-image-968" title="jaxer-logo-icon" src="http://britg.com/blog/wp-content/uploads/2009/06/jaxer-logo-icon.png" alt="The extremely original Gear logo" width="200" height="83" /><p class="wp-caption-text">Ubiquitous &quot;Gear&quot; Logo</p></div>
<p>But, in its attempts to blur the lines between client and server execution, Jaxer has made sacrifices in its extensibility.  It is meant to be plugged into another system.  For instance, I don&#8217;t know of an easy way to expose data through a RESTful JSON/XML API (<em>like so many sites are doing nowadays</em>) using Jaxer alone.</p>
<p>What I&#8217;m really looking for in SSJ is something akin to the ecosystem surrounding languages like Ruby and Python.  That&#8217;s why I was pleasantly surprised to stumble accross a few projects that aim to do just that.</p>
<h3><strong>Narwhal</strong> &#8211; Javascript Standard Library and Interactive Console</h3>
<p>The foundation of any good ecosystem is a standard library.  Enter <a title="Narwhal" href="http://narwhaljs.org/">Narwhal</a>, &#8220;<em>a flexible javascript standard library</em>.&#8221;</p>
<p>There are a lot of things to like about this project, but the primary benefit is its attempts to play nice with multiple javascript runtimes like Rhino and V8cgi.  Also, this project is embracing <a title="ServerJS" href="https://wiki.mozilla.org/ServerJS">Mozilla&#8217;s ServerJS standard</a> which I think is important for its longevity and interoperability.</p>
<p>Setup is a breeze, you can simply clone the project from <a href="http://github.com/gmosx/narwhal/tree/master">github</a>:</p>
<p><code>git clone git://github.com/tlrobinson/narwhal.git</code></p>
<p>Once you add <code>narwhal/bin</code> to your $PATH, you can use the convenient symlink <code>js</code> to enter an interactive javascript console similar to <code>irb</code> or <code>python</code>.</p>
<h3><strong>Jack</strong> &#8211; Javascript&#8217;s &#8220;Rack&#8221;</h3>
<p>Interestingly enough, Narwhal came into existence as it&#8217;s author, <a href="http://tlrobinson.net/">Tom Robinson</a>, was working on <a href="http://jackjs.org/">Jack</a>.</p>
<blockquote><p>JSGI is a webserver interface for JavaScript inspired by Ruby’s Rack (<a href="http://rack.rubyforge.org/" rel="nofollow">http://rack.rubyforge.org/</a>) and Python’s WSGI (<a href="http://www.wsgi.org/" rel="nofollow">http://www.wsgi.org/</a>).</p>
<p>Jack is an implementation of JSGI compatible handlers (to connect to web servers), middleware (to intercept and manipulate requests to add functionality), and utilities (to make using JSGI easier).</p></blockquote>
<p>Setup is also breezy.  Simply clone Jack into the same directory you cloned Narwhal into:</p>
<p><code>git clone git://github.com/tlrobinson/jack.git</code></p>
<p>Since you&#8217;ve already added narwhal&#8217;s bin directory to your path, lets just make a symlink to <code>jackup</code> from there.</p>
<p>From your narwhal/bin directory:<br />
<code>ln -s [path/to/jack]/bin/jackup jackup</code></p>
<p>Run <code>jackup -h</code> for usage.</p>
<h3>So, what&#8217;s next? Where&#8217;s <em>Javascript on Rails</em>?</h3>
<p>With Narwhal and Jack, you can start writing basic web apps.  Looking at the <code>example.js</code> script in <code>jack/examples</code> we can see the basic request/response structure.  Looks familiar huh?</p>
<pre class="brush:js">var Jack = require("jack");

var map = {};

// an extremely simple Jack application
map["/hello"] = function(env) {
    return [200, {"Content-Type":"text/plain"}, ["Hello from " + env["SCRIPT_NAME"]]];
}

// apply the URLMap
var app = Jack.ContentLength(Jack.URLMap(map));
//...</pre>
<p>While these two pieces are a good start to a vibrant server-side javascript ecosystem, there&#8217;s still a long ways to go to before it&#8217;ll be on par with Ruby and Python.</p>
<p>What SSJ needs is its Django/Pylons/Rails/Merb.  There are a couple of projects I&#8217;ve found in the wild that are using Jack and Narwhal, but they appear to still be in very rapid flux.</p>
<p><a href="http://www.nitrojs.org/">Nitro</a></p>
<blockquote><p>Nitro provides a library of carefully designed middleware and utilities for creating scalable, standards-compliant Web Applications with JavaScript.</p></blockquote>
<p><a href="http://dev.helma.org/ng/">Helma NG</a></p>
<blockquote><p>Helma NG consists of several components that can be used together or alone:</p>
<p>1) A compact JavaScript runtime environment based on Mozilla Rhino. It adds<br />
to Rhino a reloading module system that is compatible to the ServerJS<br />
Securable Module proposal.</p>
<p>2) An interactive shell with support for autocompletion and history.</p>
<p>3) A module library implemented in JavaScript, covering basic functionality<br />
such as extensions to the built-in objects, file I/O, logging, persistence,<br />
client and server side HTTP support and more.</p></blockquote>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2009/06/08/the-brave-new-world-of-server-side-javascript/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

