<?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>Jens Arps &#187; CommonJS</title>
	<atom:link href="http://jensarps.de/tag/commonjs/feed/" rel="self" type="application/rss+xml" />
	<link>http://jensarps.de</link>
	<description></description>
	<lastBuildDate>Fri, 25 Nov 2011 16:16:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>EmbedJS 0.2 and AMD</title>
		<link>http://jensarps.de/2011/10/17/embedjs-0-2-and-amd/</link>
		<comments>http://jensarps.de/2011/10/17/embedjs-0-2-and-amd/#comments</comments>
		<pubDate>Mon, 17 Oct 2011 14:44:36 +0000</pubDate>
		<dc:creator>Jens Arps</dc:creator>
				<category><![CDATA[EmbedJS]]></category>
		<category><![CDATA[Framework Peace]]></category>
		<category><![CDATA[AMD]]></category>
		<category><![CDATA[CommonJS]]></category>
		<category><![CDATA[embedjs]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[modules]]></category>
		<category><![CDATA[uxebu]]></category>

		<guid isPermaLink="false">http://jensarps.de/?p=352</guid>
		<description><![CDATA[[Note: This is a cross-post. I also published this on the uxebu blog.]During JSConf.eu, we released EmbedJS 0.2. That release was mainly about a fundamental architectural change: the move to the AMD pattern for our features. Let me explain why we decided to do this, why we think this is a big step forward and [...]]]></description>
			<content:encoded><![CDATA[<p>[<em>Note: This is a cross-post. I also published this on the <a href="http://uxebu.com/blog/2011/10/17/embedjs-0-2-and-amd/" target="_blank">uxebu blog</a>.</em>]</p><p>During JSConf.eu, we released EmbedJS 0.2. That release was mainly about a fundamental architectural change: the move to the AMD pattern for our features. Let me explain why we decided to do this, why we think this is a big step forward and what this means for the user.</p>
<p><span id="more-352"></span></p>
<h2>Modules</h2>
<p>AMD stands for “Asynchronous Module Definition”. So, what are modules? I’ll quote the definition from the <a href="http://wiki.commonjs.org/wiki/Modules/1.1" target="_blank">CommonJS Module specification</a>, as it describes it very well:</p>
<blockquote><p>This specification addresses how modules should be written in order to be interoperable among a class of module systems that can be both client and server side, secure or insecure, implemented today or supported by future systems with syntax extensions. These modules are offered privacy of their top scope, facility for importing singleton objects from other modules, and exporting their own API.</p></blockquote>
<p>So, modules are isolated parts of code that live in their own scope and are kind of self-contained. Well, that is pretty much how we see the individual Features in EmbedJS – we made our feature implementations as small as possible and reduced dependencies as much as possible. Many of EmbedJS’ features are also browser-independent, so why not make it possible to use some of the tools in a non-browser environment?</p>
<p>(If you want to learn more on modules and why we need them, I recommend <a href="http://twitter.com/briancavalier" target="_blank">@briancavalier</a>‘s <a href="http://briancavalier.com/presentations/pgh-js-amd-10-2011/" target="_blank">presentation on modules</a>.)</p>
<h2>Features in EmbedJS</h2>
<p>So far, I didn’t really explain what I mean with “Features”, so let me do another quote, this time from the <a href="http://uxebu.github.com/embedjs/" target="_blank">Project Page</a>:</p>
<blockquote><p>EmbedJS uses the concept of features: Functionalities are split up into features, as fine-grained as possible, and each feature might have multiple implementations.</p></blockquote>
<p>Our Features are kinda small and contain only few methods, sometimes even just one. The asyc-promise feature, for example, will get you Promises, and the transport-jsonp feature will get you a method for pull in data via jsonp – and that’s it.  If multiple methods are contained within one feature, this is because they are too closely related to each other to split them up, like the html-class feature, which contains the <code><span class="text">addClass</span></code>, <code><span class="text">removeClass</span></code>, <code><span class="text">toggleClass</span></code> and <code><span class="text">hasClass</span></code> methods.</p>
<h2>AMD vs CommonJS Modules 1.1</h2>
<p>Now that we knew modules were the way to go, there was another, quite important question to solve: There are two common patterns for modules, so which one do we want to apply? One pattern is described in the above mentioned CommonJS Wiki, the other pattern is described in the <a href="https://github.com/amdjs/amdjs-api/wiki/AMD" target="_blank">AMD wiki</a>.</p>
<p>Well, there have been <a href="http://tagneto.blogspot.com/2011/04/on-inventing-js-module-formats-and.html" target="_blank">some</a> <a href="http://unscriptable.com/index.php/2011/09/30/amd-versus-cjs-whats-the-best-format/" target="_blank">blog</a> <a href="http://blog.millermedeiros.com/2011/09/amd-is-better-for-the-web-than-commonjs-modules/" target="_blank">posts</a> lately that compare the pros and cons of each of them, so I don’t want to repeat all of this – but I’m hiving a similar tendency towards AMD. Besides this, there was another big reason to go with AMD: Remember, EmbedJS is based on the <a href="http://dojotoolkit.org/" target="_blank">Dojo Toolkit</a>, and it’s a <a href="http://dojofoundation.org/" target="_blank">Dojo Foundation Project</a> – and we hope that the efforts that went into making EmbedJS might flow back into the Dojo Toolkit one day. And as the Dojo Toolkit uses the AMD approach, the decision was quickly made to do so as well.</p>
<h2>Implications for EmbedJS</h2>
<p>There are several huge benefits for EmbedJS in using the AMD approach. The most noteworthy surely is the ease-of-use for developers. In your code, when you find you want an EmbedJS method, you <a href="http://uxebu.github.com/embedjs/docs/" target="_blank">look up the feature name</a> that provides this method, add it to the require statement and there you go. Man, easy.</p>
<p>A second important thing is that EmbedJS now plays really nice with AMD based projects. In fact, you could see EmbedJS now as a collection of small useful modules, that can be easily integrated – and also easily extended.</p>
<p>The third major benefit is that we can now get rid of all the custom tools we built around EmbedJS – you can load features with any AMD loader (though we use and recommend RequireJS) and build it with any AMD optimizer/builder (we recommend r.js).</p>
<p>Let’s have an extra word on</p>
<p><strong>Building</strong></p>
<p>It was always possible with EmbedJS to create a custom build that would contain only the features you wanted/needed in your project. But, you had to use our build tool that we created. And learning using Yet-Another-Build-Tool™ is always… well, let’s just say it would be cool to avoid it (and, not to forget, so is maintaining it). We did a lot to improve that, we created a GUI that allowed you to just “click together” the features you wanted, and we worked on a dynamic loader that would ease development. But still, the situation was far from ideal, and people just ended up going for our ready-made “kitchensink” builds that contained <em>all</em> of the features.</p>
<p>Now, we still provide those ready-made builds that contain only the implementations for a given platform (and are stripped of require/define calls), but I really hope that using the AMD approach and using an AMD optimizer to deploy will become the more adopted style.</p>
<h2>Q: Cross-target? A: The Feature Plugin</h2>
<p>One goal of EmbedJS is to allow for easy cross-device development. We got rid of run-time branching but instead went for an approach that held the different implementations for a given feature in separate files, so that one only has to deploy the actually needed code to a given device – and not all the alternate implementations, that sit useless in the device’s memory and never get used. We needed to achieve that with “in-house” means provided by the AMD approach. Lucky us, there’s the concept of <a href="https://github.com/amdjs/amdjs-api/wiki/Loader-Plugins" target="_blank">loader-plugins</a>, and so I created a <a href="https://github.com/jensarps/AMD-feature" target="_blank">feature-plugin for AMD loaders</a>. The idea is simple yet effective: You create an implementation map that maps a feature name to an implementation, and if there are multiple implementations, you supply tests that tells the plugin which feature to use.</p>
<p>When you’re ready to deploy, you have two choices: I f you really don’t know on what target your code is going to end up, you can use the dynamic implementation map containing the tests for the optimizer, and you’ll get a build that contains all of the available implementations. Then, during runtime, the feature plugin will run the tests and load the specific implementation. But, if you <em>do</em> know what target your code will run on, you provide a specific implementation map that doesn’t contain tests but directly maps to the according implementations, and you will only have those in your built file.</p>
<h2>Synopsis</h2>
<p>AMD is exactly what we needed to make EmbedJS more what we want it to be – an easy to use JavaScript toolbox that is especially handy for cross-target scenarios such as cross-platform mobile development. So, please don’t hesitate and check it out on Github, read the project page and check out the examples!</p>
<p><strong>Resources / Further Reading</strong></p>
<ul>
<li><a href="https://github.com/uxebu/embedjs" target="_blank">EmbedJS on GitHub</a></li>
<li><a href="http://uxebu.github.com/embedjs/" target="_blank">EmbedJS Project Page</a></li>
<li><a href="http://uxebu.github.com/embedjs/docs/" target="_blank">EmbedJS API Docs</a></li>
<li><a href="https://github.com/jensarps/AMD-feature" target="_blank">AMD-Feature plugin</a></li>
<li><a href="https://github.com/amdjs/amdjs-api/wiki" target="_blank">AMD Wiki</a></li>
<li><a href="http://wiki.commonjs.org/wiki/CommonJS" target="_blank">CommonJS Wiki</a></li>
</ul>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://jensarps.de/2011/10/17/embedjs-0-2-and-amd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Promises with dojo &#8211; a lightweight alternative to dojo.Deferred</title>
		<link>http://jensarps.de/2010/02/03/promises-with-dojo-a-lightweight-alternative-to-dojo-deferred/</link>
		<comments>http://jensarps.de/2010/02/03/promises-with-dojo-a-lightweight-alternative-to-dojo-deferred/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 23:27:16 +0000</pubDate>
		<dc:creator>Jens Arps</dc:creator>
				<category><![CDATA[Dojo Love]]></category>
		<category><![CDATA[Experiments in Web]]></category>
		<category><![CDATA[CommonJS]]></category>
		<category><![CDATA[dojo]]></category>
		<category><![CDATA[dojox]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[js]]></category>

		<guid isPermaLink="false">http://jensarps.de/?p=190</guid>
		<description><![CDATA[Update: Micheil Smith had a cool idea to improve this and posted it in the comments. I have updated the test page and the code examples to reflect his idea. Thanks Micheil! Update II: Ben Hockey proposed to do the whole thing without using the pub/sub system. I for one think its a good idea, [...]]]></description>
			<content:encoded><![CDATA[<p><em><strong>Update:</strong> <a href="http://twitter.com/Miksago" target="_blank">Micheil Smith</a> had a cool idea to improve this and posted it in the comments. I have updated the test page and the code examples to reflect his idea. Thanks Micheil!</em></p>
<p><em><strong>Update II:</strong> <a rel="nofollow" href="#comment-489">Ben Hockey</a> proposed to do the whole thing without using the pub/sub system. I for one think its a good idea, but in case you want the topic version, I&#8217;ll leave the test page and add <a href="http://jensarps.de/tests/dojo_tests/dojo-release-1.4.0-src/test_Promise_notopic.html" target="_blank">another one</a> with the topic-less version. Thanks Ben!</em></p>
<p><em><strong>Update III</strong>: Dojo 1.5 introduces robust Promises with dojo.deferred as Krys Zyp explains in <a href="http://www.sitepen.com/blog/2010/05/03/robust-promises-with-dojo-deferred-1-5/" target="_blank">this SitePen post</a>.<br />
</em></p>
<p>&#8212;</p>
<p>One of the things/ideas/concepts that I really like about CommonJS is Promises.</p>
<p>Promises? A brief explanation from the <a href="http://wiki.commonjs.org/wiki/Promises" target="_blank">CommonJS API</a>:</p>
<blockquote><p>Promises provide a well-defined interface for interacting with an object  that represents the result of an action that is performed  asynchronously, and may or may not be finished at any given point in  time.</p></blockquote>
<p>To hear more about Promises, I highly recommend <a href="http://www.michaelharrison.ws/weblog/?p=198" target="_blank">these</a> <a href="http://www.sitepen.com/blog/2010/01/19/commonjsjsgi-the-emerging-javascript-application-server-platform/" target="_blank">two</a> posts.<br />
<span id="more-190"></span><br />
That concept is not entirely new. The dojo toolkit has <a href="http://docs.dojocampus.org/dojo/Deferred" target="_blank">dojo.Deferred</a>, which does a similar job. You create a Deferred, add (multiple) callbacks and error handlers to it, and when it fires off, all your handlers get called. But dojo.Deferred is pretty heavyweight. It&#8217;s loads of code. And it works with <code>.addCallback()</code> and <code>.addErrback()</code> methods – not with <code>.then()</code> methods, which provide maximum readability.</p>
<p><strong>The goal</strong></p>
<p>What I want to have is the follwing code running (with dojo):</p>
<pre>asyncComputeTheAnswerToEverything().
    then(addTwo).
    then(printResult, onError);</pre>
<p><em>(This is the example code from the proposed CommonJS Promise API)</em></p>
<p>And I want the execution to continue right after <code>doSomethingAsnyc()</code> – the async call should still be non-blocking. The <code>.then()</code> methods should recieve the results of the previous part of the chain, but still be non-blocking. Luckily, dojo provides a tool that allows us to achieve this: the publish/subscribe system.</p>
<p><strong>Let&#8217;s do it</strong></p>
<p>When we have unique topics for each promise made, we can subscribe the <code>.then()</code> method to the current topic in the chain, and publish the next topic when the data handlers are done computing. Within the <code>then()</code> method we need to check if the data we recieve is an error or not, to determine wich handler we need to call. The spec also demands a progress handler – if we wanted to implement that, we needed to add another topic, but I left that out.</p>
<p>We only need to kick off  the whole thing when we create the first promise, then the rest takes care for itself. Including the changes proposed by Micheil, what you have to do is pretty trivial and you don&#8217;t have to care about unique topics or the pub/sub system at all. The <code>asyncComputeTheAnswerToEverything()</code> function mentioned above would look like the following:</p>
<pre>var asyncComputeTheAnswerToEverything = function(){
	var promise = new dojox.Promise();
	window.setTimeout(function(){ // some async operation
		var data = 42;
		promise.emit(data);
	},2000);
	return promise;
};</pre>
<p>You create a Promise and store a reference to it. You return the promise and use the reference to it to kick off the chain when the data is there. Everything else runs on it&#8217;s own now.<br />
Go to the <a href="http://jensarps.de/tests/dojo_tests/dojo-release-1.4.0-src/test_Promise_notopic.html" target="_blank">test page</a> or theand check the source &#8211; it contains the Promise code and the example functions. Open the console and run <code>testSpec();</code> to start off the example code from the CommonJS API proposal.</p>
<p><strong>Usage</strong></p>
<p>As a namespace to put the Promise into I chose dojox – but choose whatever floats your boat. You can just drop the promise code somewhere into your code, or, if want to <code>dojo.require("dojox.Promise")</code> it, create a file named <code>Promise.js</code> that contains the code and place a <code>dojo.provide("dojox.Promise");</code> as the first line in it. Save the file in the dojox directory and you&#8217;re done. (Well, to be honest, this violates the dojox naming convention, but if its just in your project, it&#8217;s ok and it will work.)</p>
<p>Any questions left? Feel free to leave a comment, @ me at twitter or drop me a line.</p>
<p><strong>References / Files / More<br />
</strong></p>
<ul>
<li><a href="http://wiki.commonjs.org/wiki/Promises" target="_blank">CommonJS Promise API Proposal</a></li>
<li><a href="http://www.sitepen.com/blog/2010/01/19/commonjsjsgi-the-emerging-javascript-application-server-platform/" target="_blank">Post by Kris Zyp @ SitePen blog about CommonJS</a></li>
<li><a href="http://www.michaelharrison.ws/weblog/?p=198" target="_blank">Post on www.michaelharrison.ws about promises and more</a></li>
<li><a href="http://jensarps.de/tests/dojo_tests/dojo-release-1.4.0-src/test_Promise.html" target="_blank">the test page (using topics and pub/sub)</a></li>
<li><a href="http://jensarps.de/tests/dojo_tests/dojo-release-1.4.0-src/test_Promise_notopic.html">the test page (w/o topics, recommended)</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jensarps.de/2010/02/03/promises-with-dojo-a-lightweight-alternative-to-dojo-deferred/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>

