<?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>Eric Feminella</title>
	<atom:link href="http://www.ericfeminella.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ericfeminella.com/blog</link>
	<description>Thoughts on Modern Web Application Development</description>
	<lastBuildDate>Wed, 18 Apr 2012 12:41:25 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Decoupling Backbone Modules</title>
		<link>http://www.ericfeminella.com/blog/2012/04/18/decoupling-backbone-modules/</link>
		<comments>http://www.ericfeminella.com/blog/2012/04/18/decoupling-backbone-modules/#comments</comments>
		<pubDate>Wed, 18 Apr 2012 12:40:52 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[APIs]]></category>
		<category><![CDATA[Backbone]]></category>
		<category><![CDATA[Code Review]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Object Oriented Design]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Test Driven Development]]></category>

		<guid isPermaLink="false">http://www.ericfeminella.com/blog/?p=4354</guid>
		<description><![CDATA[<p>One of the principle design philosophies I have advocated over the years, especially through various articles on this site, has been the importance of decoupling. And while I could go into significant detail to elaborate on the importance of decoupling, suffice it to say that all designs &#8211; from simple APIs to complex applications &#8211; [...]</p>
 ]]></description>
			<content:encoded><![CDATA[<p>One of the principle design philosophies I have advocated over the years, especially through various articles on this site, has been the importance of decoupling. And while I could go into significant detail to elaborate on the importance of decoupling, suffice it to say that all designs &#8211; from simple APIs to complex applications &#8211; can benefit considerably from a decoupled design; namely, with respect to testability, maintainability and reuse.</p>
<section>
<h2>Decoupling in Backbone</h2>
<p>Many of the examples which can be found around the web on <a href="http://documentcloud.github.com/backbone/#" target="_blank">Backbone</a> are intentionally simple in that they focus on higher level concepts without diverging into specific implementation or design details. Of course, this makes sense in the context of basic examples and is certainly the right approach to take when explaining or learning something new. Once you get into real-world applications, though, one of the first things you&#8217;ll likely want to improve on is how modules communicate with each other; specifically, how modules can communicate without directly referencing one another. </p>
<p>As I have mentioned <a href="http://www.ericfeminella.com/blog/2012/04/10/persisting-backbone-collections/" target="_blank">previously</a>, Backbone is an extremely flexible framework, so there are many approaches one could take to facilitate the decoupling of modules in Backbone; the most common of which, and my preferred approach, is decoupling by way of events.</p>
<h3>Basic Decoupling with Events</h3>
<p>The simplest way to facilitate communication between discreet modules in Backbone is to have each module reference a shared event broker (a pub /sub implementation). Modules can register themselves to listen for events of interest with the broker, and modules can also communicate with other modules via events as needed. Implementing such an API in Backbone is amazingly simple, in fact, so much so that the documentation provides an example in the following one liner:</p>
<p></p><pre class="crayon-plain-tag">
var dispatcher = _.clone( Backbone.Events );
  </pre><p></p>
<p>Essentially, the <code>dispatcher</code> simply clones (or alternately, <a href="http://documentcloud.github.com/underscore/#extend" target="_blank">extends</a>) the <a href="http://documentcloud.github.com/backbone/#Events" target="_blank">Backbone.Events</a> object. Different modules can reference the same dispatcher to publish and subscribe to events of interest. For example, consider the following:</p><pre class="crayon-plain-tag">
// A basic shared event broker
var broker = _.clone( Backbone.Events );

var Users = Backbone.Collection.extend{{
    // reference the broker, subscribe to an event
    initialize: function(broker){
        this.broker = broker;
        this.broker.on('users:add', this.add, this);
     },
     add: function(user) {
         console.log(user.id);
     }
};

var UserEditor = Backbone.View.extend({
     el: '#editor',
     // reference the broker
     initialize: function(broker){
        this.broker = broker;
        this.$userId = this.$('#userId');
     },
     add: function() {
        // publish an event
        var user = new User({id: this.$userId().val()});
        this.broker.trigger('users:add', user);
    }
};
// ...
   </pre><p></p>
<p>In the above example, the <code>Users</code> <a href="http://documentcloud.github.com/backbone/#Collection" target="_blank">Collection</a> is completely decoupled from the <code>UserEditor</code> <a href="http://documentcloud.github.com/backbone/#View" target="_blank">View</a>, and vice-versa. Moreover, any module can subscribe to the <code>'users:add'</code> <code>event</code> without having any knowledge of the module from which the event was published. Such a design is extremely flexible and can be leveraged to support any number of events and use-cases. The above example is rather simple; however, it demonstrates just how easy it is to decouple modules in Backbone with a shared <code>EventBroker</code>.</p>
<h3>Namespacing Events</h3>
<p>As can be seen in the previous example, the <code>add</code> <code>event</code> is prefixed with a <code>users</code> string followed by a colon. This is a common pattern used to namespace an event in order to ensure events with the same name which are used in different contexts do not conflict with one another. As a best practice, even if an application initially only has a few events, the events should be namespaced accordingly. Doing so will help to ensure that as an application grows in scope, adding additional events will not result in unintended behaviors.<br />
</section>
<section>
<h2>A General Purpose EventBroker API</h2>
<p>To help facilitate the decoupling of modules via namespaced events, I implemented a general purpose <a href="https://github.com/efeminella/backbone-eventbroker/blob/master/src/backbone-eventbroker.js" target="_blank">EventBroker </a> which builds on the default implementation of the Backbone <a href="http://documentcloud.github.com/backbone/#Events" target="_blank">Events API</a>, adding additional support for creating namespace specific <code>EventBrokers</code> and registering multiple events of interest for a given context.</p>
<h3>Basic Usage</h3>
<p>The <code>EventBroker</code> can be used directly to publish and subscribe to events of interest:</p><pre class="crayon-plain-tag">
var Users = Backbone.Collection.extend{{
    broker: Backbone.EventBroker,
    initialize: function(){
        this.broker.on('users:add', this.add, this);
    },
    add: function(user) {
        console.log(user.id);
    }
};

var UserEditor = Backbone.View.extend({
     el: '#editor',
     broker: Backbone.EventBroker,
     initialize: function(broker){
        this.$userId = this.$('#userId');
     },
     add: function() {
        // publish an event
        var user = new User({id: this.$userId().val()});
        this.broker.trigger('users:add', user);
    }
};
// ...
   </pre><p> </p>
<h3>Creating namespaced EventBrokers</h3>
<p>The <code>EventBroker</code> API can be used to create and retrieve any number of specific namespaced <code>EventBrokers</code>. A namespaced <code>EventBroker</code> ensures that all events are published and subscribed against a specific namespace.</p>
<p>Namespaced <code>EventBrokers</code> are retrieved via <code>Backbone.EventBroker.get(<i>namespace</i>)</code>. If an <code>EventBroker</code> has not been created for the given namespace, it will be created and returned. All subsequent retrievals will return the same <code>EventBroker</code> instance for the specified namespace; i.e. only one unique <code>EventBroker</code> is created per namespace.</p>
<p></p><pre class="crayon-plain-tag">
var Users = Backbone.Collection.extend{{
    // use the 'users' broker
    userBroker: Backbone.EventBroker.get('users'),
    initialize: function(broker){
        this.userBroker.on('add', this.add, this);
    },
    add: function(user) {
        console.log(user.id);
    }
};

var UserEditor = Backbone.View.extend({
    el: '#editor',
    // use the 'users' broker
    usersBroker: Backbone.EventBroker.get('users'),
    // also use the 'roles' broker
    rolesBroker : Backbone.EventBroker.get('roles'),
    initialize: function(broker){
        this.$userId = this.$('#userId');
    },
    add: function() {
        // publish an event
        var user = new User({id: this.$userId().val()});
        this.usersBroker.trigger('add', user);
    }
};
   </pre><p></p>
<p>Since namespaced <code>EventBrokers</code> ensure events are only piped thru the <code>EventBroker</code> of the given namespace, it is not necessary to prefix event names with the specific namespace to which they belong. While this can simplify implementation code, you can still prefix event names to aid in readability if desired.</p>
<p></p><pre class="crayon-plain-tag">
var Users = Backbone.Collection.extend{{
    // use the 'users' broker
    userBroker: Backbone.EventBroker.get('users'),
    initialize: function(broker){
        // prefix the namespace if desired
        this.userBroker.on('users:add', this.add, this);
    },
    add: function(user) {
        console.log(user.id);
    }
};

var UserEditor = Backbone.View.extend({
    el: '#editor',
    // use the 'users' broker
    usersBroker: Backbone.EventBroker.get('users'),
    // also use the unique 'roles' broker
    rolesBroker: Backbone.EventBroker.get('roles'),
    initialize: function(broker){
        this.$userId = this.$('#userId');
    },
    add: function() {
        // publish an event
        var user = new User({id: this.$userId().val()});
        // prefix the namespace if desired
        this.usersBroker.trigger('users:add', user);
    }
};
   </pre><p></p>
<h3>Registering Interests</h3>
<p>Modules can register events of interest with an <code>EventBroker</code> via the default <a href="http://documentcloud.github.com/backbone/#Events-on" target="_blank">on</a> method or the <code>register</code> method. The <code>register</code> method allows for registering multiple event/callback mappings for a given context in a manner similar to that of the <a href="http://documentcloud.github.com/backbone/#View-extend" target="_blank">events hash</a> in a Backbone.View.</p>
<p></p><pre class="crayon-plain-tag">
// Register event/callbacks based on a hash and associated context
var Users = Backbone.Collection.extend( 
{
    broker: Backbone.EventBroker,

    initialize: function() 
    {
	       this.broker.register({
	           'user:select'   : 'select',
	           'user:deselect' : 'deselect',
	           'user:edit'     : 'edit',
	           'user:update'   : 'update',
            'user:remove'   : 'remove'  
	       }, this );
    },
    select: function() { ... },
    deselect: function() { ... },
    edit: function() { ... },
    update: function() { ... },
    remove: function() { ... }&aring;
});
  </pre><p></p>
<p>Alternately, Modules can simply define an &#8220;interests&#8221; property containing particular event/callback mappings of interests and register themselves with an <code>EventBroker</code></p>
<p></p><pre class="crayon-plain-tag">
// Register event/callbacks based on a hash and associated context
var Users = Backbone.Collection.extend( 
{
    // defines events of interest and their corresponding callbacks
    this.interests: {
        'user:select'   : 'select',
        'user:deselect' : 'deselect',
        'user:edit'     : 'edit',
        'user:update'   : 'update',
        'user:remove'   : 'remove'  
    },
    initialize: function() 
    {
        // register this object with the EventBroker
        Backbone.EventBroker.register( this );
    },
    select: function() { ... },
    deselect: function() { ... },
    edit: function() { ... },
    update: function() { ... },
    remove: function() { ... }
});
  </pre><p></p>
</section>
<p>For additional examples, see the <a href="https://github.com/efeminella/backbone-eventbroker" target="_blank">backbone-eventbroker</a> project on github.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ericfeminella.com/blog/2012/04/18/decoupling-backbone-modules/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Persisting Backbone Collections</title>
		<link>http://www.ericfeminella.com/blog/2012/04/10/persisting-backbone-collections/</link>
		<comments>http://www.ericfeminella.com/blog/2012/04/10/persisting-backbone-collections/#comments</comments>
		<pubDate>Tue, 10 Apr 2012 13:34:21 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[APIs]]></category>
		<category><![CDATA[Backbone]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Object Oriented Design]]></category>

		<guid isPermaLink="false">http://www.ericfeminella.com/blog/?p=4256</guid>
		<description><![CDATA[<p>Backbone.js provides a powerful, robust API which focuses primarily on general structure, and the utility of that structure, without requiring a rigid adherence to specific patterns or prescribing certain design philosophies. This focused approach affords developers a significant level of flexibility which can prove to be essential to the success of many modern client side [...]</p>
 ]]></description>
			<content:encoded><![CDATA[<p><a href="http://documentcloud.github.com/backbone/" target="_blank">Backbone.js</a> provides a powerful, robust API which focuses primarily on general structure, and the utility of that structure, without requiring a rigid adherence to specific patterns or prescribing certain design philosophies. This focused approach affords developers a significant level of flexibility which can prove to be essential to the success of many modern client side web applications &#8211; especially when considering the challenges surrounding the ever changing landscape of the web.</p>
<p>Naturally, it follows that such flexibility imparts additional responsibility on the developer. In my experience with architectural frameworks in general, and Backbone in particular, many times this kind of trade off can be quite preferable.</p>
<h2>Extending Backbone</h2>
<p>As mentioned above, Backbone implements the essential building blocks necessary to provide general structure within an application. If a feature is needed which is not provided by default, by design, Backbone allows for easily extending the core APIs in order to implement additional features as needed. In fact, developers are <a href="http://documentcloud.github.com/backbone/#FAQ-extending" target="_blank">encouraged</a> to do so.</p>
<p>Perhaps a good example of this can be found in the need to persist collections in Backbone; that is, interestingly, while the <a href="http://documentcloud.github.com/backbone/#Model" target="_blank">Backbone Model</a> API implements a default <a href="http://documentcloud.github.com/backbone/#Model-save" target="_blank">save method</a>, the <a href="http://documentcloud.github.com/backbone/#Collection" target="_blank">Backbone Collection</a> does not provide a similar API for explicitly saving the models within a collection; that is, saving the collection itself. This feature may have been left out intentionally as part of an initial design decision, as there are some complexities to saving an entire collection as a general use-case;  such as saving deltas, propagating saved state to models within the collection and so forth; or, perhaps it simply may have been an oversite. Regardless of the reason, in certain scenarios it can be useful to save an entire collection rather than saving each model individually &#8211; fortunately, given the flexibility of Backbone, writing an extension to implement this feature is quite simple.</p>
<h2>The PersistableCollection</h2>
<p>As a basic solution for saving a Backbone Collection, I wrote a general abstraction &#8211; <a href="https://gist.github.com/2346564#file_backbone_persistable_collection.js" target="_blank">PersistableCollection</a>, which extends <code>Backbone.Collection</code>, implementing a default <code>save</code> method.</p>
<p>The <code>PersistableCollection</code> API is quite simple in that it essentially just implements a proxy which wraps the collection in a Backbone Model, and ensures there is only one proxy created per collection. The <code>url</code> and <code>toJSON</code> methods, respectively, of the proxy Model reference the <code>url</code> and <code>toJSON</code> methods of the collection to which the proxy is bound. You can either extend <code>PersistableCollection</code> or generate a proxy for an existing collection via the static <code>createProxy</code> method. Examples of each follow.</p>
<h3>Using a PersistableCollection</h3>
<p>A <code>PersistableCollection</code> can be instantiated and used directly, just like a Backbone.Collection:</p><pre class="crayon-plain-tag">
var users = new Backbone.PersistableCollection([
    { name: &quot;Jane&quot;, id: 25},
    { name: &quot;Joe&quot;,  id: 26}
], {
    url: '/users';
);
users.save(); //saves the collection
  </pre><p></p>
<h3>Extending PersistableCollection</h3>
<p>You can extend <code>PersistableCollection</code> and simply invoke <code>save</code> to persist the models in the collection:</p><pre class="crayon-plain-tag">
var Users = Backbone.PersistableCollection.extend({
    url: '/users',
    model: User
});
var users = new Users([[
    { name: &quot;Jane&quot;, id: 25},
    { name: &quot;Joe&quot;,  id: 26}
]);
users.save(); //saves the collection
  </pre><p></p>
<h3>Creating a proxy for an existing collection</h3>
<p>An existing collection can be saved by creating a proxy for it:</p><pre class="crayon-plain-tag">
var users = new UsersCollection([
    { name: &quot;Jane&quot;, id: 25},
    { name: &quot;Joe&quot;,  id: 26}
]);
users.url = '/users';

var proxy = PersistableCollection.createProxy( users );
proxy.save();  //saves the collection
  </pre><p></p>
<p>The <code>PersistableCollection</code> can be used as a general extension for saving entire collections based on the representation of all models within the collection. If you are interested in extending it to account for more specific use-cases, you can simply override the default save implementation as needed. </p>
<p>You can find the gist for the source and spec <a href="https://gist.github.com/2346564" target="_blank">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ericfeminella.com/blog/2012/04/10/persisting-backbone-collections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Preprocessing Modules with RequireJS Optimizer</title>
		<link>http://www.ericfeminella.com/blog/2012/03/24/preprocessing-modules-with-requirejs-optimizer/</link>
		<comments>http://www.ericfeminella.com/blog/2012/03/24/preprocessing-modules-with-requirejs-optimizer/#comments</comments>
		<pubDate>Sat, 24 Mar 2012 05:41:14 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[AMD]]></category>
		<category><![CDATA[Continuous Integration]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://www.ericfeminella.com/blog/?p=4123</guid>
		<description><![CDATA[<p>RequireJS provides an effective means of bundling an application for production deployment by way of the RequireJS Optimizer; which allows for optimizing, concatenating and minifying modules via Node or Rhino. The Optimizer is quite powerful insofar that fine-grained control over various aspects of the optimization process can be implemented with relative ease. One such example [...]</p>
 ]]></description>
			<content:encoded><![CDATA[<p><a href="http://requirejs.org/" target="_blank">RequireJS</a> provides an effective means of bundling an application for production deployment by way of the RequireJS <a href="http://requirejs.org/docs/optimization.html" target="_blank">Optimizer</a>; which allows for optimizing, concatenating and minifying <a href="http://requirejs.org/docs/api.html#define" target="_blank">modules</a> via <a href="http://nodejs.org/" target="_blank">Node</a> or <a href="http://www.mozilla.org/rhino/" target="_blank">Rhino</a>. </p>
<p>The Optimizer is quite powerful insofar that <a href="https://github.com/jrburke/r.js/blob/master/build/example.build.js" target="_blank">fine-grained</a> control over various aspects of the optimization process can be implemented with relative ease. One such example is the ability to specify a callback function to be invoked for each module in the build prior to optimization. This essentially provides the necessary hooks needed to implement a preprocessor.</p>
<h2>The onBuildWrite option</h2>
<p>The <code>optimize</code> method of the RequireJS Optimizer accepts an <code>onBuildWrite</code> option which allows for a callback to be specified. The callback will be invoked prior to serialization of each module within the optimized bundle. Callbacks receive the name, path and contents of the module; and, are always expected to return a value. </p>
<p>For example, consider the following build configuration which demonstrates a basic <code>onBuildWrite</code> callback that simply logs the name of each module processed by the build to the console and, returns the module&#8217;s content unmodified.</p>
<p></p><pre class="crayon-plain-tag">
var config = {
    baseUrl        : 'src',
    appDir         : '../',
    dir            : '../deploy',
    mainConfigFile : '../src/main.js',
    onBuildWrite   : function( name, path, contents ) {
    	console.log( 'Writing: ' + name );
    	return contents
    },
    modules: [{ 
    	name: 'main' 
    }],
};
requirejs.optimize( config, function(results) {...});
 </pre><p></p>
<p>Using the above configuration, when executed against a (contrived) example consisting of just a single module, &#8220;ModuleA&#8221;, in Node, it would output the following to the console:</p><pre class="crayon-plain-tag">
$ node build.js 
Writing: main
Writing: ModuleA

src/main.js
----------------
src/app/module.a.js
src/main.js
 </pre><p></p>
<p>If we were to print out the contents of the files we would see something like this:</p><pre class="crayon-plain-tag">
$ node build.js 
Writing: ModuleA
define( function() {
	return {
		name: &quot;Module A&quot; 
	}
});
Writing: main
require.config( {
    paths : {
        ModuleA : 'app/module.a'
    }
});
require( ['ModuleA'], function( moduleA ){...});

src/main.js
----------------
src/app/module.a.js
src/main.js
 </pre><p></p>
<p>With this in mind, a basic preprocessor can be implemented quite easily using the <code>onBuildWrite</code> option. Assume the <code>main.js</code> script has a token placeholder for the build version like so:</p><pre class="crayon-plain-tag">
/*!
 * #version
 */
require.config( {
    paths : {
        ModuleA : 'app/module.a',
    }
});
require( ['ModuleA'], function( moduleA ) {...});
 </pre><p></p>
<p>We can implement a simple preprocessor which replaces the <code>#version</code> token with a build date as follows:</p><pre class="crayon-plain-tag">
var config = {
    baseUrl        : 'src',
    appDir         : '../',
    dir            : '../deploy',
    mainConfigFile : '../src/main.js',
    onBuildWrite   : function( name, path, contents ) 
    {
        console.log( 'Writing: ' + name );

    	if ( name === 'main' ) 
        {
            // output the original source contents
            console.log( contents );
                
            // perform transformations on the original source
    		contents = contents.replace( /#version/i, new Date().toString() );
                
            // output the processed contents
    		console.log( contents );
    	}
        // return contents
    	return contents;
    },
    modules: [{ 
    	name: 'main' 
    }],
};
requirejs.optimize( config, function(results) {...});
 </pre><p></p>
<p>The above <code>onBuildWrite</code> callback logs the original contents, replaces the <code>#version</code> token with the current date, logs the result and returns the processed content. The output of which would be similar to the following:</p><pre class="crayon-plain-tag">
$ node build.js
Writing: main
/*!
 * #version
 */
require.config( {
    paths : {
        ModuleA : 'app/module.a'
    }
});
require( ['ModuleA'], function( moduleA ) {...});
/*!
 * Fri Mar 23 2012 23:35:17 GMT-0400 (EDT)
 */
require.config( {
    paths : {
        ModuleA : 'app/module.a'
    }
});
require( ['ModuleA'], function( moduleA ) {...});

src/main.js
----------------
src/app/module.a.js
src/main.js
 </pre><p></p>
<p>As can be seen in the above examples, implementing a basic preprocessor is rather simple to accomplish with the RequireJS Optimizer. The ability to do so allows for some interesting possibilities and is certainly something worth checking out if you are leveraging <a href="https://github.com/amdjs/amdjs-api/wiki/AMD" title="Asynchronous Module Definition" target="_blank">AMD</a> via RequireJS.</p>
<p>You can fork an example implementation at <a href="https://github.com/efeminella/requirejs-preprocessor-example" target="_blank">requirejs-preprocessor-example</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ericfeminella.com/blog/2012/03/24/preprocessing-modules-with-requirejs-optimizer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing Handlebars Helpers with Jasmine</title>
		<link>http://www.ericfeminella.com/blog/2012/03/13/testing-handlebars-helpers-with-jasmine/</link>
		<comments>http://www.ericfeminella.com/blog/2012/03/13/testing-handlebars-helpers-with-jasmine/#comments</comments>
		<pubDate>Tue, 13 Mar 2012 21:36:49 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[APIs]]></category>
		<category><![CDATA[Handlebars]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Jasmine]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Object Oriented Design]]></category>
		<category><![CDATA[Template Engines]]></category>

		<guid isPermaLink="false">http://www.ericfeminella.com/blog/?p=3991</guid>
		<description><![CDATA[<p>For some time now, I have primarily been using logic-less templating solutions as they allow for a greater separation of concerns in comparison to many of their logic-based counterparts. By design, the decoupling of logic-less templates imparts greater overall maintainability in that templates become considerably less complex, and therefore, considerably easier to maintain and test. [...]</p>
 ]]></description>
			<content:encoded><![CDATA[<p>For some time now, I have primarily been using logic-less templating solutions as they allow for a greater separation of concerns in comparison to many of their logic-based counterparts. By design, the decoupling of logic-less templates imparts greater overall maintainability in that templates become considerably less complex, and therefore, considerably easier to maintain and test.</p>
<p><a href="http://handlebarsjs.com" title="Handlebars" target="_blank">Handlebars</a>, my preferred logic-less templating engine, simplifies testing even further via it&#8217;s elegant <a href="http://handlebarsjs.com/#helpers" title="Handlebars Helpers" target="_blank">Helper API</a>. While Handlebars may not be the fastest templating solution available, I have found it to be the most testable, reusable and thus, maintainable.</p>
<h2>Custom Handlebars Helpers</h2>
<p>Since Handlebars is a logic-less templating engine, the interpolation of values which require logical operations and/or computed values is facilitated via Helpers. This design is quite nice in that template logic can be tested in isolation from the context in which it is used; i.e. the templates themselves. In addition to the common built-in <a href="http://handlebarsjs.com#builtins" title="Block Helpers" target="_blank">Block Helpers</a>, custom Helpers can easily be registering in order to encapsulate the logic used by your templates.</p>
<h4 id="registering-helpers">Registering Custom Helpers</h4>
<p>Registering Custom Helpers is as simple as invoking <code>Handlebars.registerHelper</code>; passing the string name of the helper which is to be registered, followed by a callback which defines the actual helpers implementation.</p>
<p>Consider the following custom Helper example, which, given a string of text, replaces plain-text URLs with anchor tags:</p><pre class="crayon-plain-tag">
( function() 
{
	// define markup enhancement regex
	var protocol = /(\b(https?|ftp):\/\/[-A-Z0-9+&amp;@#\/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#\/%=~_|])/gim,
	       scheme   = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
			
	/*
	    * Registers a Helper method with Handlebars which, given a string of
	    * plain text or existing markup, provides enhancements of plain text 
	    * URLs, converting them to their respective anchor tag equivalents.
	    */
	Handlebars.registerHelper( 'enhance', function( text )
	{
		text = text.replace( protocol, '&lt;a href=&quot;$1&quot; target=&quot;_blank&quot;&gt;$1&lt;/a&gt;');
		text = text.replace( scheme,   '$1&lt;a href=&quot;http://$2&quot; target=&quot;_blank&quot;&gt;$2&lt;/a&gt;' );
		
		return new Handlebars.SafeString( text );
	});
}());
  </pre><p><span class="figure">(<a href="https://gist.github.com/2034192#file_enhance.helper.js" target="_blank">Gist</a>)</span></p>
<p>As can be seen in the above example, custom Handlebars Helpers are registered outside the context of the templates in which they are used. This allows us to test our custom Helpers quite easily.</p>
<h2>Testing Custom Helpers</h2>
<p>Generally, I prefer to abstract testing custom Helpers specifically, and test the actual templates which use the Helpers independently from the Helpers. This allows for greater portability as it promotes reuse in that common custom Helpers (and their associated tests) can then be used across multiple projects, regardless of the templates which use them. While one can test Handlebars implementation code with any testing framework, in this example I will be using <a href="http://pivotal.github.com/jasmine/" target="_blank">Jasmine</a>.</p>
<p>Essentially, testing Custom Helpers is much the same as testing any other method. The only point to be noted is that we first need to reference the helper from the Handlebars.helpers namespace. Ideally this could be avoided as, should the namespace happen to change, so, too, will our tests need to change. That being said, the probability of such a change is unlikely.</p>
<p>Using the <a href="#registering-helpers">above</a> example, in a Jasmine spec, the <code>enhance</code> helper can be referenced as follows:</p><pre class="crayon-plain-tag">
describe( 'Custom Handlebars Helpers', function()
{
	// define a reference to the underlying helpers namespace.
        // we can then access our helpers as methods and test them
        // as needed
	var helpers = Handlebars.helpers;
});
 </pre><p></p>
<p>Then we can test that the helper was registered:</p><pre class="crayon-plain-tag">
describe( 'Custom Handlebars Helpers', function()
{
	var helpers = Handlebars.helpers;
	
    describe( 'The &quot;enhance&quot; markup helper', function()
    {
        it ( 'should be registered', function()
        {
            expect( helpers.enhance ).toBeDefined();
        });
    })
});
 </pre><p></p>
<p>We can then test any expectation. For example, the <code>enhance</code> helper should return a <strong>Handlebars.SafeString</strong>. We can test this as follows:</p><pre class="crayon-plain-tag">
describe( 'Custom Handlebars Helpers', function()
{
	// define a reference to the underlying helpers object.
	var helpers = Handlebars.helpers;
	
    describe( 'The &quot;enhance&quot; markup helper', function()
    {
        it ( 'should be registered', function()
        {
            expect( helpers.enhance ).toBeDefined();
        });
        
        it ( 'should return a Handlebars.SafeString', function()
        {
            var isSafeString = helpers.enhance(&quot;&quot;) instanceof Handlebars.SafeString
            expect( isSafeString).toBeTruthy();
        });
    })
});
 </pre><p></p>
<p>The <code>enhance</code> helper is expected to replace plain-text URLs with anchor tags. Before testing this, though, we should first test that it preserves existing markup. In order to test this use-case, we first need to access the return value from our custom Helper, we can do this by referencing the <code>string</code> property of the <strong>Handlebars.SafeString</strong> returned by our Helper:</p><pre class="crayon-plain-tag">
describe( 'Custom Handlebars Helpers', function()
{
	// define a reference to the underlying helpers object.
	var helpers = Handlebars.helpers;
	
    describe( 'The &quot;enhance&quot; markup helper', function()
    {
        it ( 'should be registered', function()
        {
            expect( helpers.enhance ).toBeDefined();
        });
        
        it ( 'should return a Handlebars.SafeString', function()
        {
            var isSafeString = helpers.enhance(&quot;&quot;) instanceof Handlebars.SafeString
            expect( isSafeString).toBeTruthy();
        });
        
        it ( 'should preserve existing markup', function()
        {
            var expected = '&lt;strong&gt;Some unescaped markup&lt;/strong&gt; and a &lt;a href=&quot;#&quot;&gt;link&lt;/a&gt;';

            // We access the SafeString.string property to test 
            // our actual return value...
            var actual   = helpers.enhance( expected ).string;
        	
            expect( actual ).toEqual( expected );
        });
    })
});
 </pre><p></p>
<p>Finally, we test that our <code>enhance</code> Helper replaces URLs with anchor tags using the above techniques:</p><pre class="crayon-plain-tag">
describe( 'Custom Handlebars Helpers', function()
{
	// define a reference to the underlying helpers object.
	var helpers = Handlebars.helpers;
	
    describe( 'The &quot;enhance&quot; markup helper', function()
    {
        it ( 'should be registered', function()
        {
            expect( helpers.enhance ).toBeDefined();
        });
        
        it ( 'should return a Handlebars.SafeString', function()
        {
            var isSafeString = helpers.enhance(&quot;&quot;) instanceof Handlebars.SafeString
            expect( isSafeString).toBeTruthy();
        });
        
        it ( 'should preserve existing markup', function()
        {
            var expected = '&lt;strong&gt;Some unescaped markup&lt;/strong&gt; and a &lt;a href=&quot;#&quot;&gt;link&lt;/a&gt;';

            // We access the SafeString.string property to test 
            // our actual return value...
            var actual   = helpers.enhance( expected ).string;
        	
            expect( actual ).toEqual( expected );
        });
        
        it ( 'should replace URLs with anchor tags', function()
        {
            var expected = 'Check out &lt;a href=&quot;http://handlebarsjs.com&quot; target=&quot;_blank&quot;&gt;http://handlebarsjs.com&lt;/a&gt;'
                actual   = helpers.enhance( 'Check out http://handlebarsjs.com' );
        	
            expect( actual.string ).toEqual( expected );
        });
    })
});
 </pre><p><span class="figure">(<a href="https://gist.github.com/2034192#file_enhance.helper.spec.js" target="_blank">Gist</a>)</span></p>
<p>We now have a complete test against our custom Helper, and all is green:<br />
<a class="img-link" href="http://code.ericfeminella.com/articles/examples/js/handlebars-helpers-jasmine/spec/spec.runner.html?showPassed=true" target="_blank"><img src="http://ericfeminella.com/blog/articles/assets/images/custom-helpers-spec.png" alt="Custom Helper Spec" /></a><br />
<span class="note">Note: The above Spec Runner is using the very nice <a href="https://github.com/esbie/jasmine-bootstrap" title="Jasmine Bootstrap" target="_blank">jasmine.BootstrapReporter</a></span></p>
<p>And that&#8217;s all there is to it. You can fork the example at <a href="https://github.com/efeminella/handlebars-helpers-jasmine" title="handlebars-helpers-jasmine" target="_blank">handlebars-helpers-jasmine</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.ericfeminella.com/blog/2012/03/13/testing-handlebars-helpers-with-jasmine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jasmine matchers for Sinon.JS</title>
		<link>http://www.ericfeminella.com/blog/2012/03/07/jasmine-matchers-for-sinon-js/</link>
		<comments>http://www.ericfeminella.com/blog/2012/03/07/jasmine-matchers-for-sinon-js/#comments</comments>
		<pubDate>Wed, 07 Mar 2012 14:19:50 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[APIs]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Object Oriented Design]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[jasmine]]></category>
		<category><![CDATA[jasmine-sinon]]></category>
		<category><![CDATA[mocks]]></category>
		<category><![CDATA[sinon.js]]></category>
		<category><![CDATA[spies]]></category>
		<category><![CDATA[stubs]]></category>
		<category><![CDATA[test driven development]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.ericfeminella.com/blog/?p=3907</guid>
		<description><![CDATA[<p>Lately I have been finding myself writing custom Jasmine matchers which wrap the Sinon.JS API as a convenience. After repeating this process quite a few times I took a step back to see if there was a similar solution already available. After a brief search, I quickly came across jasmine-sinon which, to my surprise, provides [...]</p>
 ]]></description>
			<content:encoded><![CDATA[<p>Lately I have been finding myself writing custom <a href="http://pivotal.github.com/jasmine/" target="_blank">Jasmine</a> matchers which wrap the <a href="http://sinonjs.org/" target="_blank">Sinon.JS</a> API as a convenience. After repeating this process quite a few times I took a step back to see if there was a similar solution already available. </p>
<p>After a brief search, I quickly came across <a href="https://github.com/froots/jasmine-sinon" target="_blank">jasmine-sinon</a> which, to my surprise, provides a very similar matcher API to that which I had began implementing. This library really is quite nice as it essentially provides matchers for all common Sinon.JS <a href="http://sinonjs.org/docs/#spies" target="_blank">spies</a>, <a href="http://sinonjs.org/docs/#stubs" target="_blank">stubs</a> and <a href="http://sinonjs.org/docs/#mocks" target="_blank">mocking</a> use-cases. I am sure <em>jasmine-sinon</em> has saved many developers a lot of time by not having to write their own custom matchers as it has for me.</p>
<p>And so, if you are using both Jasmine and Sinon.JS, and find yourself writing convenience matchers to simplify Sinon.JS integration, jasmine-sinon is an excellent addition which compliments both and is certainly worth considering.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ericfeminella.com/blog/2012/03/07/jasmine-matchers-for-sinon-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Integrating Handlebars Templates in Kendo UI</title>
		<link>http://www.ericfeminella.com/blog/2012/03/05/integrating-handlebars-templates-in-kendo-ui/</link>
		<comments>http://www.ericfeminella.com/blog/2012/03/05/integrating-handlebars-templates-in-kendo-ui/#comments</comments>
		<pubDate>Mon, 05 Mar 2012 16:55:46 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Browsers]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Template Engines]]></category>
		<category><![CDATA[handlebars]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jquery templates]]></category>
		<category><![CDATA[kendo ui]]></category>
		<category><![CDATA[templating]]></category>

		<guid isPermaLink="false">http://www.ericfeminella.com/blog/?p=3589</guid>
		<description><![CDATA[<p>I have been evaluating Kendo UI recently for its rich set of Widget APIs and general HTML5 UI Framework capabilities. One of the first things I wanted to see was how easily Kendo UI Widgets could be integrated with different Templating Engines, Handlebars in particular. By default, Kendo UI provides out of the box templating [...]</p>
 ]]></description>
			<content:encoded><![CDATA[<p>I have been evaluating <a href="http://www.kendoui.com/" title="Kendo UI" target="_blank">Kendo UI</a> recently for its rich set of Widget APIs and general HTML5 UI Framework capabilities. One of the first things I wanted to see was how easily Kendo UI Widgets could be integrated with different Templating Engines, <a href="http://handlebarsjs.com/" title="Handlebars JS" target="_blank">Handlebars</a> in particular.</p>
<p>By default, Kendo UI provides out of the box templating support via <a href="http://demos.kendoui.com/web/templates/index.html" title="Kendo UI Templates" target="_blank">Kendo UI Templates</a> as well as support for <a href="http://api.jquery.com/category/plugins/templates/" title="jQuery Templates" target="_blank">jQuery Templates</a>. While both solutions are quite good, I generally prefer logic-less Templating, with Handlebars being my preferred Template Engine of choice. </p>
<p>Fortunately, as it turns out, integration with Handlebars is actually quite simple. In fact, integration with basically any Template Engine is rather straight forward and can be implemented transparently.</p>
<h2>Integration</h2>
<p>In order to use a Template Engine which is not supported by default, one just needs to implement a Widget&#8217;s specific template property as a method which returns the resulting markup from a compiled template. This is easiest to understand by viewing examples in the context of both default templating as well as specific template integration.</p>
<p>First, templates in Kendo UI are typically implemented as follows (with this particular example being in the context of the <a href="http://demos.kendoui.com/web/grid/rowtemplate.html">rowTemplate</a> of the Kendo UI <a href="http://demos.kendoui.com/web/grid/index.html" target="_blank">Grid</a>):</p><pre class="crayon-plain-tag">	
&lt;script id=&quot;row-tpl&quot; type=&quot;text/x-kendo-template&quot;&gt;
    &lt;tr&gt;
        &lt;td&gt;${ name }&lt;/td&gt;
        &lt;td&gt;${ released }&lt;/td&gt;
    &lt;/tr&gt;
&lt;/script&gt;

&lt;script&gt;
    $( function() 
    {
        // Compile a typical Handlebars template...
        var template = Handlebars.compile( $( '#row-tpl' ).html() );
        	
		$( '#grid' ).kendoGrid (
		{
			dataSource: {
				data: [
					{ 'name': 'iPhone',     'released': 'June 29, 2007' },
					{ 'name': 'iPhone 3G',  'released': 'July 11, 2008' },
					{ 'name': 'iPhone 3GS', 'released': 'June 19, 2009' },
					{ 'name': 'iPhone 4',   'released': 'June 24, 2010' },
					{ 'name': 'iPhone 4S',  'released': 'October 14, 2011' }
				]
			},
         // Kendo UI Widgets directly assign a compiled template
         // to the Widget's template property (in this example, we're
         // using the kendoGrid widget's template property 'rowTemplate')
		    rowTemplate: kendo.template($(&quot;#row-tpl&quot;).html()),
		});
    });
&lt;/script&gt;
  </pre><p>Note that in the above example the compiled template is directly assigned to the <code>rowTemplate</code> property.</p>
<p>Now, to integrate a Template Engine of your choosing (in this example, Handlebars), assign a function to the <code>rowTemplate</code> property. The function assigned accepts a data object (which represents the data of a row) and, simply invoke the complied template with the data object, returning the result as follows:</p><pre class="crayon-plain-tag">
&lt;script id=&quot;row-tpl&quot; type=&quot;text/x-handlebars-template&quot;&gt;
    &lt;tr&gt;
        &lt;td&gt;{{name}}&lt;/td&gt;
        &lt;td&gt;{{released}}&lt;/td&gt;
    &lt;/tr&gt;
&lt;/script&gt;

&lt;script&gt;
    $( function() 
    {
        // Compile a typical Handlebars template...
		var template = Handlebars.compile( $( '#row-tpl' ).html() );

		$( '#grid' ).kendoGrid (
		{
			dataSource: {
				data: [
					{ 'name': 'iPhone',     'released': 'June 29, 2007' },
					{ 'name': 'iPhone 3G',  'released': 'July 11, 2008' },
					{ 'name': 'iPhone 3GS', 'released': 'June 19, 2009' },
					{ 'name': 'iPhone 4',   'released': 'June 24, 2010' },
					{ 'name': 'iPhone 4S',  'released': 'October 14, 2011' }
				]
			},
            // To integrate a specific Template Engine, simply have the
            // Widget's template property reference a function which in
            // turn returns the compiled template against the data argument.
			rowTemplate: function( data ) {
				return template( data );
			}
		});
	});
&lt;/script&gt;
  </pre><p></p>
<p>And thats all there is to it. You can try the above example implementation <a href="http://code.ericfeminella.com/articles/examples/templating/kendo.ui.handlebars/" target="_blank">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ericfeminella.com/blog/2012/03/05/integrating-handlebars-templates-in-kendo-ui/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Aptana JavaScript Outline View</title>
		<link>http://www.ericfeminella.com/blog/2012/02/11/aptana-javascript-outline-view/</link>
		<comments>http://www.ericfeminella.com/blog/2012/02/11/aptana-javascript-outline-view/#comments</comments>
		<pubDate>Sun, 12 Feb 2012 03:56:19 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.ericfeminella.com/blog/?p=3553</guid>
		<description><![CDATA[<p>Aptana Studio is a great IDE for developing Web Applications. The fact that it is built on Eclipse and completely free leaves little to be desired. That being said, there is one feature I have always found to be lacking, which is, the Outline View for JavaScript. Or, more precisely, the fact that it dosent [...]</p>
 ]]></description>
			<content:encoded><![CDATA[<p><a href="http://aptana.com/" target="_blank">Aptana Studio</a> is a great IDE for developing Web Applications. The fact that it is built on Eclipse and completely free leaves little to be desired. That being said, there is one feature I have always found to be lacking, which is, the Outline View for JavaScript. Or, more precisely, the fact that it dosent provide an Outline View when your code is sandboxed within an immediate function.</p>
<p>As it turns out, it actually does; only there is a syntactical caveat to it &#8211; your immediate functions must have the closing parentheses defined outside of the function.</p>
<p>For example, while my preferred tool for validating Javascript is <a href="http://www.jshint.com/" target="_blank">JSHint</a>, the much stricter <a href="http://www.jslint.com/" target="_blank">JSLint</a> requires defining an immediate function&#8217;s invocation (i.e. the closing parentheses) within the function:</p>
<p></p><pre class="crayon-plain-tag">
( function(){
}());
  </pre><p></p>
<p>In JSLint, failing to do so, such as the following:</p><pre class="crayon-plain-tag">
( function(){
})();
  </pre><p> </p>
<p>&#8230; results in the following error:</p>
<blockquote><p>Error: Move the invocation into the parens that contain the function.</p></blockquote>
<p>Being somewhat used to conforming to these (arguably unnecessary) rules, after some trial and error I found that adhering to JSLint&#8217;s requirements was in fact the cause of Aptana failing to provide an Outline View. </p>
<p>The solution to this problem is quite simple, just keep the invocation outside of the immediate function and Aptana will display the correct Outline View. Technically, I would consider this a bug on Aptana&#8217;s part and therefore have filed <a href="https://jira.appcelerator.org/browse/APSTUD-4364" target="_blank">APSTUD-4364</a>. Hopefully this issue will be resolved. In the interim, I hope this post helps.</p>
<p><strong>Update</strong>: As of <time datetime="2012-04-04">04.05.2012</time>, this has been fixed by the Aptana team. <a href="https://jira.appcelerator.org/browse/APSTUD-4364" target="_blank">Details</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ericfeminella.com/blog/2012/02/11/aptana-javascript-outline-view/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>One-time function initialization</title>
		<link>http://www.ericfeminella.com/blog/2012/02/04/one-time-function-initialization/</link>
		<comments>http://www.ericfeminella.com/blog/2012/02/04/one-time-function-initialization/#comments</comments>
		<pubDate>Sun, 05 Feb 2012 01:02:42 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Mobile]]></category>
		<category><![CDATA[Mobile Web]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://www.ericfeminella.com/blog/?p=3492</guid>
		<description><![CDATA[<p>When developing Mobile Web Applications, even the seemingly marginal micro-optimizations can result in a noticeable performance improvement over time and, therefore should be implemented where possible. One could also argue (and rightly so) that this same principle applies when developing Web Applications on the Desktop; however, in the context of Mobile Web Experiences, such optimizations [...]</p>
 ]]></description>
			<content:encoded><![CDATA[<p>When developing Mobile Web Applications, even the seemingly marginal micro-optimizations can result in a noticeable performance improvement over time and, therefore should be implemented where possible. One could also argue (and rightly so) that this same principle applies when developing Web Applications on the Desktop; however, in the context of Mobile Web Experiences, such optimizations are essential, perhaps even obligatory on the developers part.</p>
<p>In a previous post from a few months back I discussed some of the benefits of <a href="http://www.ericfeminella.com/blog/2011/11/19/function-overwriting-in-javascript/" title="Function Overwriting in JavaScript" target="_blank">function overwriting</a> in JavaScript. One similar performance optimization I regularly employee is that of <em>One-time function initializations</em>.</p>
<p>Conceptually, a <em>One-time function initialization</em> is a rather simple pattern which can be broadly described as follows:</p>
<ol>
<li>An Immediate Function / Self-executing Function performs some initial test conditions.</li>
<li>The Immediate Function returns an anonymous function which, in turn, returns the results of the test conditions. Alternately, the Immediate Function can just return the test condition results.</li>
<li>The anonymous function returned is assigned to a function expression or, the test condition results are assigned directly.</li>
</ol>
<p>An example in code illustrates just how simple this pattern is:</p>
<p></p><pre class="crayon-plain-tag">
var hasSomeFeature = ( function() {
    // implement test logic... for example, testing
    // a feature's existence in the browser against
    // multiple vendor prefixes, etc.

    // return a function which returns the results, or
    // just return the result value if desired...
    return function(){
		// return results...
	};
}() );
  </pre><p></p>
<p>Practical implementation example:</p>
<p></p><pre class="crayon-plain-tag">
var hasWebSockets = ( function( window ) 
{
	var prefixes = 'ms O Moz Webkit'.split(' '),
	    n = prefixes.length,
	    i = 0;
	
	for ( ; i &lt; n; ++i ) {
		if ( window[ prefixes[i] + 'WebSocket'] ) {
			return true;
		}
	}
	return 'WebSocket' in window;
}( this ) );
  </pre><p></p>
<p>Implementing <em>One-time function initializations</em> are quite useful in many situations. Specifically, they are of most value when implemented for use-cases where conditions are too complex to assign to a variable directly and, when the conditions tested only need to be evaluated once, after which re-evaluating the condition would be redundant and unnecessary &#8211; such as certain feature detections. </p>
<p>As a general rule of thumb, if a condition or set of conditions can be tested once; that is, they are guaranteed to not change during the execution of the application and, the tests are too complex to maintain if directly assign to a variable, then implementing One-time function initializations are a small, yet simple and practical optimization.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ericfeminella.com/blog/2012/02/04/one-time-function-initialization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AT&amp;T Best Practices Guide for App Development</title>
		<link>http://www.ericfeminella.com/blog/2012/01/15/att-best-practices-guide-for-app-development/</link>
		<comments>http://www.ericfeminella.com/blog/2012/01/15/att-best-practices-guide-for-app-development/#comments</comments>
		<pubDate>Sun, 15 Jan 2012 11:00:20 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Browsers]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Mobile]]></category>
		<category><![CDATA[Mobile Web]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Tablets]]></category>
		<category><![CDATA[User Experience Design]]></category>

		<guid isPermaLink="false">http://www.ericfeminella.com/blog/?p=3419</guid>
		<description><![CDATA[<p>When considering the various best practices surrounding the design of Mobile Web Experiences and Architectures, such works as the W3C&#8217;s Mobile Web Application Best Practices guide, or the excellent Mobile Web Best Practices site, and of course, the seminal text, Mobile First, are likely to come to mind. The concepts and strategies presented in these [...]</p>
 ]]></description>
			<content:encoded><![CDATA[<p>When considering the various best practices surrounding the design of Mobile Web Experiences and Architectures, such works as the W3C&#8217;s <a href="http://www.w3.org/TR/mwabp/" target="_blank">Mobile Web Application Best Practices</a> guide, or the excellent <a href="http://mobilewebbestpractices.com/" target="_blank">Mobile Web Best Practices</a> site, and of course, the seminal text, <a href="http://www.abookapart.com/products/mobile-first" target="_blank">Mobile First</a>, are likely to come to mind. The concepts and strategies presented in these works are a staple in the design of many modern Mobile Web Experiences and are without question an invaluable resource. In addition to these and other similarly related works, another new and valuable resource has been made available from a very important player in the Mobile Space indeed &#8211; an actual Wireless Carrier, AT&#038;T.</p>
<p>Recently, I was contacted by a representative of the AT&#038;T Developer Program informing me of the research conducted by the <a href="http://www.research.att.com/editions/201201_home.html?fbid=Mu13IZ0xu2h" target="_blank">AT&#038;T Research Labs</a> and, the subsequent resources made available by AT&#038;T as a result of their findings. Since I was unaware of this work, I was very interesting in learning more and, after reading the introductory statements, I was quite eager to apply AT&#038;T&#8217;s recommendations as well; to quote specifically:<br />
<blockquote>We quickly saw that a few, simple design approaches could significantly improve application responsiveness.</p></blockquote>
<p>Having read through the material in it&#8217;s entirety (provided <a href="#resources" target="_self">below</a>) I must say I am rather impressed. The information provided has very real and practical implications on the design of Mobile Web Applications. Specifically, I found the clear and concise explanation of the underlying implementation of the <a href="http://en.m.wikipedia.org/wiki/Radio_Resource_Control">Radio Resource Control (RRC) protocol</a> to be particularly relevant and useful. RRC is by far one of the most important design factors to consider in terms of battery life and Application responsiveness and, as the research suggests, this may not have been common knowledge. </p>
<p>By far, the most interesting and notable aspect of the AT&#038;T Research Lab&#8217;s work in this area is the fact that all of the information provided is applicable in the context of all Wireless Carriers, not just AT&#038;T. That is, the recommendations given, such as those regarding the RRC State Machine, for example, are all based on carrier-independent standards and protocols implemented by all Wireless Carriers. As such, understanding the implementation specifics and recommendations provided is certain to prove valuable for all users of your Application, regardless of their Carrier.</p>
<p>If you haven&#8217;t all ready, I highly recommend reading and applying the principles provided by AT&#038;T&#8217;s research to your current and future Mobile Web Application Designs.</p>
<h2 id="resources">AT&#038;T Research Labs: Mobile Application Resources</h2>
<p><a href="https://developer.att.com/developer/forward.jsp?passedItemId=7200042" target="_blank">Build Efficient Apps</a><br />
<a href="http://www.research.att.com/export/sites/att_labs/techdocs/TD_100229.pdf" target="_blank">Profiling Resource Usage for Mobile Applications: A Cross-layer Approach</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.ericfeminella.com/blog/2012/01/15/att-best-practices-guide-for-app-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Configuring iOS HTTP Monitoring</title>
		<link>http://www.ericfeminella.com/blog/2011/12/16/monitoring-http-traffic-on-ios/</link>
		<comments>http://www.ericfeminella.com/blog/2011/12/16/monitoring-http-traffic-on-ios/#comments</comments>
		<pubDate>Sat, 17 Dec 2011 02:04:29 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Browsers]]></category>
		<category><![CDATA[Mobile]]></category>
		<category><![CDATA[Mobile Web]]></category>
		<category><![CDATA[Tablets]]></category>
		<category><![CDATA[browsers]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[mobile web]]></category>
		<category><![CDATA[proxies]]></category>

		<guid isPermaLink="false">http://www.ericfeminella.com/blog/?p=3378</guid>
		<description><![CDATA[<p>When developing Web Applications for the Mobile Web Experience it is often useful to have a clear view into all HTTP requests and responses sent between the client and server. This is quite simple to accomplish when developing Web Applications for the Desktop as, the browser is running locally so any standard HTTP Monitor will [...]</p>
 ]]></description>
			<content:encoded><![CDATA[<p>When developing Web Applications for the Mobile Web Experience it is often useful to have a clear view into all HTTP requests and responses sent between the client and server. This is quite simple to accomplish when developing Web Applications for the Desktop as, the browser is running locally so any standard HTTP Monitor will suffice. And, while it is a normal part of a typical development workflow to run an application locally the majority of the time, testing on each target device is obviously an essential part of the process as well.</p>
<p>Luckily, with <a href="http://www.charlesproxy.com/" target="_blank">Charles</a>, on iOS this is quite simple to accomplish.</p>
<h2>Configuration</h2>
<p>To configure Charles to proxy all requests from an iOS device, simply follow these basic steps:</p>
<ol>
<li>From your iOS Device, open Settings.</li>
<li>Go to Wi-Fi, select your Network and select the Blue &#8220;arrow&#8221; icon.</li>
<li>Scroll to HTTP Proxy and select the Manual Button.</li>
<li>In the Server field, enter the IP address of your development machine.</li>
<li>In the port field, enter port 8888 (the default port to which Charles binds).</li>
<li>Leave Authentication set to Off.</li>
</ol>
<p>And that&#8217;s all there is to it. Now, open Mobile Safari and go to your Web Application&#8217;s URL (or any page on the web for that matter). On your development machine, in Charles you will receive a prompt with the IP Address of your Mobile Device, click &#8220;Allow&#8221; and you are all set. When you are done working, make sure to turn off HTTP Proxy on your device.</p>
<h3>Additional Note</h3>
<p>While this article may be focused on Mobile Web Applications, these same configurations apply to all HTTP traffic from any application on your device that requires resources over the web. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.ericfeminella.com/blog/2011/12/16/monitoring-http-traffic-on-ios/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>External Templates in jQote2</title>
		<link>http://www.ericfeminella.com/blog/2011/12/12/external-templates-in-jqote2/</link>
		<comments>http://www.ericfeminella.com/blog/2011/12/12/external-templates-in-jqote2/#comments</comments>
		<pubDate>Mon, 12 Dec 2011 12:00:56 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[APIs]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Template Engines]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jqote2]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[templating]]></category>

		<guid isPermaLink="false">http://www.ericfeminella.com/blog/?p=3315</guid>
		<description><![CDATA[<p>The jQote2 API Reference provides plenty of useful examples which are sure to help users get up and running quickly. I found it a bit unclear, though, as to how templates could be loaded externally as, in the reference examples, templates are defined within the containing page. For the sake of simplicity this approach certainly [...]</p>
 ]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://aefxx.com/api/jqote2-reference/" target="_blank">jQote2 API Reference</a> provides plenty of useful examples which are sure to help users get up and running quickly. I found it a bit unclear, though, as to how templates could be loaded externally as, in the reference examples, templates are defined within the containing page. For the sake of simplicity this approach certainly makes sense in the context of examples. However, in practice, templates would ideally be loaded externally. </p>
<p>While <a href="http://aefxx.com/jquery-plugins/jqote2/" target="_blank">jQote2</a> provides a perfect API for templating, it does not provide a method specifically for loading external templates; this is likely due to the fact that loading external templates could easily be accomplished natively in <a href="http://jquery.com/" target="_blank">jQuery</a>. However, since this is a rather common development use case, having such a facility available would be quite useful.</p>
<p>After reviewing the comments I came across a nice example from <a href="http://aefxx.com/" target="_blank">aefxx</a> (the author of jQote2) which demonstrated a typical approach to loading external templates which was simular to what I had been implementing myself. </p>
<p>And so, I wrote a simple jQuery Plug-in which provides a tested, reusable solution for loading external templates. After having leveraged the Plugin on quite a few different projects, I decided to open source it as others may find it useful as well.</p>
<h2>Using the Plugin</h2>
<p>Using the jQote2 Template Loader plugin is rather straight forward. Simply include <a href="http://jquery.com/" target="_blank">jQuery</a>, <a href="http://aefxx.com/jquery-plugins/jqote2/" target="_blank">jQote2</a> and the <a href="https://github.com/efeminella/jqote2-template-loader/blob/master/jquery.jqote2.loader-min.js" target="_blank">jquery.jqote2.loader-min.js</a> script on your page.</p>
<p>As a basic example, assume a file named <code>example.tpl</code> exists, which contains the following template definition:</p>
<p></p><pre class="crayon-plain-tag">
&lt;script type=&quot;text/html&quot; id=&quot;articles_tpl&quot;&gt;
	&lt;![CDATA[
    	&lt;% var article, i, n;
    	   
    	   for ( i = 0, n = this.articles.length; i &lt; n; i++ ) {
			     article = this.articles[i]; 
		 %&gt;
			&lt;article&gt;
				&lt;header&gt;
					&lt;h1&gt;&lt;%= article.name %&gt;&lt;/h1&gt;
				&lt;/header&gt;
				&lt;p&gt;&lt;%= article.text %&gt;&lt;/p&gt;
			&lt;/article&gt;
        &lt;% } %&gt;
	]]&gt;
&lt;/script&gt;
  </pre><p></p>
<p>We can load the <code>example.tpl</code> template file described above via <code>$.jqoteload</code> as follows:</p>
<p></p><pre class="crayon-plain-tag">
$.jqoteload( 'example.tpl', function( templates )
{
	// create some mock articles...
	var articles = [ { name: 'Article A', text: 'Articles A test...'},
					 { name: 'Article B', text: 'Articles B test...'},
					 { name: 'Article C', text: 'Articles C test...'} ];
    // Render the articles...
    $('#articles').jqoteapp( templates.articles_tpl, { 'articles': articles } );
});
  </pre><p></p>
<p>After <code>example.tpl</code> has been loaded, from another context we can access the compiled templates via their template element <code>id</code>. In this example <code>"articles_tpl"</code>.</p>
<p></p><pre class="crayon-plain-tag">
//... within some other context, access the same compiled template
var template = $.jqoteret( 'articles_tpl' );
  </pre><p></p>
<p>You can grab the source and view the example over on the <a href="https://github.com/efeminella/jqote2-template-loader">jQote2 Template Loader</a> Github page.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ericfeminella.com/blog/2011/12/12/external-templates-in-jqote2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>DHTMLX Touch 1.0 Released</title>
		<link>http://www.ericfeminella.com/blog/2011/11/23/dhtmlx-touch-1-0-released/</link>
		<comments>http://www.ericfeminella.com/blog/2011/11/23/dhtmlx-touch-1-0-released/#comments</comments>
		<pubDate>Wed, 23 Nov 2011 13:31:56 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[iPad]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Mobile]]></category>
		<category><![CDATA[Mobile Web]]></category>

		<guid isPermaLink="false">http://www.ericfeminella.com/blog/?p=3284</guid>
		<description><![CDATA[<p>Last week, shortly after I blogged about the release of jQuery Mobile 1.0, I received an email informing me of the release of another Mobile Web Framework: DHTMLX Touch 1.0. Being that I was unfamiliar with DHTMLX Touch (as I have been using jQuery Mobile almost exclusively), I was quite interested to learn more; and, [...]</p>
 ]]></description>
			<content:encoded><![CDATA[<p>Last week, shortly after I blogged about the release of <a href="http://www.ericfeminella.com/blog/2011/11/17/jquery-mobile-1-0-released/" target="_blank">jQuery Mobile 1.0</a>, I received an email informing me of the release of another Mobile Web Framework: <a href="http://www.dhtmlx.com/touch/" target="_blank">DHTMLX Touch 1.0</a>. </p>
<p>Being that I was unfamiliar with <em>DHTMLX Touch</em> (as I have been using <a href="http://jquerymobile.com/" target="_blank">jQuery Mobile</a> almost exclusively), I was quite interested to learn more; and, having tried the <a href="http://www.dhtmlx.com/touch/samples/" target="_blank">Examples</a> and reviewed the <a href="http://docs.dhtmlx.com/touch/" target="_blank">Documentation</a>, I was rather impressed by DHTMLX Touch. </p>
<p>And so, if you haven&#8217;t already, <a href="http://www.dhtmlx.com/blog/?p=1425" target="_blank">check it out</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.ericfeminella.com/blog/2011/11/23/dhtmlx-touch-1-0-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

