<?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/tags/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://britg.com</link>
	<description>The big yellow one&#039;s the sun.</description>
	<lastBuildDate>Fri, 03 Feb 2012 05:08:39 +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>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>Forging Forgecraft Part 1: Introduction</title>
		<link>http://britg.com/2011/12/29/forging-forgecraft-part-1-introduction/</link>
		<comments>http://britg.com/2011/12/29/forging-forgecraft-part-1-introduction/#comments</comments>
		<pubDate>Thu, 29 Dec 2011 23:50:58 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[gaming]]></category>
		<category><![CDATA[coffeescript]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[forgecraft]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://britg.com/?p=26154</guid>
		<description><![CDATA[For the past few months I&#8217;ve been hacking away at a game partly, well, to make a game, and partly to play with a bunch of web technologies I&#8217;ve been interested in. That game is Forgecraft! Check it out and tell me what you think. What is Forgecraft? If you&#8217;ve played bejeweled you&#8217;ve got an [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://playforgecraft.com"><img src="http://britg.com.s3.amazonaws.com/forgecraft/intro.jpg" style="float: right; margin-left: 10px; margin-bottom: 10px;" /></a>For the past few months I&#8217;ve been hacking away at a game partly, well, to make a game, and partly to play with a bunch of web technologies I&#8217;ve been interested in. That game is <a href="http://playforgecraft.com">Forgecraft</a>! Check it out and tell me what you think.</p>
<h3>What is Forgecraft?</h3>
<p>If you&#8217;ve played bejeweled you&#8217;ve got an idea of the primary game mechanic: move gems into patterns. If you&#8217;ve played Minecraft you&#8217;ve got an idea of the gameplay twist: patterns. You&#8217;re not just matching 3, but moving ores into patterns that resemble weapons and armor. And finally, if you&#8217;ve played any loot-based game ever you&#8217;ve got an idea of reward structure: loot!</p>
<p>The target player is the casual player, but the game may also appeal to people who just like loot. And the target platforms are any modern web browser. Right now things are working ok in Chrome, Firefox, and Safari. Oh, and the game plays well as an installable web app on the iPad. In fact, all of the design decisions were made with this play mode in mind. Go ahead and save-to-homescreen on your iPad!</p>
<p><strong>Warning:</strong> It&#8217;s rough around the edges. There&#8217;s no tutorial and there may be bugs/features just flat out missing. I consider the game&#8217;s state as &#8216;playable demo.&#8217; But do let me know if you run into any bugs.</p>
<h3>The Tech</h3>
<p>Over the next few months I hope to put together a series of posts on the different technologies I played with while making Forgecraft. You know, go in-depth on each of them and all that jazz. For now, here&#8217;s just a run-down of the fun stuff I used:</p>
<h4>Back End</h4>
<ul>
<li>Hosted on <a href="http://heroku.com">Heroku</a> (Cedar stack)</li>
<li><a href="http://rubyonrails.org">Rails 3.1</a> with the asset pipeline</li>
<li><a href="http://mongodb.org">MongoDB</a></li>
</ul>
<h4>Front End</h4>
<ul>
<li>Haml/Sass through <a href="http://compass-style.org/">Compass</a></li>
<li><a href="http://jashkenas.github.com/coffee-script/">Coffeescript</a></li>
<li><a href="http://jquery.com">jQuery</a></li>
<li><a href="http://documentcloud.github.com/backbone/">Backbone.js</a></li>
<li><a href="http://twitter.github.com/bootstrap/">Bootstrap</a> from Twitter</li>
</ul>
<h4>HTML5 Buzzwords</h4>
<ul>
<li>CSS3 Animations</li>
<li>Web Audio API</li>
<li>History API / Pushstate API</li>
<li>iOS web-app installable</li>
</ul>
<p>My plan is to continue developing Forgecraft, expanding the items, mines, etc. and digging further into these emergent HTML5 technologies. I also would like to continue improving performance across the board. Things can get pretty choppy on the iPad when there are a lot of animations running at the same time.</p>
<p>Please, give <a href="http://playforgecraft.com">Forgecraft</a> a try and let me know how you like it and if you have any suggestions. The number one question I have is, is it fun? A game should be fun, I&#8217;m told.</p>
<hr />
<p><em>More Forging Forgecraft:</em></p>
<ul>
<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>
<li> <a href="http://britg.com/2012/01/15/forging-forgecraft-integrating-css3-transitions-with-javascript/">Integrating CSS3 Transitions with Javascript</a></li>
</ul>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2011/12/29/forging-forgecraft-part-1-introduction/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>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>Using a Location Proxy for URL Bindings in the Sammy Javascript Framework</title>
		<link>http://britg.com/2009/05/25/using-a-location-proxy-for-url-bindings-in-the-sammy-javascript-framework/</link>
		<comments>http://britg.com/2009/05/25/using-a-location-proxy-for-url-bindings-in-the-sammy-javascript-framework/#comments</comments>
		<pubDate>Mon, 25 May 2009 06:21:19 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[sammy]]></category>

		<guid isPermaLink="false">http://britg.com/?p=904</guid>
		<description><![CDATA[As I hinted in my previous post, the Sammy javascript framework is a great organization layer ontop of javascript heavy apps because it brings web developers back to familiar ground &#8211; the URL. But, there are occasions where we don&#8217;t want the actual URL in the browser to change, including the hash parameters. Why? Maybe [...]]]></description>
			<content:encoded><![CDATA[<p>As I hinted in my <a href="http://britg.com/2009/05/18/the-return-of-the-href-the-sammy-javascript-microframework/">previous post</a>, the Sammy javascript framework is a great organization layer ontop of javascript heavy apps because it brings web developers back to familiar ground &#8211; the URL.  But, there are occasions where we don&#8217;t want the actual URL in the browser to change, including the hash parameters.</p>
<p>Why?  Maybe we don&#8217;t want Back-button accessibility, or as in my case, we are running our scripts on a 3rd party domain and we want to minimize our impact.</p>
<p>So, how can we maintain the organization that URLs provide, but prevent the actual URL from changing?  Use a proxy!</p>
<p>You can find my fork of the Sammy project <a href="http://github.com/britg/sammy/tree/master">here</a>.</p>
<h3>Usage</h3>
<pre class="brush:js">
var app = $.sammy(function(){ with(this) {

  // denote that we will be using a location proxy
  use_location_proxy = true;

  get('#/home', function() {
    //... do something
  });

  //...
});</pre>
<p>And the corresponding link would look like:</p>
<pre class="brush: xml; title: ;">
&lt;a onclick=&quot;app.setLocation('#/home'); return false;&quot; href=&quot;#/home&quot;&gt;Home&lt;/a&gt;</pre>
<p>Even though we are preventing the URL from changing in the browser (with return false), the Sammy framework still activates the &#8216;#/home&#8217; routing.</p>
<p>Some things to note:  if you define <code>use_location_proxy</code> in your application, it will no longer listen to the browser URL.  Future versions may have more flexibility with this.</p>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2009/05/25/using-a-location-proxy-for-url-bindings-in-the-sammy-javascript-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Great, Another Internet Explorer</title>
		<link>http://britg.com/2009/01/27/great-another-internet-explorer/</link>
		<comments>http://britg.com/2009/01/27/great-another-internet-explorer/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 18:04:07 +0000</pubDate>
		<dc:creator>britg</dc:creator>
				<category><![CDATA[news]]></category>
		<category><![CDATA[ie8]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://britg.com/?p=758</guid>
		<description><![CDATA[Just saw an article on ZDNet in which they benchmark the javascript performance of IE8 RC1 with other browsers. Sadly, it looks like Microsoft&#8217;s javascript engine doesn&#8217;t perform very well at all. Having moved to primarily javascript development, my first reaction is to take my face and plant it firmly in my palm. I&#8217;m sure [...]]]></description>
			<content:encoded><![CDATA[<p>Just saw an article on ZDNet in which they benchmark the javascript performance of IE8 RC1 with other browsers.  Sadly, it looks like Microsoft&#8217;s javascript engine doesn&#8217;t perform very well at all.  Having moved to primarily javascript development, my first reaction is to take my face and plant it firmly in my palm.</p>
<p>I&#8217;m sure Microsoft will try to make up for this lack of speed with extremely aggressive caching&#8230;</p>
<div id="attachment_759" class="wp-caption aligncenter" style="width: 610px"><a href="http://www.zdnet.com.au/news/software/soa/Internet-Explorer-8-RC1-Photos/0,130061733,339294590-4s,00.htm"><img src="http://britg.com/wordpress/wp-content/uploads/2009/01/ie8-090127-1.jpg" alt="IE8 RC1 javascript performance courtesy of ZDNet" title="ie8-090127-1" width="600" height="254" class="size-full wp-image-759" /></a><p class="wp-caption-text">IE8 RC1 javascript performance courtesy of ZDNet</p></div>]]></content:encoded>
			<wfw:commentRss>http://britg.com/2009/01/27/great-another-internet-explorer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

