<?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>Calyptus Life</title>
	<atom:link href="http://blog.calyptus.eu/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.calyptus.eu</link>
	<description>Advanced web application development tactics - from scalability to UI design</description>
	<lastBuildDate>Wed, 28 Dec 2011 10:31:02 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Custom DateTime JSON Format for .NET JavaScriptSerializer</title>
		<link>http://blog.calyptus.eu/seb/2011/12/custom-datetime-json-serialization/</link>
		<comments>http://blog.calyptus.eu/seb/2011/12/custom-datetime-json-serialization/#comments</comments>
		<pubDate>Wed, 28 Dec 2011 09:21:32 +0000</pubDate>
		<dc:creator>Sebastian Markbåge</dc:creator>
				<category><![CDATA[Client Side]]></category>

		<guid isPermaLink="false">http://blog.calyptus.eu/?p=477</guid>
		<description><![CDATA[The DateTime serialization format in the built-in JSON serializer in .NET is particularly inconvenient as it requires a regular expression to parse and is not human-readable which makes debugging a pain.
ISO 8601
JSON doesn&#8217;t have a standard Date format per say. By design. Instead, the JavaScript defines toJSON methods so that objects can convert themselves to [...]]]></description>
			<content:encoded><![CDATA[<p>The DateTime serialization format in the built-in JSON serializer in .NET is particularly inconvenient as it requires a regular expression to parse and is not human-readable which makes debugging a pain.</p>
<p><strong>ISO 8601</strong></p>
<p>JSON doesn&#8217;t have a standard Date format per say. By design. Instead, the JavaScript defines toJSON methods so that objects can convert themselves to a JSON compatible format. The ECMAScript specification 5th Edition (15.9.5.4) defines that toJSON of a Date object should return a ISO 8601 formatted string in universal time (UTC). E.g: &#8220;2011-12-28T08:20:31.917Z&#8221;</p>
<p>This is a convenient format that specifically avoids confusion and ambiguity when passing it between systems. To turn it back into a Date object in JavaScript we can simply pass it to the Date constructor: E.g: Date(&#8220;2011-12-28T08:20:31.917Z&#8221;)</p>
<p><strong>Custom Serialization Using JavaScriptConverter</strong></p>
<p>.NET&#8217;s JavaScriptSerializer does provide an extension point for custom serialization. By calling RegisterConverters and passing custom JavaScriptConverter instances you can control how custom classes are serialized. APIs such as Script Services allow you to register such converters in Web.config. (AFAIK ASP.NET MVC doesn&#8217;t yet provide a hook to add JavaScriptConverters so you have to use <a href="http://weblogs.asp.net/rashid/archive/2009/03/23/submitting-my-first-bug-after-asp-net-mvc-1-0-rtm-release.aspx">a custom ActionResult</a>.)</p>
<p>Unfortunately the JavaScriptConverter API will only allow you to convert an object into another object (IDictionary&lt;string, object&gt;). Not into a custom string format.</p>
<p>It is at this point you might be looking for other serializers such as Json.NET. There are certainly many much faster and less crappy serializers out there. However, there is a benefit to using the built-in one. Mainly it may be already integrated into existing system that you can&#8217;t change. Luckily, as long as they allow you to register custom JavaScriptConverters I have the solution for you.</p>
<p><strong>The Hack</strong></p>
<p>The implementation of JavaScriptSerializer does string serialization for several types but Uri in particular. Uri is a class instead of a struct and fortunately is not sealed. That means we can inherit from it to implement the IDictionary&lt;string, object&gt; interface. That will allowing us to pass it in our custom JavaScriptConverter. Since it inherits from Uri it will be serialized as a string. It will do some URI encoding but this doesn&#8217;t affect the ISO 8601 format.</p>
<p>Deserialization is handled by the default implementation.</p>
<p>You can also use this hack to serialize custom enum types as strings instead of numbers or objects.</p>
<p><strong>The Code</strong></p>

<div class="wp_codebox"><table width="100%" ><tr id="p4772"><td class="code" id="p477code2"><pre class="javascript" style="font-family:monospace;">&nbsp;
<span style="color: #003366; font-weight: bold;">public</span> <span style="color: #003366; font-weight: bold;">class</span> DateTimeJavaScriptConverter <span style="color: #339933;">:</span> JavaScriptConverter
<span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">public</span> override object Deserialize<span style="color: #009900;">&#40;</span>IDictionary<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span> dictionary<span style="color: #339933;">,</span> Type type<span style="color: #339933;">,</span> JavaScriptSerializer serializer<span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">new</span> JavaScriptSerializer<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ConvertToType</span><span style="color: #009900;">&#40;</span>dictionary<span style="color: #339933;">,</span> type<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #003366; font-weight: bold;">public</span> override IDictionary<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span> Serialize<span style="color: #009900;">&#40;</span>object obj<span style="color: #339933;">,</span> JavaScriptSerializer serializer<span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #009900;">&#40;</span>obj <span style="color: #000066; font-weight: bold;">is</span> DateTime<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">new</span> CustomString<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>DateTime<span style="color: #009900;">&#41;</span>obj<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ToUniversalTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ToString</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;O&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #003366; font-weight: bold;">public</span> override IEnumerable<span style="color: #339933;">&lt;</span>Type<span style="color: #339933;">&gt;</span> SupportedTypes
  <span style="color: #009900;">&#123;</span>
    get <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">new</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">typeof</span><span style="color: #009900;">&#40;</span>DateTime<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #003366; font-weight: bold;">private</span> <span style="color: #003366; font-weight: bold;">class</span> CustomString <span style="color: #339933;">:</span> Uri<span style="color: #339933;">,</span> IDictionary<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">public</span> CustomString<span style="color: #009900;">&#40;</span>string str<span style="color: #009900;">&#41;</span>
      <span style="color: #339933;">:</span> base<span style="color: #009900;">&#40;</span>str<span style="color: #339933;">,</span> UriKind.<span style="color: #660066;">Relative</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">void</span> IDictionary<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span>.<span style="color: #660066;">Add</span><span style="color: #009900;">&#40;</span>string key<span style="color: #339933;">,</span> object value<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    bool IDictionary<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span>.<span style="color: #660066;">ContainsKey</span><span style="color: #009900;">&#40;</span>string key<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    ICollection<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;</span> IDictionary<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span>.<span style="color: #660066;">Keys</span>
    <span style="color: #009900;">&#123;</span>
      get <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    bool IDictionary<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span>.<span style="color: #660066;">Remove</span><span style="color: #009900;">&#40;</span>string key<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    bool IDictionary<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span>.<span style="color: #660066;">TryGetValue</span><span style="color: #009900;">&#40;</span>string key<span style="color: #339933;">,</span> out object value<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    ICollection<span style="color: #339933;">&lt;</span>object<span style="color: #339933;">&gt;</span> IDictionary<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span>.<span style="color: #660066;">Values</span>
    <span style="color: #009900;">&#123;</span>
      get <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    object IDictionary<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span>.<span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#91;</span>string key<span style="color: #009900;">&#93;</span>
    <span style="color: #009900;">&#123;</span>
      get
      <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
      set
      <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">void</span> ICollection<span style="color: #339933;">&lt;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;&gt;</span>.<span style="color: #660066;">Add</span><span style="color: #009900;">&#40;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span> <span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">void</span> ICollection<span style="color: #339933;">&lt;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;&gt;</span>.<span style="color: #660066;">Clear</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    bool ICollection<span style="color: #339933;">&lt;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;&gt;</span>.<span style="color: #660066;">Contains</span><span style="color: #009900;">&#40;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span> <span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">void</span> ICollection<span style="color: #339933;">&lt;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;&gt;</span>.<span style="color: #660066;">CopyTo</span><span style="color: #009900;">&#40;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> array<span style="color: #339933;">,</span> int arrayIndex<span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    int ICollection<span style="color: #339933;">&lt;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;&gt;</span>.<span style="color: #660066;">Count</span>
    <span style="color: #009900;">&#123;</span>
      get <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    bool ICollection<span style="color: #339933;">&lt;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;&gt;</span>.<span style="color: #660066;">IsReadOnly</span>
    <span style="color: #009900;">&#123;</span>
      get <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    bool ICollection<span style="color: #339933;">&lt;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;&gt;</span>.<span style="color: #660066;">Remove</span><span style="color: #009900;">&#40;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;</span> <span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    IEnumerator<span style="color: #339933;">&lt;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;&gt;</span> IEnumerable<span style="color: #339933;">&lt;</span>KeyValuePair<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">,</span> object<span style="color: #339933;">&gt;&gt;</span>.<span style="color: #660066;">GetEnumerator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    IEnumerator IEnumerable.<span style="color: #660066;">GetEnumerator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">throw</span> <span style="color: #003366; font-weight: bold;">new</span> NotImplementedException<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.calyptus.eu/seb/2011/12/custom-datetime-json-serialization/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Choosing JavaScript Module Dependency Syntax</title>
		<link>http://blog.calyptus.eu/seb/2011/10/choosing-a-javascript-module-syntax/</link>
		<comments>http://blog.calyptus.eu/seb/2011/10/choosing-a-javascript-module-syntax/#comments</comments>
		<pubDate>Sat, 08 Oct 2011 13:39:32 +0000</pubDate>
		<dc:creator>Sebastian Markbåge</dc:creator>
				<category><![CDATA[Client Side]]></category>

		<guid isPermaLink="false">http://blog.calyptus.eu/?p=414</guid>
		<description><![CDATA[TLDR This post is mainly a way for me to structure arguments and counter-arguments for various JavaScript module systems. You can jump to the bottom of the page for a matrix mapping features to various module systems. I&#8217;ll keep this page updated as new arguments are accepted or new module systems are invented, if they [...]]]></description>
			<content:encoded><![CDATA[<p><em>TLDR This post is mainly a way for me to structure arguments and counter-arguments for various JavaScript module systems. You can jump to the bottom of the page for a matrix mapping features to various module systems. I&#8217;ll keep this page updated as new arguments are accepted or new module systems are invented, if they add new benefits.</em></p>
<p><em>I make the assumption that you should always compile scripts together and gzip in production (possibly to multiple files). I make a second assumption that the complexity of such a build tool is irrelevant once it’s already developed. If you don&#8217;t accept these assumptions, the arguments below might be irrelevant or incomplete.</em></p>
<p><strong>Introduction</strong></p>
<p>JavaScript originally didn&#8217;t specify a way to work with source code in multiple different files, or across different modules in the same file. Recently we have seen many different ways to solve this approach mainstream JavaScript development. I&#8217;ll try to break them down and explain the reasoning for choosing between them in today&#8217;s JavaScript environments.</p>
<p>There are three primary attributes that a module system might include:</p>
<p><em>Module Isolation </em>- Code within a module should not leak in to the global scope shared by multiple modules.</p>
<p><em>Inter-module Dependency Definition</em> &#8211; There should be some syntax for defining dependencies between multiple source code files.</p>
<p><em>Script Loader </em>- Some how the application code from all relevant files must be loaded at runtime. The module system might use the same technique during development and release, but often you should treat them differently. In a production environment, your focus is on fast loading. In debug, your focus is on ease of use and mapping VM breakpoints and errors to readable source code.</p>
<p><em>Sandboxing and Inversion of Control</em> &#8211; This is currently a rarely used feature. It involves a way to load a module dependency graph in a different context or sandbox. It is an important part of dependency loading. It&#8217;s beyond the scope of this post, but it can be implemented together with any custom script loader.</p>
<p><strong>The Traditional JavaScript Library</strong></p>
<p>Traditionally JavaScript libraries handled module isolation by wrapping source code in a (function(){ &#8230; })() closure.</p>
<p>Inter-module Dependencies didn&#8217;t have a specific syntax. One module gained access to another through a namespace. A namespace was defined in the global scope. Modules could collide if the same namespace was used by two different modules.</p>
<p>On the web, loading of dependent files was managed by defining all application dependencies in a long list using &lt;script&gt; tags.</p>
<p>Note: If one &lt;script&gt; tag fails to load, others may still run. That means this model is fragile in a production environment. If one of your dependencies isn&#8217;t loaded, other code may still run. It might not be noticeable at first. You can see this with Chrome sometime. It uses various &#8220;smart&#8221; network techniques that sometimes fail to load a script dependency on a page, causing some features to break, sometimes in very bad ways.</p>
<p>In production, the best practice is to compile all these code files into a single minified and compressed JavaScript file. This ensures that all dependencies are loaded together, or not at all. It also makes sure the script is small by minifying the source. Putting it all into a single file makes good uses of GZIP compression and ensures minimal overhead from the transfer protocols.</p>
<p>The problem with the traditional approach is that there isn&#8217;t a specified way to define dependencies between various script files. Therefore it&#8217;s difficult to know what scripts need to be included to run a program and in what order they need to run. Together they form a dependency graph.</p>
<p><strong>Externally Defined Dependencies</strong></p>
<p>The module isolation is done as in traditional JavaScript libraries. The creation of the dependency graph and script loader is a little different though.</p>
<p>We can define the dependency graph in an external file. E.g. we can include a package file which defines references to all the files in a packages and how they relate to each other.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p41410"><td class="code" id="p414code10"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span>
  <span style="color: #3366CC;">'/MyDependentModule.js'</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">'/lib/StandAloneModule.js'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>
  <span style="color: #3366CC;">'/lib/StandAloneModule.js'</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>A custom script loader would first load a package file, then load and execute all scripts in the order they need to be executed. We can also add some asynchronous loading magic. This is the most efficient way to load scripts and easy to do.</p>
<p>It is easier to maintain than list of scripts because we don&#8217;t have to worry about the ordering of the scripts. The loader calculates that. On the down side, it&#8217;s still rather painful to maintain since you have a separate file that needs to be maintained when dependencies change.</p>
<p><strong>Inferred Dependencies</strong></p>
<p>You can try to infer the dependency graph by parsing the code and infer what global namespaces are defined in one file and what namespaces are used by another.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p41411"><td class="code" id="p414code11"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> MyGlobalModule <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> imported <span style="color: #339933;">=</span> MyOtherModule<span style="color: #339933;">;</span>
  ...
  <span style="color: #000066; font-weight: bold;">return</span> exports<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Since we&#8217;re not in a &#8220;with&#8221; statement we can infer the MyOtherModule must be in the global scope. Since we&#8217;re not defining it, someone else must be. Therefore we have a dependency on what ever file defines MyOtherModule.</p>
<p>Modules that don&#8217;t define a new object but rather extend existing ones (monkey patching) doesn&#8217;t necessarily have an exports. You can easily add an empty object to create a dependency on these pseudo-modules.</p>
<p>One problem with this approach is that we need to have a list of all files available. Then pre-parse them so that we can see which files are used and in what order they need to be executed. This is easy enough for a local compiler. It can just scan all files in a directory. An in-browser script loader for use during development can&#8217;t list files though.</p>
<p>One way to solve this is to have a convention where the name of a global variable maps to the name of a file. That way we can also infer the name and location of the file.</p>
<p>This technique hasn&#8217;t gained much traction. Possibly because it takes some effort to make the tools. Once the tooling is done, that&#8217;s not an argument not to use it.</p>
<p><strong>Comment Defined Dependencies</strong></p>
<p>Instead of inferring our dependencies using a convention, we define them in a comment within the source file.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p41412"><td class="code" id="p414code12"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// @requires /lib/MyOtherModule.js</span>
<span style="color: #003366; font-weight: bold;">var</span> MyGlobalModule <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> imported <span style="color: #339933;">=</span> MyOtherModule<span style="color: #339933;">;</span>
  ...
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">export</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The script loader can load the script file using XHR. Then parse the file&#8217;s comments to see what dependencies it has. Then load the dependency using XHR etc. After the dependency graph has been loaded this way, they can be executed in order using &lt;script&gt; tags.</p>
<p>This has the added benefit that the file names doesn&#8217;t necessarily need to correspond to global object names.</p>
<p>This is also easy to implement which is why it has gained more traction than inferred dependencies.</p>
<p><strong>Synchronous Module Definition (CommonJS)</strong></p>
<p>The CommonJS wiki originally defined a synchronous API to load dependencies in non-browser environments. Module isolation between files is built-in. So, the global scope isn&#8217;t shared. Only exported properties are shared.</p>
<p>Inter-module dependencies are defined using a synchronous API. You call the global require function passing a string argument representing the name of another source file.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p41413"><td class="code" id="p414code13"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> imported <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'lib/MyOtherModule'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
...
<span style="color: #660066;">exports</span>.<span style="color: #660066;">myExport</span> <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>These modules can be used as is, in Node.js and other CommonJS compatible implementations. (Much fewer than JavaScript compatible environments since CommonJS is not a formal standard.)</p>
<p>This model can be used in a browser environment using a custom script loader. The script loader can use XHR to load the script, parse the require statements, load the next script, parse it and build the dependency graph.</p>
<p>To actually execute modules in isolation, you need to wrap them in some custom closure. Then the code is executed by inject the new code into script tags.</p>
<p><strong>CommonJS Hybrids</strong></p>
<p>To make a script compatible with both CommonJS and the traditional model you can use a hybrid model. Your source file checks for existence of CommonJS require/exports and uses them if available, otherwise it falls back on the traditional model. This makes source code directly compatible with CommonJS and the traditional model out-of-the-box.</p>
<p><strong>Define Block</strong></p>

<div class="wp_codebox"><table width="100%" ><tr id="p41414"><td class="code" id="p414code14"><pre class="javascript" style="font-family:monospace;">define<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>require<span style="color: #339933;">,</span> exports<span style="color: #339933;">,</span> module<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> imported <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'lib/MyOtherModule'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  ...
  <span style="color: #660066;">exports</span>.<span style="color: #660066;">myExport</span> <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The define() statement that enables async running. That&#8217;s half way to AMD. This solves some debugging issues in current browsers. However, it doesn&#8217;t support defining the dependency list before running the code. Therefore the loaders still won&#8217;t work automatically in browser environments.</p>
<p>UPDATE: This was supported in Node.js for a while but is no longer supported in 0.5.x.</p>
<p><strong>Asynchronous Module Definition (AMD)</strong></p>
<p>Asynchronous Module Definition combines module-isolation, dependency definitions and script-loading into one tool, to make it easier to use the code in the browser.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p41415"><td class="code" id="p414code15"><pre class="javascript" style="font-family:monospace;">define<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #3366CC;">'MyOtherModule'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>imported<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
...
<span style="color: #000066; font-weight: bold;">return</span> exports<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>This requires a custom loader. The custom loader is efficient than the custom loaders used by Infered Dependencies, Comment Defined Dependencies and Synchronous Module Definitions. It can also work with Cross-Site Scripting (XSS) dependencies without the Cross-Origin Resource Sharing protocol (CORS). However, the Externally Defined dependency graph is even more efficient.</p>
<p>It is possible to create and AMD/CommonJS/Traditional hybrid that supports all formats directly from source. This requires a lot of boilerplate code and is not easy to maintain.</p>
<p><strong>ECMAScript.Next Modules</strong></p>
<p>The ECMAScript Harmony proposals include a new syntax for defining modules. This will probably be in ECMAScript.Next (probably ECMAScript 6).</p>
<p>All module scope will be isolated by default. Dependencies are defined using a new syntax. The new syntax ensures that module dependencies can be statically inferred (without relying on convention).</p>

<div class="wp_codebox"><table width="100%" ><tr id="p41416"><td class="code" id="p414code16"><pre class="javascript" style="font-family:monospace;">module importedModule from <span style="color: #3366CC;">&quot;MyOtherModule.js&quot;</span><span style="color: #339933;">;</span>
...
<span style="color: #003366; font-weight: bold;">export</span> myExport<span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Just like Synchronous Module Definitions, this requires code rewriting. The custom script loader will execute the rewritten code after all dependencies has been loaded.</p>
<p>This syntax has the added advantage of all the other ECMAScript.Next syntax that you can use as well.</p>
<p><strong>Static Compilation</strong></p>
<p>All systems except (A)synchronous Module Definitions and Infered Dependencies allow dynamic naming of modules based on some programmatic logic. I.e. you can call the require function with a variable require(selectedModule + &#8216;/subComponent&#8217;); Don&#8217;t do this. If you do, you can&#8217;t statically infer the dependencies and you can&#8217;t compile your script together without executing it. I&#8217;m going to assume the convention to always define a constant string.</p>
<p>Regardless of what syntax you use for defining dependencies, you can use a compiler and minifier to package them up. There are some benefits of using a custom script loader even in production because you can load scripts in parallell and from several servers. The best way is to use an Externally Defined Dependency Graph. That way, you can start loading files without first loading the files that dependent upon them.</p>
<p>Asynchronous Module Definition (AMD) by definition includes a fairly efficient script loader for the browser. You may be tempted to use it as-is in production. However, you should package related files together and at least minify them (as stated above). Therefore you&#8217;re already introducing a compilation step. That compilation step can be used to turn any other syntax into AMD or better yet, generate an Externally Defined Dependency Graph.</p>
<p>Because you should <strong>never</strong> put raw source code in a production web app, all syntaxes are equals in terms of production browser script loading. However, during development you may well want to load source code without a compilation step and different syntaxes can provide some advantages there.</p>
<p><strong>Choosing Module Dependency Syntax</strong></p>
<table class="compatibility" style="margin: auto;" border="0" cellspacing="1" cellpadding="0">
<tbody>
<tr class="top-head">
<td></td>
<th><span>Traditional</span></th>
<th><span>External</span></th>
<th><span>Comment</span></th>
<th><span>Inferred</span></th>
<th><span>CommonJS</span></th>
<th><span>Hybrid</span></th>
<th><span>Define Block</span></th>
<th><span>AMD</span></th>
<th><span>AMD Hybrid</span></th>
<th><span>ES.Next</span></th>
</tr>
<tr>
<th><span>Easily Maintained / Clean Syntax</span></th>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: yellow;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
<td style="background: lime;"></td>
</tr>
<tr>
<th><span>Source Compatible with Traditional Model</span></th>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
</tr>
<tr>
<th><span>Source Compatible with Node.js (Out-of-the-box)</span></th>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
</tr>
<tr>
<th><span>Analysis/Completion Tooling in Current IDEs</span></th>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
<td style="background: yellow;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: yellow;"></td>
<td style="background: red;"></td>
</tr>
<tr>
<th><span>Debugging in WebKit</span></th>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
</tr>
<tr>
<th><span>Debugging in Other Browsers</span></th>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: yellow;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: yellow;"></td>
</tr>
<tr>
<th><span>XSS Development Loader using CORS</span></th>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
</tr>
<tr>
<th><span>XSS Development Loader without CORS</span></th>
<td style="background: lime;"></td>
<td style="background: yellow;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
</tr>
<tr>
<th><span>file:// Protocol Development Loader</span></th>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
</tr>
<tr>
<th><span>Fast Development Loader (Large Code Base, Cold Start)</span></th>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: yellow;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: red;"></td>
</tr>
<tr>
<th><span>Fast Production Loader</span></th>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
<td style="background: lime;"></td>
</tr>
<tr>
<th><span>ES.Next Features (Classes, Destructuring etc.)</span></th>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: red;"></td>
<td style="background: lime;"></td>
</tr>
</tbody>
</table>
<p>For me, maintainability and less boilerplate is important. Therefore the Traditional, External and AMD Hybrid model are not acceptable.</p>
<p>The main reason to choose the AMD syntax is if you have a very large code base. For those cases, pre-parsing may be slow during development. You can also cache pre-parsed dependencies so that only changed files are updated. This means the others can be fast the second time you run a large code base in development.</p>
<p>Another case to use AMD is if you need cross-site scripting dependency support in IE6/7 or against a third-party server without CORS support, during development. This is a much more esoteric use-case. I&#8217;ve had the need for it, but not during development. Only in production, and then we&#8217;re only using compiled code.</p>
<p>If you do need source compatibility with the traditional model and/or CommonJS, then choose either Inferred, CommonJS or the Hybrid model. This doesn&#8217;t require your users to download a separate bootstrapper to run your source.</p>
<p>If you accept that you require a bootstrapper. Then you can use the ES.Next model which gives you the added benefit of many new syntax features. There is a problem debugging code that is rewritten on-the-fly in some WebKit Inspector implementations. This is a passing problem and we&#8217;ll soon have full symbol mapped debugging for new source languages.</p>
<p>In fact, all the problems with the ES.Next model are likely a passing problems while the other&#8217;s remain. It&#8217;s going to be the model to replace them all in the long term.</p>
<p>If you have more module syntaxes or more arguments for one model over another, please drop a comment. A lot of times we base our decisions on intuition rather than reasoned arguments. I&#8217;ve tried to break it down without intuitive arguments (like &#8220;it feels cleaner or feels simpler&#8221;).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.calyptus.eu/seb/2011/10/choosing-a-javascript-module-syntax/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Simple Browser Icons</title>
		<link>http://blog.calyptus.eu/seb/2011/09/simple-browser-icons/</link>
		<comments>http://blog.calyptus.eu/seb/2011/09/simple-browser-icons/#comments</comments>
		<pubDate>Tue, 13 Sep 2011 21:25:14 +0000</pubDate>
		<dc:creator>Sebastian Markbåge</dc:creator>
				<category><![CDATA[Client Side]]></category>

		<guid isPermaLink="false">http://blog.calyptus.eu/?p=403</guid>
		<description><![CDATA[For the conversion tool from SVG path to CSS animations I needed a selector for vendor prefixes. I decided to use the browser&#8217;s logos.
High resolution and vector versions are readily available for all the browser logos. Unfortunately they don&#8217;t look very good in small icons. They&#8217;re also very colorful which tend to attract the eye [...]]]></description>
			<content:encoded><![CDATA[<p>For the <a href="http://blog.calyptus.eu/seb/2011/09/csspathanimation/">conversion tool from SVG path to CSS animations</a> I needed a selector for vendor prefixes. I decided to use the browser&#8217;s logos.</p>
<p>High resolution and vector versions are readily available for all the browser logos. Unfortunately they don&#8217;t look very good in small icons. They&#8217;re also very colorful which tend to attract the eye of the user. Especially in a simple design.</p>
<p>I couldn&#8217;t find any simplified versions of the logos so I decided to roll my own. You&#8217;re welcome to use it if you want.</p>
<p>Here&#8217;s the result:</p>
<p><a href="/wp-content/uploads/browser-logos.svg"><img class="alignnone" title="Browser Logos" src="/wp-content/uploads/browser-logos.png" alt="" width="344" height="61" /></a></p>
<p><a href="/wp-content/uploads/browser-logos.svg"> </a></p>
<p><a href="/wp-content/uploads/browser-logos.svg">Download browser-logos.svg</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.calyptus.eu/seb/2011/09/simple-browser-icons/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Convert a SVG Path to CSS Animation Keyframes</title>
		<link>http://blog.calyptus.eu/seb/2011/09/csspathanimation/</link>
		<comments>http://blog.calyptus.eu/seb/2011/09/csspathanimation/#comments</comments>
		<pubDate>Mon, 12 Sep 2011 15:16:14 +0000</pubDate>
		<dc:creator>Sebastian Markbåge</dc:creator>
				<category><![CDATA[Client Side]]></category>
		<category><![CDATA[Arc]]></category>
		<category><![CDATA[ART]]></category>
		<category><![CDATA[Bezier curve]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[Path]]></category>
		<category><![CDATA[SVG]]></category>

		<guid isPermaLink="false">http://blog.calyptus.eu/?p=388</guid>
		<description><![CDATA[Click Here to Test The Tool
It&#8217;s not easy to generate keyframes for CSS3 Animations. This new CSS Path Animation tool can help you convert SVG paths into CSS keyframes.
SVG
Using SVG you can use the animateMotion element to move and rotate content following along a complex curved path. However, some vendors have turned away from SVG for animation [...]]]></description>
			<content:encoded><![CDATA[<p><strong><a href="http://csspathanimation.calyptus.eu/">Click Here to Test The Tool</a></strong></p>
<p>It&#8217;s not easy to generate keyframes for <a href="http://www.w3.org/TR/css3-animations/">CSS3 Animations</a>. <a href="http://csspathanimation.calyptus.eu/">This new CSS Path Animation tool</a> can help you convert SVG paths into CSS keyframes.</p>
<p><strong>SVG</strong></p>
<p>Using SVG you can use the <a href="http://www.w3.org/TR/SVG/animate.html#AnimateMotionElement">animateMotion</a> element to move and rotate content following along a complex curved path. However, some vendors have turned away from SVG for animation and prefer CSS as the way to do animations. For HTML content it tends to be very invasive. Using SVG with foreign objects tend to be poorly implemented as well.</p>
<p><strong>JavaScript</strong></p>
<p>Most JavaScript frameworks for vector graphics (<a href="http://github.com/calyptus/art">including ART</a>) can do the same thing with JavaScript animations.</p>
<p>Some people think that CSS animations inherently provide better performance than JavaScript animations. This is not strictly true. It is the hardware compositing step that&#8217;s the important part. You can use JavaScript animations together with requestAnimationFrame and 3D transforms to trigger hardware compositing. You get the same level of performance as with CSS.</p>
<p>However, this won&#8217;t work in JavaScript-free environments, such as some banner ad sandboxes. CSS animations provide a nice separation of concerns and easy of use.</p>
<p>NOTE: If available, JavaScript is the preferred way to do this kind of animation efficiently. In a later post, I&#8217;ll show you how to do this with <a href="http://github.com/calyptus/art">ART</a>.</p>
<p>Another aspect is that the JavaScript to run this animation can be very small.</p>
<p><strong>CSS</strong></p>
<p>If you prefer <a href="http://www.w3.org/TR/css3-animations/">CSS Animations</a>, how do you create the keyframes to animate an object along a complex path?</p>
<p>If you only have straight lines, it is easy. Just apply a <a href="http://www.w3.org/TR/css3-2d-transforms/">CSS Transform</a> to the X and Y coordinates of each point along the path. The rotation can be adjusted based on the angle of the line if you need it.</p>
<p><strong>CSS Curve Animation</strong></p>
<p>Things get much more complicated when you consider smooth curved paths. I.e. bezier curves or arcs.</p>
<p>The typical way to handle curves, is to subdivide them into very small straight line segments. However, if you generate this many CSS keyframes, the document would be huge. That&#8217;s not an option. We need a better technique.</p>
<p><strong>The Arc Rotation Technique</strong></p>
<p>For arcs, you can adjust the transform origin and rotate the element around the arc&#8217;s center point. This is the optimal technique for simple arcs such as circles and ellipses. You can approximate bezier curves using several arc segments. This can generate very small files for simple curves, or very big files for complex curves. This means it&#8217;s unreliable for an automated conversion tool.</p>
<p>If you want to avoid rotating the element and only move along a path, then you need an additional nested element to counter act the rotation.</p>
<p><strong>The Timing Function Technique</strong></p>
<p>A future new best friend of mine pointed out to me that you can animate the X and Y axis using different easing functions. That way the timing will cause the animation to be a smooth curve. The CSS animation standard specifies a timing function based on a cubic bezier. This gives us a lot of flexibility to define an easing function.</p>
<p>The trick is in defining the timing function used. A simple implementation would specify bezier curve control points on the second and forth argument to the timing function, leaving the first and third argument at 0 and 1 respectively. This gives a perfect motion along the path. Unfortunately, it doesn&#8217;t move at a constant speed.</p>
<p>To get the animation to move across the curve at a constant speed we have to use a little black magic math to approximate the motion at constant speed.</p>
<p>Not all curves can be animated using this technique due to limitations placed on the timing function. If a complex curve is found, we split it into two, until we have curves that can be animated this way. This provides us with a generic technique that can be used reasonably well for any path.</p>
<p><strong>Hardware Acceleration</strong></p>
<p>The arc technique uses a single CSS transform and is therefore easily hardware accelerated.</p>
<p>The timing function technique, requires different easing functions for each axis. That means that each axis needs it&#8217;s own animation.</p>
<p>Luckily we can apply multiple animations on a single element by animating the &#8220;left&#8221; and &#8220;top&#8221; properties independently. This is simple to use and non-invasive. However, this doesn&#8217;t currently provide the hardware compositing with sub-pixel accuracy, like the &#8220;transform&#8221; property does.</p>
<p>Unfortunately, we can&#8217;t animate each axis of a transform independently. The way to solve this is to use three nested elements and apply one transform for each element. This is a bit more invasive but provides the best visuals.</p>
<p>(UPDATE: The IE10 preview has a bug in nested transforms. At least in software mode. The previous method works well though and it&#8217;s hardware accelerated in IE. If the bug remains, I&#8217;ll update the converter to take this into account.)</p>
<p><strong>Conclusion</strong></p>
<p>In <a href="http://csspathanimation.calyptus.eu/">the conversion tool</a> I use the timing function technique with three nested elements. This gives us a generic solution that is also hardware accelerated in current Webkit and Mozilla browsers.</p>
<p>The resulting CSS is very bloated. GZIP:ing does a lot to the size but it&#8217;s still fairly big. There are a few action points browser vendors and W3C people could do to help:</p>
<p>1) Hardware accelerate left/top absolute positioning with sub-pixel precision. IE9 did this from the start. This is where the full(er) hardware pipeline of IE9 shines. This would allow us to use a single element for this hack.</p>
<p>2) Drop vendor prefixes on specs that are far along. CSS keyframes can be very bloated and they have to be multiplied in full for each vendor.</p>
<p>3) Standardize something like SVG&#8217;s animateMotion, but for CSS. SVG isn&#8217;t less verbose but there&#8217;s a specialized element to handle this scenario. This same hack would be even more bloated in SVG.</p>
<p>A CSS rule could be used to name a SVG-style path. This name can then be referenced by the &#8220;animation-name&#8221; property to apply a transform to an element along a path. The current hack can be used to provide backward compatibility.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p38819"><td class="code" id="p388code19"><pre class="css" style="font-family:monospace;"><span style="color: #cc00cc;">#target</span> <span style="color: #00AA00;">&#123;</span>
  animation<span style="color: #00AA00;">:</span> myMotion 1s infinite<span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #a1a100;">@motion myMotion {</span>
  path<span style="color: #00AA00;">:</span> <span style="color: #ff0000;">'m0,0 l100,100 ...'</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span></pre></td></tr></table></div>

<p>I think I&#8217;ll prototype something like this for LESS.js.</p>
<p><strong>UPDATE:</strong><br />
I&#8217;ve started <a href="http://lists.w3.org/Archives/Public/www-style/2011Sep/0295.html">a discussion about standardizing this pattern on the www-style mailing list</a>.</p>
<p>The current idea is to add a &#8220;motion&#8221; property that&#8217;s valid only within the context of keyframes.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p38820"><td class="code" id="p388code20"><pre class="css" style="font-family:monospace;"><span style="color: #cc00cc;">#target</span> <span style="color: #00AA00;">&#123;</span>
  animation<span style="color: #00AA00;">:</span> myMotion 1s infinite<span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #a1a100;">@keyframes myMotion {</span>
  <span style="color: #933;"><span style="color: #cc66cc;">0</span>%</span> <span style="color: #00AA00;">&#123;</span>
    motion<span style="color: #00AA00;">:</span> m0<span style="color: #00AA00;">,</span><span style="color: #cc66cc;">0</span> l100<span style="color: #00AA00;">,</span><span style="color: #cc66cc;">100</span> ...<span style="color: #00AA00;">;</span>
  <span style="color: #00AA00;">&#125;</span>
  <span style="color: #933;"><span style="color: #cc66cc;">50</span>%</span> <span style="color: #00AA00;">&#123;</span>
    motion<span style="color: #00AA00;">:</span> M100<span style="color: #00AA00;">,</span><span style="color: #cc66cc;">100</span> L0<span style="color: #00AA00;">,</span><span style="color: #cc66cc;">0</span> ...<span style="color: #00AA00;">;</span>
  <span style="color: #00AA00;">&#125;</span>
<span style="color: #00AA00;">&#125;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.calyptus.eu/seb/2011/09/csspathanimation/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>JavaScript Call Performance &#8211; Just Inline It</title>
		<link>http://blog.calyptus.eu/seb/2011/01/javascript-call-performance-just-inline-it/</link>
		<comments>http://blog.calyptus.eu/seb/2011/01/javascript-call-performance-just-inline-it/#comments</comments>
		<pubDate>Mon, 24 Jan 2011 23:46:49 +0000</pubDate>
		<dc:creator>Sebastian Markbåge</dc:creator>
				<category><![CDATA[Client Side]]></category>
		<category><![CDATA[Classes]]></category>
		<category><![CDATA[Compiler]]></category>
		<category><![CDATA[Inlining]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Optimization]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://blog.calyptus.eu/?p=371</guid>
		<description><![CDATA[There are a couple of well-known micro optimization techniques when you need that extra speed within an expensive loop. It generally comes down to eliminating function calls and flattening the closure scope.
Intuitively you don&#8217;t want to bloat your download size with repeated code. You also want a clear separation of concerns to make your code [...]]]></description>
			<content:encoded><![CDATA[<p>There are a couple of well-known micro optimization techniques when you need that extra speed within an expensive loop. It generally comes down to eliminating function calls and flattening the closure scope.</p>
<p>Intuitively you don&#8217;t want to bloat your download size with repeated code. You also want a clear separation of concerns to make your code understandable and managable. You want to separate common code into sub-routines (functions).</p>
<p><strong>Intra-object method calls</strong></p>
<p>I&#8217;ve done <a href="http://jsperf.com/classes-with-inner-function-calls-instantiation">a number</a> <a href="http://jsperf.com/classes-with-inner-function-calls">of tests</a> <a href="http://jsperf.com/classes-with-many-inner-function-calls">on repeated calls</a> within a single object. This is typically where an expensive loop would occur.</p>
<p>Now you might think that property look-ups are expensive and should be avoided. Since in a naive implementation they would be continued hash-table look-ups. However, traversing closure scopes and .call(bind) invocations tend to be more expensive in real world engines. Generally, you are better off invoking the function, by property name, on the same prototype &#8211; continuously. Engines optimize for this pattern. In the tests you can see that this is even more prevalent in recent optimizations.</p>
<p><strong>Super/base method calls</strong></p>
<p>In Class-oriented/OOP patterns, you often see the need to override an inherited method. However, while doing so you wish to call the overridden (super/base/parent) function from within the new one.</p>
<p>The most common way of doing this is by storing a reference to the prototype object, then invoking the function using .call() or .apply() to set the &#8220;this&#8221; context to the right value. However, as I&#8217;ve shown, navigating a closure and invoking the function using .call() is more expensive than invoking prototype methods.</p>
<p>The benefit of storing a reference to the prototype is that you get a live property that can be monkey patched with a new super function on the fly. However, relying on this pattern can be tricky.</p>
<p>You&#8217;re better off having a module system that supports proper file ordering of monkey patches. Where monkey patches are applied before any child modules inherit from their parent. This will enable better optimization on engines that depend on declaration order to optimize their hidden classes (like V8). It also enables monkey patching of mixins that are copied. I.e. has no live inheritance (since JS doesn&#8217;t support multiple inheritance).</p>
<p>If we can assume that we don&#8217;t need on-the-fly updates of super functions, then we can optimize this further. Again, <a href="http://jsperf.com/super-call">my tests</a> show, that it&#8217;s faster to invoke a method on the same prototype than finding a function reference and invoking .call().</p>
<p>I&#8217;ve toyed with some <a href="https://gist.github.com/790455">syntax experiments</a> to make this prettier.</p>
<p><strong>Just Inline It</strong></p>
<p><a href="http://twitter.com/steida">Daniel Steigerwald</a> pointed out that once you make the assumption that we don&#8217;t need on-the-fly monkey patches, you should just inline the code. This is always faster.</p>
<p>Let&#8217;s take a look at some nonsensical code. The function bar calls the function foo four times.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p37123"><td class="code" id="p371code23"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> foo<span style="color: #009900;">&#40;</span>state<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> my <span style="color: #339933;">=</span> <span style="color: #3366CC;">'code'</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> l <span style="color: #339933;">=</span> my.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> l<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">%</span> <span style="color: #CC0000;">10</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span>
            state.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>my<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">==</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span>
            state.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>my<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>l <span style="color: #339933;">==</span> <span style="color: #CC0000;">2</span> <span style="color: #339933;">&amp;&amp;</span> i <span style="color: #339933;">==</span> <span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span>
            state.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'foo'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">else</span>
            state.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'else'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> my<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> bar<span style="color: #009900;">&#40;</span>condition<span style="color: #339933;">,</span> state<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">var</span> complexCondition <span style="color: #339933;">=</span> <span style="color: #339933;">!</span>condition <span style="color: #339933;">&amp;&amp;</span> state.<span style="color: #660066;">length</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">var</span> value <span style="color: #339933;">=</span> state<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>condition<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        value <span style="color: #339933;">=</span> foo<span style="color: #009900;">&#40;</span>state<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>complexCondition<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            state.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'someData'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            value <span style="color: #339933;">=</span> foo<span style="color: #009900;">&#40;</span>state<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>value.<span style="color: #660066;">length</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            value <span style="color: #339933;">=</span> foo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>value <span style="color: #339933;">==</span> <span style="color: #3366CC;">'else'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        	value <span style="color: #339933;">=</span> foo<span style="color: #009900;">&#40;</span>state<span style="color: #009900;">&#41;</span>
        	state.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'test'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        condition <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>value <span style="color: #339933;">==</span> <span style="color: #3366CC;">'foo'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This file weighs in at about 300 bytes gzipped.</p>
<p>If we instead inline (copy) the foo code into all four places in the bar function. We get something like this.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p37124"><td class="code" id="p371code24"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> bar<span style="color: #009900;">&#40;</span>condition<span style="color: #339933;">,</span> state<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">var</span> complexCondition <span style="color: #339933;">=</span> <span style="color: #339933;">!</span>condition <span style="color: #339933;">&amp;&amp;</span> state.<span style="color: #660066;">length</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">3</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">var</span> value <span style="color: #339933;">=</span> state<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>condition<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            <span style="color: #003366; font-weight: bold;">var</span> stack <span style="color: #339933;">=</span> state<span style="color: #339933;">;</span>
			<span style="color: #003366; font-weight: bold;">var</span> my <span style="color: #339933;">=</span> <span style="color: #3366CC;">'code'</span><span style="color: #339933;">;</span>
			<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> l <span style="color: #339933;">=</span> my.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> l<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
				<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">%</span> <span style="color: #CC0000;">10</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>my<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">==</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>my<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>l <span style="color: #339933;">==</span> <span style="color: #CC0000;">2</span> <span style="color: #339933;">&amp;&amp;</span> i <span style="color: #339933;">==</span> <span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'foo'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">else</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'else'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			value <span style="color: #339933;">=</span> my<span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>complexCondition<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            state.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'someData'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #003366; font-weight: bold;">var</span> stack <span style="color: #339933;">=</span> state<span style="color: #339933;">;</span>
			<span style="color: #003366; font-weight: bold;">var</span> my <span style="color: #339933;">=</span> <span style="color: #3366CC;">'code'</span><span style="color: #339933;">;</span>
			<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> l <span style="color: #339933;">=</span> my.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> l<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
				<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">%</span> <span style="color: #CC0000;">10</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>my<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">==</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>my<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>l <span style="color: #339933;">==</span> <span style="color: #CC0000;">2</span> <span style="color: #339933;">&amp;&amp;</span> i <span style="color: #339933;">==</span> <span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'foo'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">else</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'else'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			value <span style="color: #339933;">=</span> my<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>value.<span style="color: #660066;">length</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">5</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            <span style="color: #003366; font-weight: bold;">var</span> stack <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
			<span style="color: #003366; font-weight: bold;">var</span> my <span style="color: #339933;">=</span> <span style="color: #3366CC;">'code'</span><span style="color: #339933;">;</span>
			<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> l <span style="color: #339933;">=</span> my.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> l<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
				<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">%</span> <span style="color: #CC0000;">10</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>my<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">==</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>my<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>l <span style="color: #339933;">==</span> <span style="color: #CC0000;">2</span> <span style="color: #339933;">&amp;&amp;</span> i <span style="color: #339933;">==</span> <span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'foo'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">else</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'else'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			value <span style="color: #339933;">=</span> my<span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>value <span style="color: #339933;">==</span> <span style="color: #3366CC;">'else'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
            <span style="color: #003366; font-weight: bold;">var</span> stack <span style="color: #339933;">=</span> state<span style="color: #339933;">;</span>
			<span style="color: #003366; font-weight: bold;">var</span> my <span style="color: #339933;">=</span> <span style="color: #3366CC;">'code'</span><span style="color: #339933;">;</span>
			<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> l <span style="color: #339933;">=</span> my.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> l<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span>
				<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">%</span> <span style="color: #CC0000;">10</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>my<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">==</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>my<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>l <span style="color: #339933;">==</span> <span style="color: #CC0000;">2</span> <span style="color: #339933;">&amp;&amp;</span> i <span style="color: #339933;">==</span> <span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'foo'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
				<span style="color: #000066; font-weight: bold;">else</span>
					stack.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'else'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			value <span style="color: #339933;">=</span> my<span style="color: #339933;">;</span>
        	state.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'test'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        condition <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>value <span style="color: #339933;">==</span> <span style="color: #3366CC;">'foo'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This file weighs about 290 bytes gzipped. Wait, what? We more than doubled the original file size but the result is smaller?</p>
<p>Yes, the GZIP compression uses the <a href="http://en.wikipedia.org/wiki/LZ77">LZ77</a> algorithm to find repeated byte sequences. This means that inlining your code may actually result in smaller download sizes since some plumbing code is removed.</p>
<p>Is it cheating to compare gzipped file size instead of originals? No. You should always send your static uncompressed content using the GZIP compression. It&#8217;s cheap. This is the real world baseline. You should optimize for this.</p>
<p>There are some quirks to look out for. Some minifiers rename variables inconsistently. This may result in inconsistent sequences. You should look out for this, since that would cause a larger file size.</p>
<p>The larger code base may cause a slightly slower start up, since the JS engine needs to parse and compile more code. This should be very very minimal though. Remember, we&#8217;re optimizing for tight loops here.</p>
<p><strong>JS-to-JS Compilers</strong></p>
<p>Our inlined code is ugly and unmaintainable. Luckily there are tools that can inline pretty source code for us. E.g. the <a href="http://closure-compiler.appspot.com">Google Closure Compiler</a>. Unfortunately the Closure Compiler doesn&#8217;t seem to inline functions that are called more than once. Neither does it use these optimization techniques for super calls. Perhaps there are settings that I&#8217;m not aware of.</p>
<p>Recursive functions may be difficult to inline but there are tools that can rewrite these and do tail call optimizations as well.</p>
<p>However, this is just a hint of the awesomeness that could be achieved by using a custom JS-to-JS compiler. More on that later.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.calyptus.eu/seb/2011/01/javascript-call-performance-just-inline-it/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>WebGL &#8211; Not just for 3D</title>
		<link>http://blog.calyptus.eu/seb/2010/11/webgl-not-just-for-3d/</link>
		<comments>http://blog.calyptus.eu/seb/2010/11/webgl-not-just-for-3d/#comments</comments>
		<pubDate>Thu, 18 Nov 2010 04:11:28 +0000</pubDate>
		<dc:creator>Sebastian Markbåge</dc:creator>
				<category><![CDATA[Client Side]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[ART]]></category>
		<category><![CDATA[Diffusion Curves]]></category>
		<category><![CDATA[GLSL]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[OpenGL]]></category>
		<category><![CDATA[Page Curl]]></category>
		<category><![CDATA[WebGL]]></category>

		<guid isPermaLink="false">http://blog.calyptus.eu/?p=340</guid>
		<description><![CDATA[UPDATED: The demos are now updated to work around some bugs in the ANGLE implementation currently in Chrome 9 beta and Firefox 4 beta 8.
Those of you who are following me on Twitter know that I&#8217;ve been really getting into WebGL lately. Basically it&#8217;s 1:1 JavaScript bindings to OpenGL ES 2.0 including GLSL (OpenGL Shading [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATED: The demos are now updated to work around some bugs in the ANGLE implementation currently in Chrome 9 beta and Firefox 4 beta 8.</strong></p>
<p>Those of you who are <a href="http://twitter.com/sebmarkbage">following me on Twitter</a> know that I&#8217;ve been really getting into <a href="http://www.khronos.org/webgl/">WebGL</a> lately. Basically it&#8217;s 1:1 JavaScript bindings to OpenGL ES 2.0 including GLSL (OpenGL Shading Language). This will allow you to access the power of GPU hardware directly in your website.</p>
<p>Safari, Chrome and Firefox all have WebGL enabled in their latest betas/nightly builds. Opera is on the working group as well. Additionally modern iOS and Android devices have OpenGL ES support so mobile support is probably not far away. Firefox already has WebGL support on Maemo.</p>
<p><strong>Microsoft is not yet on board</strong></p>
<p>While Microsoft is constantly bragging about the fully hardware accelerated rendering in IE9 using DirectX. They&#8217;re the only one of the major players not yet in the WebGL working group. WebGL is supposedly designed so that it can be implemented on top of DirectX. This allows for stronger implementations on Windows where OpenGL support is poor. Mozilla and Google are already <a href="http://news.softpedia.com/news/Google-s-ANGLE-Project-WebGL-Based-on-DirectX-137892.shtml">doing this</a> in their implementations.</p>
<p>Microsoft obviously have a lot invested in DirectX and may not want to support an API so close to the competing OpenGL. However, given their recent effort to support standards I&#8217;m hopeful they&#8217;ll get on board for IE 10.</p>
<p><strong>Fallbacks</strong></p>
<p>Given that no browser supports WebGL yet, other than in beta versions. We will obviously need some fallback.</p>
<p><a href="http://mrdoob.com/">Mr. Doob</a> is doing some great progress on a 3D API with Canvas 2D and SVG fallback support &#8211; called <a href="https://github.com/mrdoob/three.js/">three.js</a>. However, I think this will be of limited use in most real-world scenarios.</p>
<p>For any proper 3D beyond gimmicks you&#8217;ll want to use hardware acceleration. The exception being data visualization.</p>
<p>Flash and Silverlight already have pixel shader support. This doesn&#8217;t help 3D much but they do help for 2D special effects etc. Although these are not hardware accelerated, they can run multi-core and they&#8217;re faster than anything you can do with 2D canvas.</p>
<p>Additionally Adobe has announced hardware accelerated 3D support through the <a href="http://labs.adobe.com/technologies/flash/molehill/">Molehill APIs</a>. I&#8217;m sure Microsoft is not far behind with Silverlight. Once these get out to IE users, we&#8217;ll have direct hardware capabilities on all the major platforms.</p>
<p><strong>Abstractions</strong></p>
<p>WebGL is a horrible looking API. It&#8217;s intentionally a direct translation of the C interface. The intension is that people will provide abstractions on top of it. E.g. a general game engine or a data visualization API built on top of it.</p>
<p>Some have tried to make thin wrappers around it. Like <a href="http://mootools.net">MooTools</a> or <a href="http://jquery.com">jQuery</a> wraps the DOM in a thin API abstraction. I think that is a mistake. You really need to optimize for performance and to do that you need a higher level abstraction that works directly to the WebGL API.</p>
<p>I have no intension of making a thin GL wrapper nor a single generic 3D API. Although&#8230;</p>
<p><strong>It&#8217;s not just for 3D</strong></p>
<p>Those of you <a href="http://github.com/calyptus">following me</a> on <a href="http://github.com/">GitHub</a> know that I&#8217;ve been doing a lot of work on the <a href="http://mootools.net/">MooTools</a> vector graphics library &#8211; <a href="http://github.com/calyptus/art">ART</a>. We already have great SVG and VML support. Next for me is to focus on high performance scenarios.</p>
<p>To start off, I&#8217;ve implemented two 2D use cases that are otherwise difficult to do properly using CPU only.</p>
<p><a href="http://labs.calyptus.eu/diffusioncurves/">Diffusion Curves</a></p>
<p><a href="http://labs.calyptus.eu/diffusioncurves/"><img alt="" src="http://blog.calyptus.eu/wp-content/uploads/diffusion-curves.jpg" title="Diffusion Curves" class="alignnone" width="512" height="512" /></a></p>
<p>A Diffusion Curve is a new vector primitive. To understand what they are and why they&#8217;re incredibly cool, I recommend watching <a href="http://artis.imag.fr/Publications/2008/OBWBTS08/">the video from the authors of the original research paper</a>. Implementing a rasterizer of Diffusion Curves involves a diffusion and blur step that are both very computationally expensive. However, using a clever implementation you can take advantage of GPU hardware acceleration to get acceptable performance. There have been talks about introducing diffusion curves in SVG 2.0. But until that gets into browsers, we can already use it through the power of WebGL.</p>
<p><a href="http://labs.calyptus.eu/pagecurl/">Page Curl Effect</a></p>
<p><a href="http://labs.calyptus.eu/pagecurl/"><img alt="" src="http://blog.calyptus.eu/wp-content/uploads/page-curl.jpg" title="Page Curl" class="alignnone" width="512" height="512" /></a></p>
<p>A page curling effect can be implemented many different ways. However, to get a smooth realistic effect on dynamic content you really need some acceleration. This applies to many special effects that you can apply to 2D content.</p>
<p>Safari doesn&#8217;t implement SVG filters yet. Such filters can be implemented in terms of WebGL and extended further to advanced blending effects and crazy transforms.</p>
<p><strong>Computation</strong></p>
<p>WebGL is a great complement to JavaScript. JavaScript can be used to implement business logic and UI components while WebGL is used for computationally expensive tasks. Many of the use cases of NaCi (Native Client) goes out the window. You can even use WebGL to performance non-graphics tasks such as audio signal analysis/transformation.</p>
<p>Now all we need is a JavaScript based OpenCL like API for running GPU accelerated workers. There are already several projects doing <a href="http://mathema.tician.de/software/pyopencl">something similar</a> with Python.</p>
<p><strong>Learning more about WebGL</strong></p>
<p>The best way to learn WebGL is to head over to <a href="http://learningwebgl.com/">Learning WebGL</a> and check out <a href="http://twitter.com/gpjt">Giles Thomas</a>&#8216; excellent introductory lessons.</p>
<p><strong>Coming Up</strong></p>
<p>Lessons Learned &#8211; WebGL</p>
<p>Lessons Learned &#8211; Diffusion Curves</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.calyptus.eu/seb/2010/11/webgl-not-just-for-3d/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>JavaScript Proxies &#8211; &#8220;Leaky this&#8221;</title>
		<link>http://blog.calyptus.eu/seb/2010/11/javascript-proxies-leaky-this/</link>
		<comments>http://blog.calyptus.eu/seb/2010/11/javascript-proxies-leaky-this/#comments</comments>
		<pubDate>Wed, 17 Nov 2010 23:31:17 +0000</pubDate>
		<dc:creator>Sebastian Markbåge</dc:creator>
				<category><![CDATA[Client Side]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Leaky Abstraction]]></category>
		<category><![CDATA[Leaky This]]></category>
		<category><![CDATA[Proxies]]></category>
		<category><![CDATA[Wrapper]]></category>

		<guid isPermaLink="false">http://blog.calyptus.eu/?p=307</guid>
		<description><![CDATA[You can introduce AOP interception patterns by either changing the original instance or by using additional proxy objects. The later can introduce confusion among instances if not treated correctly. Skip to &#8220;Leaky this&#8221; if you&#8217;re already familiar with proxies in ECMAScript Harmony.
Rewriting vs. Wrapping
Intercepting normal program flows using aspect oriented and other meta-programming patterns can [...]]]></description>
			<content:encoded><![CDATA[<p><em>You can introduce AOP interception patterns by either changing the original instance or by using additional proxy objects. The later can introduce confusion among instances if not treated correctly. Skip to &#8220;<a href="#leaky-this">Leaky this</a>&#8221; if you&#8217;re already familiar with proxies in ECMAScript Harmony.</em></p>
<p><strong>Rewriting vs. Wrapping</strong></p>
<p>Intercepting normal program flows using aspect oriented and other meta-programming patterns can be used for a variety of advanced tricks. Object-relational mapping, logging, security, customized APIs etc.</p>
<p>You can do this by rewriting the methods of the original class/prototype/instance, effectively providing a single instance. You can also do this by providing wrapper objects. That way you have two or more instances.</p>
<p>Rewriting instances or prototypes is easy to do in JS by overriding the functions on existing objects with your own wrapper functions. Although it&#8217;s not always possible on the magical host objects. It can also be a problem when these objects have different requirements in various contexts. Such as in a secured sandbox vs. host environment.</p>
<p>Wrappers allow you to leave the original object intact while providing the wrapper to a specific context as if it&#8217;s the real object.</p>
<p><strong>Wrappers in ECMAScript 5</strong></p>
<p>In <a href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf">ECMAScript 5</a> you can already do seemingly perfect wrappers by getting all the properties of an object. Then you define those properties on the wrapper &#8211; called a proxy. These are custom getters and setters that delegate to the original object &#8211; called the subject.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p30731"><td class="code" id="p307code31"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> subject <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Node<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> proxy <span style="color: #339933;">=</span> Object.<span style="color: #660066;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
Object.<span style="color: #660066;">getOwnPropertyNames</span><span style="color: #009900;">&#40;</span>subject<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">forEach</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #000066;">name</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  Object.<span style="color: #660066;">defineProperty</span><span style="color: #009900;">&#40;</span>proxy<span style="color: #339933;">,</span> <span style="color: #000066;">name</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>
    get<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #000066;">name</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      <span style="color: #006600; font-style: italic;">// interception code</span>
      <span style="color: #000066; font-weight: bold;">return</span> subject<span style="color: #009900;">&#91;</span><span style="color: #000066;">name</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>(For simplicity I&#8217;ve left out the prototype, setters, enumerations rules etc. Getters are enough to illustrate my point.)</p>
<p>These are fine for frozen objects. The problem is that they don&#8217;t represent later changes to the subject. E.g. adding or deleting properties. Additionally, property changes applied to the proxy aren&#8217;t propagated back into the subject.</p>
<p><strong>Proxies in ECMAScript Harmony</strong></p>
<p>It looks like the next version of ECMAScript will get support for <a href="http://wiki.ecmascript.org/doku.php?id=harmony:proxies">proxy object</a> that can delegate all operations dynamically &#8211; using so called &#8220;catch-all&#8221; functions.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p30732"><td class="code" id="p307code32"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> subject <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Node<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> proxy <span style="color: #339933;">=</span> Proxy.<span style="color: #660066;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  get<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>receiver<span style="color: #339933;">,</span> <span style="color: #000066;">name</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// interception code</span>
    <span style="color: #000066; font-weight: bold;">return</span> subject<span style="color: #009900;">&#91;</span><span style="color: #000066;">name</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>When we&#8217;re reading a property from the proxy instance, our get-function gets called with the receiver (the proxy instance itself) and the name of the property that should be loaded. We delegate this request to the subject by reading the same property. We can insert any intercepting code as we choose.</p>
<p>This is more efficient and allows for dynamic evaluation of intercepting code. Many ORM patterns &#8211; such as <a href="http://en.wikipedia.org/wiki/Active_record">Active Record</a> &#8211; often use this technique in dynamic environments.</p>
<p><a name="leaky-this"></a><strong>&#8220;Leaky this&#8221;</strong></p>
<p>However, a problem occurs when these two instances get confused. Imagine this scenario:</p>

<div class="wp_codebox"><table width="100%" ><tr id="p30733"><td class="code" id="p307code33"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Node <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">,</span> children <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  self.<span style="color: #660066;">addChild</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>child<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    children.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>child<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    child.<span style="color: #660066;">parent</span> <span style="color: #339933;">=</span> self<span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> self<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>If we wrap an instance of Node in a proxy. Then call:</p>

<div class="wp_codebox"><table width="100%" ><tr id="p30734"><td class="code" id="p307code34"><pre class="javascript" style="font-family:monospace;">proxy.<span style="color: #660066;">addChild</span><span style="color: #009900;">&#40;</span>child<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">addChild</span><span style="color: #009900;">&#40;</span>childOther<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>We first call addChild through the proxy instance. Our child.parent property is set to the subject instance. The subject instance is returned and we next call addChild directly on the subject instance. Bypassing the proxy.</p>
<p>This is a well-known problem in languages that strongly binds the &#8220;this&#8221; keyword to a specific instance. <a href="http://rogeralsing.com/">Roger Alsing</a> calls this &#8220;<a href="http://www.puzzleframework.com/forum/thread.aspx?Thread=828">leaky this</a>&#8221; which I find to be an appropriate term since the abstraction is leaking.</p>
<p>However, imagine this JavaScript code:</p>

<div class="wp_codebox"><table width="100%" ><tr id="p30735"><td class="code" id="p307code35"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Node <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">children</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
Node.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">addChild</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>child<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">children</span>.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>child<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  child.<span style="color: #660066;">parent</span> <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The addChild function now references the &#8220;this&#8221; keyword. If we repeat the same call in this scenario we get a different result. We call addChild while passing the proxy as the &#8220;this&#8221; reference. We set the parent property of child to the proxy instance. The proxy instance is returned, and the process is repeated on the second call. This shows the beauty of not having the &#8220;this&#8221; keyword bound to specific instances.</p>
<p>Although, sometimes you don&#8217;t want to use the proxy instance in internal functions. You could use this hybrid to use the subject for whatever use internally, while exposing any proxies externally:</p>

<div class="wp_codebox"><table width="100%" ><tr id="p30736"><td class="code" id="p307code36"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> Node <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">,</span> children <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  self.<span style="color: #660066;">addChild</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>child<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    children.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>child<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    child.<span style="color: #660066;">parent</span> <span style="color: #339933;">=</span> self<span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>Conclusion</strong></p>
<p><a href="http://brendaneich.com/">Brendan Eich</a> <a href="http://brendaneich.com/2010/11/proxy-inception/">points out</a> that unaware consumers of a proxy should be able to treat it just as any other object. This is only true if the provider of both the proxy and the subject have carefully considered the implications of two instances and made sure that no leaking occurs. Code that can be wrapped needs to carefully consider what instance it is currently working with.</p>
<p>Not all code can be wrapped using a proxy indiscriminately.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.calyptus.eu/seb/2010/11/javascript-proxies-leaky-this/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>The Reactive Extensions for JavaScript &#8211; MooTools Integration</title>
		<link>http://blog.calyptus.eu/seb/2010/03/rx-for-mootools/</link>
		<comments>http://blog.calyptus.eu/seb/2010/03/rx-for-mootools/#comments</comments>
		<pubDate>Sun, 07 Mar 2010 21:08:00 +0000</pubDate>
		<dc:creator>Sebastian Markbåge</dc:creator>
				<category><![CDATA[Client Side]]></category>
		<category><![CDATA[MooTools]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Reactive Extensions]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://blog.calyptus.eu/?p=194</guid>
		<description><![CDATA[This is a follow up to my earlier post about the Reactive Extensions (Rx) for JavaScript by Microsoft&#8217;s DevLabs. This is also in response to Matthew Podwysocki&#8217;s post on jQuery integration (which deserves some credit for putting it out there).
I will assume some familiarity with Rx.
Just like any other DOM library, MooTools has a way of [...]]]></description>
			<content:encoded><![CDATA[<p><em>This is a follow up to my earlier post about the <a href="http://blog.calyptus.eu/seb/2010/03/rx-for-javascript/">Reactive Extensions (Rx) for JavaScript</a> by Microsoft&#8217;s DevLabs. This is also in response to Matthew Podwysocki&#8217;s post on <a href="http://weblogs.asp.net/podwysocki/archive/2010/03/05/introduction-to-the-reactive-extensions-for-javascript-jquery-integration.aspx">jQuery integration</a> (which deserves some credit for putting it out there).</em></p>
<p><em>I will assume some familiarity with Rx.</em></p>
<p>Just like any other DOM library, MooTools has a way of working with native and custom passive DOM events. We can easily give Element object and the Elements collection a method to provide these events as &#8220;Observables&#8221;. In the jQuery example the method name &#8220;ToObservable&#8221; was added to the jQuery object, accepting an event type parameter, which was my initial reaction as well. But I&#8217;m going to call mine <strong>getEvent</strong> as in &#8220;<em>getting a stream of events given the event type</em>&#8220;.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p19445"><td class="code" id="p194code45"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> observableFromEvent <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>type<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">return</span> Rx.<span style="color: #660066;">Observable</span>.<span style="color: #660066;">Create</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>observer<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      <span style="color: #003366; font-weight: bold;">var</span> fn <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>event<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          observer.<span style="color: #660066;">OnNext</span><span style="color: #009900;">&#40;</span>event<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
      self.<span style="color: #660066;">addEvent</span><span style="color: #009900;">&#40;</span>type<span style="color: #339933;">,</span> fn<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        self.<span style="color: #660066;">removeEvent</span><span style="color: #009900;">&#40;</span>type<span style="color: #339933;">,</span> fn<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
Window.<span style="color: #660066;">implement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'getEvent'</span><span style="color: #339933;">,</span> observableFromEvent<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Document.<span style="color: #660066;">implement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'getEvent'</span><span style="color: #339933;">,</span> observableFromEvent<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Element.<span style="color: #660066;">implement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'getEvent'</span><span style="color: #339933;">,</span> observableFromEvent<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Elements.<span style="color: #660066;">implement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'getEvent'</span><span style="color: #339933;">,</span> observableFromEvent<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><em>These are infinite Observables but we could also make .destroy() trigger onComplete to make them finite as well.</em></p>
<p><strong>Flickables Example</strong></p>
<p>Instead of the canonical Drag and Drop example I thought I show a twist. Let&#8217;s say we want to listen to a mouse flick. The mouse position have to move over 100px in 200ms. Then we want the angle of the flick.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p19446"><td class="code" id="p194code46"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> angleFromPosition <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>position<span style="color: #339933;">,</span> center<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> diffX <span style="color: #339933;">=</span> position.<span style="color: #660066;">x</span> <span style="color: #339933;">-</span> center.<span style="color: #660066;">x</span><span style="color: #339933;">,</span> diffY <span style="color: #339933;">=</span> position.<span style="color: #660066;">y</span> <span style="color: #339933;">-</span> center.<span style="color: #660066;">y</span><span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> distance <span style="color: #339933;">=</span> Math.<span style="color: #660066;">sqrt</span><span style="color: #009900;">&#40;</span>diffX <span style="color: #339933;">*</span> diffX <span style="color: #339933;">+</span> diffY <span style="color: #339933;">*</span> diffY<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> angle <span style="color: #339933;">=</span> Math.<span style="color: #660066;">atan2</span><span style="color: #009900;">&#40;</span>diffY <span style="color: #339933;">+</span> distance<span style="color: #339933;">,</span> diffX<span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #CC0000;">360</span> <span style="color: #339933;">/</span> Math.<span style="color: #660066;">PI</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#123;</span> distance<span style="color: #339933;">:</span> distance<span style="color: #339933;">,</span> angle<span style="color: #339933;">:</span> angle <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> distanceReached <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>angle<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> angle.<span style="color: #660066;">distance</span> <span style="color: #339933;">&gt;</span> <span style="color: #CC0000;">100</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> timeLimit <span style="color: #339933;">=</span> Rx.<span style="color: #660066;">Observable</span>.<span style="color: #660066;">Timer</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">200</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> mousePositions <span style="color: #339933;">=</span> document.<span style="color: #660066;">getEvent</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'mousemove'</span><span style="color: #009900;">&#41;</span>
                     .<span style="color: #660066;">Select</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>event<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">return</span> event.<span style="color: #660066;">page</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> flicks <span style="color: #339933;">=</span> document.<span style="color: #660066;">getElements</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.flickable'</span><span style="color: #009900;">&#41;</span>
             .<span style="color: #660066;">getEvent</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'mousedown'</span><span style="color: #009900;">&#41;</span>
             .<span style="color: #660066;">SelectMany</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>event<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
                 <span style="color: #000066; font-weight: bold;">return</span> mousePositions
                     .<span style="color: #660066;">Select</span><span style="color: #009900;">&#40;</span>angleFromPosition.<span style="color: #660066;">bindWithEvent</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">,</span> event.<span style="color: #660066;">page</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
                     .<span style="color: #660066;">TakeUntil</span><span style="color: #009900;">&#40;</span>document.<span style="color: #660066;">getEvent</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'mouseup'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
                     .<span style="color: #660066;">TakeUntil</span><span style="color: #009900;">&#40;</span>timeLimit<span style="color: #009900;">&#41;</span>
                     .<span style="color: #660066;">Where</span><span style="color: #009900;">&#40;</span>distanceReached<span style="color: #009900;">&#41;</span>
                     .<span style="color: #660066;">Take</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
             <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// ...</span>
&nbsp;
flicks.<span style="color: #660066;">Subscribe</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>current<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Flicked in direction: '</span> <span style="color: #339933;">+</span> current.<span style="color: #660066;">angle</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">'°'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>Events Mixin</strong></p>
<p>MooTools has a very strong benefit compared to many other libraries. The publish/subscribe pattern is made explicit even for custom classes, using the Events mixin. By implement our &#8220;getEvent&#8221; method on this class we can use Rx on all custom MooTools classes that provide passive events.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p19447"><td class="code" id="p194code47"><pre class="javascript" style="font-family:monospace;">Events.<span style="color: #660066;">implement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'getEvent'</span><span style="color: #339933;">,</span> observableFromEvent<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>Side-effects</strong></p>
<p>Rx allows for the act of subscribing to an event to trigger an action/side-effect. Think of the Request object for example. You can use the act of subscribing to it, to issue a HTTP request. Then we can turn the subsequent events like success and failure into the Observable interface. This means that Request is a complete Observable in it self. This is what I was saving the conversion name <strong>toObservable</strong> for.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p19448"><td class="code" id="p194code48"><pre class="javascript" style="font-family:monospace;">Request.<span style="color: #660066;">implement</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
&nbsp;
  toObservable<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> Rx.<span style="color: #660066;">Observable</span>.<span style="color: #660066;">create</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>observer<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
      <span style="color: #003366; font-weight: bold;">var</span> listeners <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
&nbsp;
        success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>result<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          self.<span style="color: #660066;">removeEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          observer.<span style="color: #660066;">OnNext</span><span style="color: #009900;">&#40;</span>result<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          observer.<span style="color: #660066;">OnCompleted</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
        cancel<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          self.<span style="color: #660066;">removeEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          observer.<span style="color: #660066;">OnCompleted</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
        failure<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>xhr<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          self.<span style="color: #660066;">removeEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          observer.<span style="color: #000066;">OnError</span><span style="color: #009900;">&#40;</span>xhr<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
      <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>self.<span style="color: #660066;">running</span> <span style="color: #339933;">||</span> self.<span style="color: #660066;">options</span>.<span style="color: #660066;">link</span> <span style="color: #339933;">==</span> <span style="color: #3366CC;">'cancel'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        self.<span style="color: #660066;">addEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">send</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          self.<span style="color: #660066;">removeEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">cancel</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>self.<span style="color: #660066;">options</span>.<span style="color: #660066;">link</span> <span style="color: #339933;">==</span> <span style="color: #3366CC;">'chain'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> disposed<span style="color: #339933;">,</span> running<span style="color: #339933;">;</span>
        self.<span style="color: #660066;">chain</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          running <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
          <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>disposed<span style="color: #009900;">&#41;</span> self.<span style="color: #660066;">addEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">send</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>running<span style="color: #009900;">&#41;</span> self.<span style="color: #660066;">removeEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">cancel</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          disposed <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      observer.<span style="color: #660066;">OnComplete</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>This creates a finite stream of events &#8211; only one response to be exact. However, since the act of subscribing to it causes it to occur we can have it trigger repeatedly as part of a composite stream of events.</p>
<p>MooTools&#8217; Fx provides a similar concept but slightly different. Even though we don&#8217;t get an event for each tick, we still get an asynchronous complete event. This means we can insert Fx as part of a composite stream of events.</p>
<p>Fx also requires from/to arguments to be passed at the start. So we add the option &#8220;defaultArgs&#8221; to allow us to pass those at initialization.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p19449"><td class="code" id="p194code49"><pre class="javascript" style="font-family:monospace;">Fx.<span style="color: #660066;">implement</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
&nbsp;
  toObservable<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> Rx.<span style="color: #660066;">Observable</span>.<span style="color: #660066;">create</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>observer<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
      <span style="color: #003366; font-weight: bold;">var</span> listeners <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
&nbsp;
        complete<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          self.<span style="color: #660066;">removeEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          observer.<span style="color: #660066;">OnCompleted</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
        cancel<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          self.<span style="color: #660066;">removeEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          observer.<span style="color: #660066;">OnCompleted</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
      <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>self.<span style="color: #660066;">running</span> <span style="color: #339933;">||</span> self.<span style="color: #660066;">options</span>.<span style="color: #660066;">link</span> <span style="color: #339933;">==</span> <span style="color: #3366CC;">'cancel'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        self.<span style="color: #660066;">addEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">start</span>.<span style="color: #660066;">run</span><span style="color: #009900;">&#40;</span>self.<span style="color: #660066;">options</span>.<span style="color: #660066;">defaultArgs</span><span style="color: #339933;">,</span> self<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          self.<span style="color: #660066;">removeEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">cancel</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>self.<span style="color: #660066;">options</span>.<span style="color: #660066;">link</span> <span style="color: #339933;">==</span> <span style="color: #3366CC;">'chain'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> disposed<span style="color: #339933;">,</span> running<span style="color: #339933;">;</span>
        self.<span style="color: #660066;">chain</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          running <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
          <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>disposed<span style="color: #009900;">&#41;</span>
            self.<span style="color: #660066;">addEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">start</span>.<span style="color: #660066;">run</span><span style="color: #009900;">&#40;</span>self.<span style="color: #660066;">options</span>.<span style="color: #660066;">defaultArgs</span><span style="color: #339933;">,</span> self<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>running<span style="color: #009900;">&#41;</span> self.<span style="color: #660066;">removeEvents</span><span style="color: #009900;">&#40;</span>listeners<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">cancel</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
          disposed <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      observer.<span style="color: #660066;">OnComplete</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Of course since there are a lot of other classes extending the Request and Fx classes, you get the same benefits on them. This is one of the true benefits of MooTools&#8217; modular extensibility.</p>
<p><em>That is one of the benefits of using the class(ical) pattern in JavaScript. More on that next time&#8230;</em></p>
<p><strong>Side-effects Example</strong></p>

<div class="wp_codebox"><table width="100%" ><tr id="p19450"><td class="code" id="p194code50"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> popup <span style="color: #339933;">=</span> document.<span style="color: #660066;">id</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'popup'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> showPopup <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Fx.<span style="color: #660066;">Morph</span><span style="color: #009900;">&#40;</span>popup<span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span> property<span style="color: #339933;">:</span> <span style="color: #3366CC;">'opacity'</span><span style="color: #339933;">,</span> defaultArgs<span style="color: #339933;">:</span> <span style="color: #CC0000;">1</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> feed <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Request.<span style="color: #660066;">JSON</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span> url<span style="color: #339933;">:</span> <span style="color: #3366CC;">'mydata.json'</span><span style="color: #339933;">,</span> method<span style="color: #339933;">:</span> <span style="color: #3366CC;">'get'</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> showFeed <span style="color: #339933;">=</span> feed.<span style="color: #660066;">toObservable</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
               .<span style="color: #000066; font-weight: bold;">Do</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span> popup.<span style="color: #660066;">set</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'text'</span><span style="color: #339933;">,</span> data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
               .<span style="color: #660066;">Concat</span><span style="color: #009900;">&#40;</span>showPopup.<span style="color: #660066;">toObservable</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// ...</span>
&nbsp;
showFeed.<span style="color: #660066;">Subscribe</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// loads mydata.json into #popup and displays it</span></pre></td></tr></table></div>

<p><strong>Using Arrays in Unit Tests</strong></p>
<p>Since natives are allowed to be extended within the MooTools theorem, we can add a convenience method to turn an Array into an observable stream of content.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p19451"><td class="code" id="p194code51"><pre class="javascript" style="font-family:monospace;">Array.<span style="color: #660066;">implement</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'toObservable'</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> Rx.<span style="color: #660066;">Observable</span>.<span style="color: #660066;">FromArray</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>We can use this to fake the &#8220;flicks&#8221; event stream in our earlier example. We avoid having to include complex asynchronous tests or user action tests.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p19452"><td class="code" id="p194code52"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> flicks <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span>
               <span style="color: #009900;">&#123;</span> angle<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> distance<span style="color: #339933;">:</span> <span style="color: #CC0000;">100</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
               <span style="color: #009900;">&#123;</span> angle<span style="color: #339933;">:</span> <span style="color: #CC0000;">45</span><span style="color: #339933;">,</span> distance<span style="color: #339933;">:</span> <span style="color: #CC0000;">100</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
               <span style="color: #009900;">&#123;</span> angle<span style="color: #339933;">:</span> <span style="color: #CC0000;">90</span><span style="color: #339933;">,</span> distance<span style="color: #339933;">:</span> <span style="color: #CC0000;">100</span> <span style="color: #009900;">&#125;</span>
             <span style="color: #009900;">&#93;</span>
             .<span style="color: #660066;">toObservable</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Unit tests</span>
<span style="color: #006600; font-style: italic;">// Synchronously testing code that's depending on a flick event stream</span></pre></td></tr></table></div>

<p><strong>Web Sockets and Web Workers</strong></p>
<p>Now imagine this on a stream of events coming in from <a href="http://dev.w3.org/html5/websockets/">Web Sockets</a> or <a href="http://dev.w3.org/html5/workers/">Web Workers</a>.</p>
<p>You could set up a web socket to asynchronously feed you JSON objects, and easily hook that up to the rest of you UI just as easily as the Request example above.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.calyptus.eu/seb/2010/03/rx-for-mootools/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>The Reactive Extensions for JavaScript &#8211; Event Composition</title>
		<link>http://blog.calyptus.eu/seb/2010/03/rx-for-javascript/</link>
		<comments>http://blog.calyptus.eu/seb/2010/03/rx-for-javascript/#comments</comments>
		<pubDate>Sat, 06 Mar 2010 14:37:22 +0000</pubDate>
		<dc:creator>Sebastian Markbåge</dc:creator>
				<category><![CDATA[Client Side]]></category>
		<category><![CDATA[Composable Events]]></category>
		<category><![CDATA[Event Composition]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Reactive Extensions]]></category>
		<category><![CDATA[Rx]]></category>

		<guid isPermaLink="false">http://blog.calyptus.eu/?p=186</guid>
		<description><![CDATA[I&#8217;ve been following the work on the Reactive Extensions for .NET (Rx) by Eric Meijer and others over at Microsoft. At first look I was intrigued but didn&#8217;t really understand the purpose of it. However, at a second look, I realized that it had the potential to solve every major problem I&#8217;ve had with advanced UI [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been following the work on the <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">Reactive Extensions for .NET</a> (Rx) by <a href="http://research.microsoft.com/en-us/um/people/emeijer/ErikMeijer.html">Eric Meijer</a> and others over at Microsoft. At first look I was intrigued but didn&#8217;t really understand the purpose of it. However, at a second look, I realized that it had the potential to solve every major problem I&#8217;ve had with advanced UI development in JavaScript.</p>
<p><strong>Asynchronous Programming &#8211; Composable Events</strong></p>
<p>Modern UI development forces us to use asynchronous patterns for user actions, animations and data load. But to make UI development easy you can think of each operation as sequential. You can even artificially lock down the user interface &#8211; by disabling or hiding UI elements &#8211; while an operation is occurring.</p>
<p>If you want to optimize your user experience, you will need to start dabble in the complicated art of event composition. The problem occurs when you have complex interactions that depend upon other interaction or state.</p>
<p>You can solve this using various state machine patterns. However, I think you will find it quite difficult at times. Even if you do solve it, it&#8217;s probably going to be for a specific purpose which is not easily generalizable nor extensible.</p>
<p>Various tools have tried using patterns like Futures and Promises. I think those patterns need to be applied at the language level to be really useful though.</p>
<p><strong>Reactive Programming in an Object Oriented World</strong></p>
<p>JavaScript has introduced the map/filter/reduce methods on arrays to allow collection operations using a sequenced composition of functions.</p>
<p>There&#8217;s one minor thing that JavaScript developers should note. In <a href="http://linqjs.codeplex.com/">LINQ</a> these operations are lazy iterables. The map/filter operations aren&#8217;t actually executed until an .each() starts iterating over them. This avoids having to create duplicates of the result in memory. It also means that the underlying array can change after we call filter and map. This is similar to &#8220;live&#8221; collections in the DOM. But they can also be infinite in length just like <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Iterators_and_Generators">Mozilla&#8217;s Iterators</a>. The .each() call is still essentially a synchronous operation though.</p>
<p><a href="http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Brian-Beckman-and-Erik-Meijer-Inside-the-NET-Reactive-Framework-Rx/">Erik Meijer and team</a> simply decided to make that iteration execution asynchronous.</p>
<p>This means that the source data can be asynchronous. So instead of thinking of Events as independent, think of them as a stream of data with an unknown length&#8230; (or an asynchronous list/array).</p>
<p>This means that you can now apply the same type of function composition to streams of events. Enter the <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">Reactive Extensions for .NET</a>.</p>
<p>Supposedly this could solve the problem of Event composition in the UI space.</p>
<p><strong>The Reactive Extensions for JavaScript</strong></p>
<p>To my surprise, <a href="http://weblogs.asp.net/podwysocki/">Matthew Podwysocki</a> recently started a <a href="http://weblogs.asp.net/podwysocki/archive/2010/02/16/introduction-to-the-reactive-extensions-to-javascript.aspx">blog series</a> about the Reactive Extensions for JavaScript (also Microsoft to be clear). Apparently the benefits of this tool in the JS world has not gone unnoticed.</p>
<p>There are no bits officially released yet. However, considering <a href="http://weblogs.asp.net/podwysocki/">Matthew Podwysocki&#8217;s</a> recent posts and <a href="http://live.visitmix.com/MIX10/Sessions/FTL01">Eric Meijer&#8217;s upcoming talk</a> at the Mix conference&#8230; I wouldn&#8217;t be surprised if something was released at Mix on March 17th.</p>
<p><strong>Learning More</strong></p>
<p>I have since been interested in learning more about various alternative models. There&#8217;s a research project called <a href="http://www.cs.umd.edu/~jfoster/arrows.pdf">Arrows</a> which provides a different model that&#8217;s more purely functional. There&#8217;s also a framework called <a href="http://www.flapjax-lang.org/">Flapjax</a> which is more of a DOM library aiming to provide reactive concepts to JavaScript.</p>
<p>To learn more about the Reactive Extensions, take a look at the <a href="http://channel9.msdn.com/tags/Rx/">videos about the .NET version posted by the team over at Channel 9</a>.</p>
<p><strong>Concerns</strong></p>
<p>I&#8217;m not sure the first implementation of the Reactive Extensions is going to be the one to solve all these problems.</p>
<p>I think that many developers will have a difficult time thinking about these concepts in the terms of event streams. That could make it difficult to use the current method naming. In this sense, I think <a href="http://www.cs.umd.edu/~jfoster/arrows.pdf">Arrows</a> might be easier to get started with. It will allow you to think about events as sequential operations. However, I also see benefit in the model employed by the Reactive Extensions, IF we can all wrap our heads around it.</p>
<p>Another issue is the &#8220;Let&#8221; method. This may be difficult to know when to use for many developers. That&#8217;s true even for LINQ. However, in the Reactive Extensions I have a feeling those issues will become even more prevalent. Hopefully there will be better syntactical sugar to solve this issue.</p>
<p>Rx has yet to prove itself in real world complex applications that goes well beyond single subscription examples. I may try to extend the canonical drag and drop examples to my own <a href="http://github.com/calyptus/mootools-draggable">HTML5 based Drag and Drop</a> model and plugins to stress test it.</p>
<p><strong>Naming Conventions</strong></p>
<p>There&#8217;s also the issue of upper camel case in method names. <a href="http://linqjs.codeplex.com/">LINQ for JavaScript</a> is also using this convention. I&#8217;m guessing they&#8217;re trying to be compatible. However, the JavaScript convention is to use lower camel case method names, which also the <a href="http://ajax.codeplex.com/">new ASP.NET AJAX</a> library is doing. So I don&#8217;t understand why.</p>
<p>In dynamic languages with limited auto-completion (IntelliSense) support, naming conventions are very important to follow.</p>
<p>Although, I do like the names Select/Where/OrderBy better than map/filter/sort since given the arguments, that tends to read better as a grammatical sentence.</p>
<p><strong>UPDATE: Event DSLs</strong></p>
<p>I should mention that the MooTools 2.0 team has been working on a DSL based on the CSS selector syntax. This is an extension of the <a href="http://mootools.net/docs/more/Element/Element.Delegation">Element.Delegation</a> plugin.</p>
<p>The idea is to use event names and pseudos in combination to create custom composite event listeners. This example would listen to the first click event:</p>

<div class="wp_codebox"><table width="100%" ><tr id="p18654"><td class="code" id="p186code54"><pre class="javascript" style="font-family:monospace;">element.<span style="color: #660066;">addEvent</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'click:flash'</span><span style="color: #339933;">,</span> firstClick<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>This could enable a lot more powerful combinations of custom events. However, it doesn&#8217;t enable passing of parameters and the composability of Rx and Arrows.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.calyptus.eu/seb/2010/03/rx-for-javascript/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Performance of .nodeName</title>
		<link>http://blog.calyptus.eu/seb/2009/11/the-performance-of-nodename/</link>
		<comments>http://blog.calyptus.eu/seb/2009/11/the-performance-of-nodename/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 05:43:01 +0000</pubDate>
		<dc:creator>Sebastian Markbåge</dc:creator>
				<category><![CDATA[Client Side]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://blog.calyptus.eu/?p=177</guid>
		<description><![CDATA[I was researching various options of traversing nodes for Slick and the DOM Range for MooTools. I realized that the nodeName property is incredibly slow to access in WebKit browsers. This is because it is working with qualified names (with namespaces and stuff) internally.

if &#40;node.nodeName == 'A'&#41; // do something with anchor tag

If you add [...]]]></description>
			<content:encoded><![CDATA[<p>I was researching various options of traversing nodes for <a href="http://github.com/subtleGradient/slick">Slick</a> and the <a href="http://github.com/calyptus/mootools-more/tree/range/Source/Native/">DOM Range for MooTools</a>. I realized that the nodeName property is incredibly slow to access in WebKit browsers. This is because it is working with qualified names (with namespaces and stuff) internally.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p17757"><td class="code" id="p177code57"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>node.<span style="color: #660066;">nodeName</span> <span style="color: #339933;">==</span> <span style="color: #3366CC;">'A'</span><span style="color: #009900;">&#41;</span> <span style="color: #006600; font-style: italic;">// do something with anchor tag</span></pre></td></tr></table></div>

<p>If you add case insensitive matching to that it will be even slower.</p>
<p>Instead I decided to try to check the constructor of the node to determine what type it is. For example for the anchor (A) tag, modern browsers will use the prototype of HTMLAnchorElement. This can potentially speed up these checks if you&#8217;re looking for a known node type.</p>

<div class="wp_codebox"><table width="100%" ><tr id="p17758"><td class="code" id="p177code58"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>node.<span style="color: #660066;">constructor</span> <span style="color: #339933;">===</span> HTMLAnchorElement<span style="color: #009900;">&#41;</span> <span style="color: #006600; font-style: italic;">// do something</span>
<span style="color: #006600; font-style: italic;">// OR...</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>node <span style="color: #000066; font-weight: bold;">instanceof</span> HTMLAnchorElement<span style="color: #009900;">&#41;</span> <span style="color: #006600; font-style: italic;">// do something</span></pre></td></tr></table></div>

<p>I ran <a href="http://labs.calyptus.eu/NodeName/performance-test.html">this performance test</a> in various browsers. It traverses all nodes in a large HTML documents and checks which ones are anchor nodes. It first does a blank run to eliminate any initialization quirks. Then it does a control run without the anchor check. Then it tests each of the above models.</p>
<p><strong>IE6 and IE7</strong> will obviously fail since they don&#8217;t support the HTMLAnchorElement constructor/prototype. For that case you would have to fall back to the nodeName property.</p>
<p><strong>IE8</strong> will be slightly slower with the constructor check than the nodeName check. But the difference is marginal in the overall scope of IE&#8217;s slowness.</p>
<p><strong>WebKit</strong> will gain significant performance using the constructor check. The difference is relatively small to the overhead of manually walking the tree. However, if you take the control value from the blank run into account, the difference of just the node type checks will be significant (several times faster). The slow part is the WebKit DOM API, so you will see this with both JavaScriptCore and V8 (Safari and Chrome respectively).</p>
<p><strong>Firefox</strong> will be slower on the first run for some weird reason. But in subsequent runs the constructor check will be faster than the nodeName check.</p>
<p><em>As a side note, node.tagName is no different. That is just an alias for node.nodeName.</em></p>
<p><em>In <a href="http://ejohn.org/blog/nodename-case-sensitivity/">John Resig&#8217;s case sensitivity</a> he discusses the case inconsistencies of the nodeName property in various contexts and the impact on performance. For example, in IE, the value of nodeName of unknown elements (like the new HTML5 elements) keeps it original case as in the markup.</em></p>
<p><em>This means that any proper CSS selector search for such elements would have to run a case-insensitive match against the nodeName property. Unfortunately the little trick I&#8217;ve shown above doesn&#8217;t remedy this problem because unknown elements will be lacking a known constructor. However, known Elements can still utilize this trick as a slight performance boost, while letting unknown element fallback to a case insensitive match.</em></p>
<p><em>UPDATE: I added a case-insensitive match to the <a href="http://labs.calyptus.eu/NodeName/performance-test.html">performance tests</a> using regular expressions &#8211; showing the added overhead compared to constructor checking.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.calyptus.eu/seb/2009/11/the-performance-of-nodename/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

