<?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>ActionScript &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<atom:link href="https://jessewarden.com/tag/actionscript/feed" rel="self" type="application/rss+xml" />
	<link>https://jessewarden.com</link>
	<description>Software &#124; Fitness &#124; Gaming</description>
	<lastBuildDate>Tue, 07 Aug 2012 17:31:13 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://jessewarden.com/wp-content/uploads/2016/08/cropped-Lambda2-32x32.png</url>
	<title>ActionScript &#8211; Software, Fitness, and Gaming &#8211; Jesse Warden</title>
	<link>https://jessewarden.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Backbone.js for Flash and Flex Developers</title>
		<link>https://jessewarden.com/2012/08/backbone-js-for-flash-and-flex-developers.html</link>
					<comments>https://jessewarden.com/2012/08/backbone-js-for-flash-and-flex-developers.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Tue, 07 Aug 2012 16:42:47 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[backbone]]></category>
		<category><![CDATA[cairngorm]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[dependencyinjection]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[parsley]]></category>
		<category><![CDATA[require]]></category>
		<category><![CDATA[robotlegs]]></category>
		<category><![CDATA[swiz]]></category>
		<category><![CDATA[underscore]]></category>
		<category><![CDATA[wire]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=3268</guid>

					<description><![CDATA[Introduction The JavaScript web development community has a significant amount of application development frameworks, specifically around creating scalable applications using MVC/MVP/MVVM/MVPM/MVPV/MVSC, etc. Flash &#38; Flex have the same, although not as many, nor as many library dependencies. Backbone in particular has some longevity amongst the many frameworks available and has been used in some high [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><a href="http://jessewarden.com/2012/08/backbone-js-for-flash-and-flex-developers.html"><img fetchpriority="high" decoding="async" style="padding-right: 8px; padding-bottom: 8px;" src="http://jessewarden.com/archives/blogentryimages/backboneforas/backbone-for-as-logo.png" alt="" width="320" height="247" align="left" /></a></p>
<h3 style="clear: none;">Introduction</h3>
<p>The JavaScript web development community has a significant amount of application development frameworks, specifically around creating scalable applications using <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a>/<a href="http://martinfowler.com/eaaDev/ModelViewPresenter.html">MVP</a>/<a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">MVVM</a>/<a href="http://martinfowler.com/eaaDev/PresentationModel.html">MVPM</a>/<a href="http://martinfowler.com/eaaDev/PassiveScreen.html">MVPV</a>/<a href="http://martinfowler.com/eaaDev/SupervisingPresenter.html">MVSC</a>, etc. <a href="http://www.adobe.com/products/flash">Flash</a> &amp; <a href="http://www.adobe.com/products/flex">Flex</a> have the same, although not as many, nor as many library dependencies.</p>
<p>Backbone in particular has some longevity amongst the many frameworks available and has been used in some high profile applications (notably <a href="http://pivotaltracker.com">Pivotal Tracker</a>). Since I&#8217;ve recently been fixing a web application project with a varied history, I&#8217;m diving head first into Backbone, and taking a break from diving into <a href="http://angularjs.org/">Angular</a>.</p>
<p>In this article, I&#8217;ll go over what Backbone is, how its features compare to frameworks Flash &amp; Flex Developers are used to, and some implementation details that will help you compare how JavaScript MVC apps compare to Flash and Flex ones.</p>
<p><span id="more-3268"></span>Also, while I&#8217;ll have a lot of future articles on web development, rather than reading 20 billion novels, if you&#8217;re just looking to get immersed in as much web dev as possible to get a 30,000ft view of where things stand, this is a better post to read even if dated. I&#8217;m still learning the web stack, so I&#8217;ll update this post with any inaccuracies pointed out. Just comment or send me an email/tweet.</p>
<h3>What Is Backbone?</h3>
<p>Backbone is basically an MVC framework for writing JavaScript web applications. If you&#8217;ve ever messed with <a href="http://en.wikipedia.org/wiki/Cairngorm_(Flex_framework)">Cairngorm</a>, <a href="http://puremvc.org/">PureMVC</a>, <a href="http://www.robotlegs.org/">Robotlegs</a>, <a href="http://swizframework.org/">Swiz</a>, or <a href="http://www.spicefactory.org/parsley/">Parsley</a>, you&#8217;ll instantly see a lot you recognize. Like a lot of JavaScript MVC frameworks, it is a collection of JavaScript libraries.</p>
<p>Also, it like others has the intentional ability to easily integrate with other toolsets and libraries.Â Examples include UI component frameworks like <a href="http://jquery.com/">jQuery</a> or <a href="http://www.sencha.com/products/touch/">Sencha Touch</a>, HTML template engines like <a href="http://handlebarsjs.com/">Handlebars</a>, and it assumes you&#8217;ll either hand code your CSS or use something like <a href="http://sass-lang.com/">SASS</a>/<a href="http://lesscss.org/">LESS</a> if you need to make your CSS more manageable on larger projects.</p>
<p>While Cairngorm and PureMVC were self contained, Robotlegs depended on <a href="https://github.com/tschneidereit/SwiftSuspenders/">SwiftSuspenders</a> for the <a href="http://martinfowler.com/articles/injection.html">Dependency Injection</a> functionality&#8230; however it is known that you just used Robotlegs without really caring, nor knowing buried in the robotlegs.swc file, there was a Swift Suspenders dependency.</p>
<p>Dependency management is tons harder in JavaScript, but I&#8217;ll briefly cover that plus more on Underscore in a bit. The same holds true for Backbone. It utilizes a library called <a href="http://underscorejs.org/">Underscore</a> to basically fix JavaScript to a certain standard of usability, add many OOP and Array features functional server-side devs love, and to abstract away the browserÂ incompatibilitiesÂ for the 1st and 2nd.</p>
<p>It also utilizes Douglas Crockford&#8217;s <a href="https://github.com/douglascrockford/JSON-js">json.js</a>, the man behind the book &#8220;<a href="http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742">JavaScript: The Good Parts</a>&#8221; and a promoter of using <a href="https://www.google.com/#hl=en&amp;safe=off&amp;sclient=psy-ab&amp;q=closure+vs+prototype&amp;oq=closure+vs+prototype&amp;gs_l=hp.3..0j0i5j0i5i30j0i8i30.3434.5654.2.5772.20.15.0.2.2.0.134.1355.7j7.14.0...0.0...1c.JHUmsVPluXQ&amp;pbx=1&amp;bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&amp;fp=89dccf89cf1c3a70&amp;biw=1052&amp;bih=723">closure based OOP vs. Object.prototype.</a>Â His json library does the same, allowing the JSON format to workÂ seamlesslyÂ in JavaScript regardless of browser; for older browsers it parses, for newer ones it uses the built in parser. You should be using json2 since it doesn&#8217;t mess with the prototype (omg, purism). You&#8217;ll notice, too, just about every article on JavaScript nowadays assumes this part is &#8220;handled&#8221;; you&#8217;ll see a magic &#8220;JSON&#8221; in the code. It&#8217;s implied it comes form this library, is native, or both. In a development environment, you just include all the libraries mentioned at the bottom if your index.html body tag (so all the GUI and CSS dependencies load first) in script tags.</p>
<h3>Why Backbone?</h3>
<p>If you&#8217;re a Flex Developer, you already know why: it&#8217;s an MVC framework. Sold. Feel free to <a href="#backboneevents">skip this section</a> or just skim 4 &amp; 5.</p>
<p>I was thinking of deleting this section, but then read Smashing Magazine&#8217;s <a href="http://coding.smashingmagazine.com/2012/07/27/journey-through-the-javascript-mvc-jungle/">Journey Through The JavaScript MVC Jungle</a>, and decided more details were needed for those who are questioning why they even need an MVC framework.</p>
<p>For those that don&#8217;t, MVC frameworks helpÂ separateÂ out your visual, data, application, and business logic in distinct areas in your code. This allows you to have multiple developers work on the code, the code to more easily scale for larger applications, and to make it more testable. Putting logic in your DOM, aka your JavaScript mashed into your HTML and CSS on a &#8220;page&#8221;, makes things unmaintable, hard to find bugs, and unreadable. &#8230;for larger applications. Just like Flash, there is fine line that&#8217;s blurred as all get out. Whether you use an MVC framework or not depends on:</p>
<ol>
<li>your business</li>
<li>your team</li>
<li>size of your application</li>
<li>multi-device</li>
<li>server-side vs. client side</li>
<li>website vs. app</li>
</ol>
<p><strong>Your Business</strong></p>
<p><strong></strong>For those who have non-negotiable deadlines, any OOP, design patterns, and frameworks usually get in the way. Paying off technical debt never happens much, so spit and duct tape applications are fine. On the other hand if your business is creating code that will have to live for years and/or is a product for consumers or other businesses, using OOP, design patterns, and a framework is a good idea. Usually. Sometimes you need to just launch and get funding. Also, there is always the risk that a &#8220;Prototype&#8221; suddenly becomes &#8220;The Product&#8221;. Starting out with even a few parts in a framework will prevent a lot of pain down the line.</p>
<p><strong>Your Team</strong></p>
<p><strong></strong>If you&#8217;re a 1 woman show, and management has done the estimates to show that all design, development, testing, and bug fixing can be done just by you, great; architect as you see fit.</p>
<p>However, if you&#8217;re on a team environment because your project is of the size that can in fact utilizeÂ multipleÂ designers and developers to create value in tandem, an MVC framework can allow your team to work with each other, in different files, being productive using modern source control systems. Additionally, Backbone like many frameworks has enough industry traction that documentation &amp; answers to common questions/problems are all online. This makes hiring &amp; training both new &amp; existing team resources much cheaper and faster. The code has SOME semblance of structure, even if the original developer(s) didn&#8217;t follow Backbone conventions to a T.</p>
<p><strong>Application Size/Scope</strong></p>
<p><strong></strong>If you&#8217;re application is just a few screens/pages/widgets, use jQuery, shove you&#8217;re services and data into a dozen files and call it a day. You could still even write it where your service and application logic layer was testable to get unit tests, all without the need of a framework. I&#8217;ve seen a lot of Flash Developers take to this route just fine over the past year for both desktop and mobile. Some even threw everything on the sever and just did HTML/CSS on the client.</p>
<p>If, however, you&#8217;re creating a large application with many screens, a lot of client side logic/data caching, and maybe even iterating on a design, then separating things out cleanly via Backbone, or some other framework, is the way to go. Again, this assumes you&#8217;re not using the server for much beyond services. This&#8217;ll ensure when you create new functionality, you know where it goes. WhenÂ revisitingÂ already created functionality, you know where to look for what.</p>
<p><strong>Multi Device</strong></p>
<p><strong></strong>One thing that isn&#8217;t mentioned much is MVC frameworks can help with mutli-device strategies. People attribute that to HTML5 and make the assumption you&#8217;re coding things in a DRY manner and they can be easily reused. Taking your application logic, data/validation, and services OUT of the presentation layer (what the user see&#8217;s) allows you to test &amp; scale each in isolation.</p>
<p>What usually doesn&#8217;t change is you need all/most/some of the same exact code on a phone as you do the tablet and desktop. While the GUI can change, whether a different HTML and CSS template used for different screen sizes, your core application &amp; business logic does not. BackboneÂ especiallyÂ with it&#8217;s use of the PassiveView pattern makes it (mostly) easy to change the underlying html or templates you&#8217;re using. Even if that code isn&#8217;t DRY because of a hard deadline or a challenging design, all your models and services stay the same helping to somewhat mitigate the problem. There are a variety of responsive design techniques you can use to not really change anything.</p>
<p><strong>Server-Side vs. Client Side</strong></p>
<p><strong></strong>This one is easy. If you&#8217;re development shopÂ primarilyÂ does their websites and/or applications server-side, there are a lot of wonderful frameworks out there that are already &#8220;Backbone on the Server&#8221; as it were. Additionally, they have the library support just like JavaScript does to fill in the gaps.Â These include Ruby on Rails, Django for Python, Java&#8217;s Play Framework or GWT, and good ole&#8217; .NET.</p>
<p>In these instances, 90% of the code and design is done on the server, and a tincy bit of client side code or design is done. In these cases, you don&#8217;t need Backbone because you&#8217;re already doing MVC on the server and treating the entire client as the View. The criticism by some is that, even with delivery or raw HTML/CSS/JS that&#8217;s minified and gzipped by the server, you still utilize a lot more bandwidth and http requests onÂ theÂ client. This is not what you want to be doing with mobile. There are a variety of frameworks and design strategies to mitigate this, though.</p>
<p>If you don&#8217;t do server-side development, then you need something. There is a reason Rails, Django, Play, .NET, GTW, etc. all utilize some form of MVC.</p>
<p><strong>Website vs. Application</strong></p>
<p><strong></strong>Finally, what exactly are you building? To me, even though I&#8217;m still learning JavaScript/HTML/CSS stack, theÂ delineationÂ is pretty clear to me. Why anyone can argue, and be correct, that the same Backbone application with large amount of JavaScript and a complicated build process could be made using simple HTML/CSS, and a tincy bit of jQuery&#8230; I just use the first 5 items to make the decision.</p>
<p>If you have a bunch of web designers on your team, they&#8217;re more apt to inherit something and be successful maintaing it if it&#8217;s in a context they&#8217;re used to. Conversely, if you have a lot of software client developers, they&#8217;ll be more apt to maintain something doneÂ primarilyÂ in code.</p>
<p>If they&#8217;re server-side devs, they&#8217;ll typically have larger expectations of a technology stack even compared to client side developers&#8230; hence rather developing on the server instead.</p>
<p>Bottom line, if you&#8217;re just building a website with some progressively enhanced interactivity, you don&#8217;t need a framework. If you&#8217;re doing a lot of service calls, have &#8220;state&#8221; on the client, and have a lot of user interaction &amp; things they need to input, you&#8217;re probably building an application and probably should use a framework.<br />
<a name="backboneevents"></a></p>
<h3>Events</h3>
<p>Many frameworks have a messaging system that&#8217;s independent of the stack it&#8217;s on. This is also sometimes called the &#8220;event bus&#8221;. Cairngorm has CairngormEventDispatcher on top of Flash Player Events. PureMVC has Notifications. Robotlegs injects a special base class with a unique EventDispatcher instance. Backbone, much like ActionScript 2&#8217;s <a href="http://www.adobe.com/support/documentation/en/flex/1/asdocs/mx/events/EventDispatcher.html">EventDispatcher</a>Â or <a href="http://help.adobe.com/en_US/flashlite/dev/2x3x/WS006f4c657bd0baee1e63e3d11cddf884e3-7ffb.html">ASBroadcaster</a> in ActionScript 1, uses the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator pattern</a>Â to add event listening and broadcasting to any JavaScript object. It relies on the Underscore library to do this. Underscore does in fact use the _ as it&#8217;s class name. Yes, there are basic ECMA level event dispatching capabilities in JavaScript, but they don&#8217;t have good cross browser support, and are harder to modify. AS1:</p>
<pre lang="actionscript">var obj = {};
var listener = {};
ASBroadcaster.initialize(obj);
obj.addEventListener(listener);
listener.alert = function()
{
	trace("Alert!");	
};
obj.broadcastMessage("alert", "Sup.");</pre>
<p>AS2:</p>
<pre lang="actionscript">import mx.events.EventDispatcher;
import mx.utils.Delegate;
var obj = {};
var listener = {};
EventDispatcher.initialize(obj);
obj.addEventListener("alert", Delegate.create(listener, onAlert));
listener.onAlert = function(event)
{
	trace("Alert!");	
};
obj.dispatchEvent({type:"alert", target: obj});</pre>
<p>AS3:</p>
<pre lang="actionscript3">import flash.events.EventDispatcher;
import flash.events.Event;

var dispatcher:EventDispatcher = new EventDispatcher();
var listener:Object = {};
listener.alert = function(event:Event):void
{
	trace("Alert!");	
};
listener.addEventListener("alert", listener.alert);
dispatcher.dispatchEvent(new Event("alert"));</pre>
<p>Backbone via Underscore:</p>
<pre lang="javascript">var object = {};

_.extend(object, Backbone.Events);

object.on("alert", function(msg) {
  alert("Triggered " + msg);
});

object.trigger("alert", "an event");</pre>
<p>Notice this uses a callback as an anonymous function. If you&#8217;d prefer a proper function attached to a class or a closure or some other object, you can do that too.</p>
<p>In ActionScript 3, if your events grow, you start utilizing packages to organize Event classes to their domain of interest.</p>
<p><img decoding="async" src="http://jessewarden.com/archives/blogentryimages/backboneforas/package-events.png" alt="" width="309" height="248" /></p>
<p>In Backbone, they want you to utilize namespaces (a colon toÂ separateÂ noun:verb) to delineate them.</p>
<pre lang="javascript">myCollection.trigger("selection:changed", myIndex);
socketWatcher.trigger("user:join", userModel);</pre>
<p>While JavaScript doesn&#8217;t support constants, many IDE&#8217;s can infer them through code hinting / intellisense like <a href="http://www.jetbrains.com/idea/">IntelliJ/Webstorm</a>, <a href="http://www.sublimetext.com/">Sublime</a>, and <a href="http://www.aptana.com/">Aptana</a>. Although magic strings don&#8217;t go away in JavaScript, this is how you can mitigate the growth, make them easier to test, and prevent misspelling bugs.</p>
<p>You can also trigger many events in 1 call by adding a space.</p>
<pre lang="javascript">book.on("change:title change:author", someCallbackFunction);</pre>
<p>Since JavaScript has the same stupid scope challenges that ActionScript 1/pre-Delegate, you can optionally provide a scope (called a context) as the 3rd parameter.</p>
<pre lang="javascript">model.on('change', this.render, this)</pre>
<p>Unlike ActionScript, the Underscore event system allows you to hear about all events via &#8220;all&#8221; which is basically a reserved word/event name.</p>
<pre lang="javascript">var logger = {};
logger.on("all", function(eventName)
{
	console.log("Event: " + eventName);
});</pre>
<p>Notice here I&#8217;m using console which is basically JavaScript&#8217;s trace. This breaks IE. Don&#8217;t do it. Use <a href="http://log4javascript.org/">log4javascript</a> unless you&#8217;re a WebKit Only Kid.</p>
<p>To remove events, in Flash you just use removeEventListener:</p>
<pre lang="actionscript3">myListener.removeEventListener("alert", onAlert);</pre>
<p>Using Underscore, they have a lot more options here.</p>
<pre lang="javascript">// Removes just the `onChange` callback.
object.off("change", onChange);

// Removes all "change" callbacks.
object.off("change");

// Removes the `onChange` callback for all events.
object.off(null, onChange);

// Removes all callbacks for `context` for all events.
object.off(null, null, context);

// Removes all callbacks on `object`.
object.off();</pre>
<p>Finally, dispatchEvent is to trigger. ActionScript:</p>
<pre lang="actionscript3">object.dispatchEvent(new Event("myEvent"));</pre>
<p>Underscore:</p>
<pre lang="javascript">object.trigger("myEvent", arg1, arg2, etc);</pre>
<p>You can pass as many arguments as you want, and they&#8217;ll get passed in.</p>
<p>Take a hint from a guy who survived AS1 and AS2: pass an object as the first and only parameters; it&#8217;ll make your API more flexible and is an easier convention to follow vs. being forced to use event order from 2 disparate places in code.</p>
<p>Let&#8217;s review.</p>
<p>ActionScript: EventDispatcher<br />
Backbone: Underscore.js</p>
<p>ActionScript: addEventListener<br />
Backbone: on</p>
<p>ActionScript: removeEventListener<br />
Backbone: off</p>
<p>ActionScript: dispatchEvent<br />
Backbone: trigger</p>
<p>ActionScript: MyClass extends EventDispatcher<br />
Backbone: _.extend(MyClass, Backbone.Events);</p>
<h3>Backbone.Model</h3>
<p>A Backbone Model is basically a PureMVC Proxy. That is, a Model that handles both access control to your data, change events via the Observer pattern, and it wraps a service layer to some web service that the Model&#8217;s data maps to on the back-end.</p>
<p>In Cairngorm it&#8217;d be basically the same thing. In Robotlegs it&#8217;d be a Model that has a Service injected into it. In Swiz, Parsley, and even in Robotlegs, the Model doesn&#8217;t usually contain validation, nor a service(s) with error handling. Sencha&#8217;s ExtJS and Touch do this as well with their Models, and it&#8217;s a common theme you&#8217;ll see with a lot of JavaScript frameworks. Doesn&#8217;t make it right, just something you&#8217;ll have to wrap your head around. Think a Rails ActiveRecord on the client with the ability to be mapped to various services; like localStorage vs. an actual Ajax call to some web service.</p>
<p>Additionally, it&#8217;s implied they are a single entity. Usually the whole point of Models or ValueObjects in ActionScript was to create a combination of data from both what the middle tier provided, but also things the client needed as well. There wasn&#8217;t always such a tight coupling between a database table and the Model you&#8217;re viewing. This is how Backbone Model&#8217;s are viewed.</p>
<p>Assuming you&#8217;re creating a framework-less Model in ActionScript, you&#8217;d go:</p>
<pre lang="actionscript">package
{
	import flash.events.EventDispatcher;

	class Person extends EventDispatcher
	{
		private var _firstName:String = "Jesse"

		public function get firstName():String
		{
			reutrn _firstName;
		}

		public function set firstName(value:String):void
		{
			if(value !== _firstName)
			{
				_firstName = value;
				dispatchEvent(new Event("firstNameChanged"));
			}
		}

		function Person()
		{
			super();
		}
	}
}</pre>
<p>If you&#8217;re using Flex:</p>
<pre lang="actionscript3">package
{
	import flash.events.EventDispatcher;

	class Person extends EventDispatcher
	{
		[Bindable]
		public var firstName:String = "Jesse";

		function Person()
		{
			super();
		}
	}
}</pre>
<p>Or PureMVC:</p>
<pre lang="actionscript3">package
{
	import flash.events.EventDispatcher;

	class PersonProxy extends Proxy
	{

		public static const NAME:String = "Person";

		private var _firstName:String = "Jesse";

		public function get firstName():String
		{
			return _firstName;
		}

		public function set firstName(value:String):void
		{
			if(value !== _firstName)
			{
				_firstName = value;
				sendNotification("firstNameChanged", _firstName);
			}
		}

		function Person()
		{
			super(NAME);
		}
	}
}</pre>
<p>In Backbone it&#8217;d be:</p>
<pre lang="javascript">Person = Backbone.Model.extend({

	firstName: "Jesse"
});</pre>
<p>Notice how you&#8217;re &#8220;extending&#8221; a Backbone.Model. Classes &amp; inheritance in JavaScript are a rabbit hole (all the things ActionScript 1 fixed in ECMA are still not fixed in JavaScript&#8230; not even in Chrome nightly builds), so for now let&#8217;s just pretend it&#8217;s what you think it is.</p>
<p>For working with Backbone Model&#8217;s, you use the get and set function convention. Sencha&#8217;s ExtJS and Touch do this as well. Meaning, you do not set things like this:</p>
<pre lang="javascript">// Wrong
var person = new Person;
person.firstName = "Cow";</pre>
<p>Instead, you set it:</p>
<pre lang="javascript">// Correct
var person = new Person;
person.set("firstName", "Cow");
// or object syntax
person.set({"firstName": "Cow"});</pre>
<p>The set method will trigger a &#8220;change&#8221; event automatically dispatched (triggered) from your Model. If you pass a</p>
<pre lang="javascript">{silent: true}</pre>
<p>as the 2nd parameter, it won&#8217;t trigger the event.</p>
<p>These events are automatically name spaced to the properties that changed. For example, in Flex, the convention was &#8220;propertyName&#8221; + &#8220;Changed&#8221;, like so:</p>
<pre lang="actionscript3">[Bindable(event="firstNameChanged")]
public var firstName:String = "Jesse";</pre>
<p>In Backbone, while the change will fire for anything, if you&#8217;re just interested in a specific property, you can do the same thing:</p>
<pre lang="javascript">person.on("change:firstName", function(model, firstName)
{
	log("Person's change firstName, model: ", model, ", firstName: ", firstName);
});</pre>
<p>You do NOT have to define these yourself like you do in Flash/Flex, it&#8217;s done &amp; triggered for you automatically based on the property names on your model.</p>
<p>Like Sencha&#8217;s ExtJS, the Models have a validate method that can be applied on a per property basis. If the validate method is there, it&#8217;s run. If it doesn&#8217;t validate your change, the property isn&#8217;t set, and the change event isn&#8217;t triggered, and an error event is triggered instead. You can either listen for these, or pass an error callback into the set method itself.</p>
<p>A Model has a lot of other methods only server-side people care about. The only ones you&#8217;ll care about are fetch, parse, toJSON, and isValid.</p>
<p>Now for the scary things:</p>
<ul>
<li>Model&#8217;s have a fetch function that creates a <a href="http://api.jquery.com/jQuery.ajax/#jqXHR">jQuery XMLHttpRequest</a> instance to populate your model from some url. Basically a lighter weight HTTPService (or nice wrapper for URLRequest).</li>
<li>A built in parse method which defaults to smartly reading JSON responses. In Flash/Flex, we&#8217;re used to either using a Factory class, or a ValueObject that knows how to &#8220;build itself&#8221;.</li>
<li>A save method that does the same, asking jQuery to serialize and save your updated Model.</li>
</ul>
<p>One last thing to note that is mentioned in the 2nd bullet. ALL parsing is basically done in the Model. It&#8217;s assumed your middle tier is giving you JSON (bad assumption for larger companies who areÂ infatuatedÂ withÂ XML. Yes, I know it&#8217;s 2012, they don&#8217;t). You have the option to override the parse function and parse it however you want, like in the case of using XML.</p>
<p>This, as opposed to using Factories inside of your Service class, or using self-building ValueObjects. Then placing the results in your Model&#8230; vs. your Model class doing everything.</p>
<p>Individually these are strange, but ok. Together, they&#8217;re whack. A mash of functionality, at least in Flex projects, I&#8217;m used to separating out&#8230; even without unit tests. You don&#8217;t have to use these functions they provide for you, but it&#8217;s very clear they did a lot of work making it easy as pie to use Backbone with someone like Ruby on Rails without the client doing a lot of work.</p>
<p>Either way, the jQuery ajax calls wrap HTTP requests really well, so it&#8217;s not like you can&#8217;t introspect what&#8217;s going on. Callbacks work and Safari/Chrome/Firefox have better-than-Flash/Flex networking debugging tools as well.</p>
<h3>Backbone Collections</h3>
<p>Some brief notes about Backbone Collections. Like Sencha&#8217;s Ext JS, Model&#8217;s have an implied one to one relationship with some back-end service that populates your Model class. Collections are basically a bunch of Models. So if you get a &#8220;list of Contacts&#8221;, in Backbone it&#8217;d be a &#8220;Collection of Models&#8221;.</p>
<p>Backbone uses Underscore to add 50 billion useful array methods to it so working and filtering your Model lists is easier. The &#8220;nice&#8221; feature of Collections is you can set the Model that it contains, and all our add methods will automatically convert the JSON you pass to it. :: shrugs :: I&#8217;d rather have unit tests verify these access points, or even&#8230; you know&#8230; strong typing. Still, there&#8217;s tons of value if you&#8217;re using formalized JSON; I&#8217;ll show you in a second.</p>
<p>Collections have a lot of the same methods as a Model for interacting with the server, parsing, etc. This is where setting the Model of the Collection handles the parsing/populating for you.</p>
<pre lang="javascript">Backbone.sync = function(method, model) {
  alert(method + ": " + model.url);
};

var Accounts = new Backbone.Collection;
Accounts.url = '/accounts';

Accounts.fetch();</pre>
<p>The fetch method is a Model &amp; Collection method for &#8220;go get data from the server at my url&#8221;. It&#8217;s like HTTPService&#8217;s send method or URLRequest&#8217;s load. It creates a jQuery XMLHTTPRequest internally. For those interested, I believe it&#8217;s using the multiple concurrency option (as opposed to first/last which you could configure for Flex HTTPService).</p>
<p>Notice if the Accounts model property is &#8220;Account&#8221;, then whatever comes back from the server will automatically be parsed to an Account Model. The url is the web service URL.</p>
<p>Also rad is the sync method. There&#8217;s a cool infrastructure here that you can read more about on Backbone&#8217;s site. Suffice to say they&#8217;ve abstracted serialization of your Models, whether you&#8217;re saving to a database or LocaleStorage (the string key value store you get in browsers that has more space the Flash&#8217;s SharedObject). This makes caching, mocking, and testing a lot easier.</p>
<p>One thing I found curious is your Model&#8217;s have a validate function but Collections do not. My guess is it&#8217;s trivial to use a forEach with a validate call, so they saw no need to add. Most Flash/Flex developers don&#8217;t really write these as much as they should. You usually either let the server guys code tell your data is bad, you use unit tests, or hope strong-typing finds problems when creating ValueObjects from UI controls. Sencha follows this validate mentality as well.</p>
<h3>Router</h3>
<p>Web applications are unique in that they have an address. Some even have an address that represents a state they can exist in. There is often a symbiotic relationship between the URL and the application. A different URL can put the application in a different state. Conversely, the application state is reflected in the URL.</p>
<p>The format, however, varies. The short of it is, everyone likes slashes, but # are used for backwardsÂ compatibilityÂ for those browsers that don&#8217;t support the History API (basically IE 9 and below). Backbone&#8217;s Router abstracts this for you.</p>
<p>If you&#8217;ve ever utilized <a href="http://www.gaiaflashframework.com/">Gaia</a> to build a Flash website, you&#8217;ll know exactly what to use Backbone Router for. Sort of. Instead of mapping your web site&#8217;s pages, you&#8217;re mapping both page URL&#8217;s as well as URL query parameters to run functions. Yes, you could have those functions change a page, or just draw a new one. Gaia handled all of this internally including branching, hijacking, and URL modification. Backbone Router does a lot of the same but is a little lower level so you to do a little more work.</p>
<p>There are basically 2 features you can utilize. The first is when you go to a different section or state in your application, you can update the URL in the web browser.</p>
<p>The second is when the URL changes. Whether the user modifies the URL in the url bar, they press the back or forward button, or even if the user comes to the URL via a book mark or copy pasta. All can trigger a callback function for each type of URL so your application can get itself into the proper state, get the data it needs, or whatever else to correctly represent the URL.</p>
<p>Notice the routes hash below:</p>
<pre lang="javascript">var Workspace = Backbone.Router.extend({

  routes: {
    "help":                 "help",    // #help
    "search/:query":        "search",  // #search/kiwis
    "search/:query/p:page": "search"   // #search/kiwis/p7
  },

  help: function() {
    ...
  },

  search: function(query, page) {
    ...
  }

});</pre>
<p>You extend the Router class, and then define the routes in the URL, and what callback function to call. While straightforward, you can use all kinds of string matching for more dynamic URL&#8217;s. Internally, those routes will call addCallback to initialize it. When you want to update the URL, just call navigate.</p>
<p>Using the Backbone.history class, you can monitor change events, support the back button in your app, etc.</p>
<h3>View</h3>
<p>A Backbone.View isn&#8217;t a View that a Flash or Flex Developer would call a View. It&#8217;s actually a Controller class on top of aÂ <a href="http://martinfowler.com/eaaDev/PassiveScreen.html">Passive View</a>Â that allows your GUI to have a less coupled integration into Backbone. All your HTML and CSS, whether made by hand or using a templating library like <a href="http://mustache.github.com/">Mustache</a> or <a href="http://handlebarsjs.com/">Handlebars</a>, has no code in it.</p>
<p>All the code that updates via the Models is done in the View.</p>
<p>All the code that listens for user gestures is done in the View.</p>
<p>So it&#8217;s the Controller in the Passive View pattern. Make sense?</p>
<p>I&#8217;ve seen 2 people utilize Robotlegs Mediators like this. One was a colleague who&#8217;d create MXML with zero ActionScript in it. Just like you do in HTML, he&#8217;d assign click handlers to MXML component id&#8217;s (or Sprite/MovieClip names) all in the Mediator. When his Model Actors would send out change events, he&#8217;d use the injected Models to update the View&#8217;s data usually with intimate knowledge of the view&#8217;s structure since it didn&#8217;t have any getter/setters, nor binding, to help with the drawing.</p>
<p>PureMVC could be done in the same way.Â There was a sect of people in the early Cairngorm days who used a ViewModel in aÂ similarÂ fashion.</p>
<p>A Backbone View was specifically created to handle HTML and CSS, and as such, has a LOT more references than just the passive view reference. Those are:</p>
<ul>
<li>el</li>
<li>id</li>
<li>className</li>
<li>tagName</li>
<li>attributes</li>
</ul>
<div><span style="font-size: medium;"><span style="line-height: 24px;">Just stick to id, and it&#8217;ll act just like a member variable in ActionScript, or an ID in MXML.</span></span></div>
<p>Here&#8217;s a tiny Robotlegs Mediator:</p>
<pre lang="actionscript">package
{
public class AvatarViewMediator extends Mediator
{
	[Inject]
	public var view:AvatarView;

	[Inject]
	public var model:PersonModel;

	public override function onRegister():void
	{
		addContextListener("onPersonModelChanged", updateImage);
		addViewListener("onImageClicked", onImageClicked);
		updateImage();
	}

	private function updateImage(event:Event=null):void
	{
		view.image = model.userImageURL;
	}

	private function onImageClicked(event:MouseEvent):void
	{
		dispatch(new Event("onAvatarImageClicked"));
	}
}
}</pre>
<p>When the ActionScript GUI class is created, it&#8217;s Mediator is created. It immediately updates the Avatar GUI with the latest user image. If the Model ever changes thereafter, the image is immediately updated. Finally if the user clicks on the image, it&#8217;ll dispatch an event on the frameworks event bus to let someone else handle it; maybe a Command, maybe another Mediator&#8230; etc.</p>
<p>Here&#8217;s the equivalent in JavaScript:</p>
<pre lang="javascript">// make a global event bus like Robotlegs, or PureMVC's Notifications
eventBus = _.extend({}, Backbone.Events);
Backbone.Model.prototype.eventBus = Backbone.Collection.prototype.eventBus = Backbone.View.prototype.eventBus = eventBus;

var personModel = new PersonModel;

var AvatarView = Backbone.View.extend({
	id: "avatar-div",

	initialize: function()
	{
		this.model.on("change", this.render, this);
	},

	events:
	{
		"click .avatarImage":	"onImageClick"
	},

	render: function()
	{
		var imageURL = this.model.get("imageURL");
		$(this.el).html(this.template('
&lt;img src="&lt;%= imageURL %&gt;" alt="" /&gt;'));
		return this;
	},

	onImageClick: function()
	{
		this.eventBus.trigger("onAvatarImageClicked");
	}
});

var aView = new AvatarView({model: personModel});</pre>
<p>Using Underscore, we listen for change events from our Model. Also notice View&#8217;s are assumed to have 1 Model. If you&#8217;ve seen any reasonably sized Robotlegs/PureMVC app, you know this isn&#8217;t often the case, heh. It&#8217;s assumed this is not null when the View is created.</p>
<p>The click handler listens for a click event from our HTML div. Our render function, run when the View is shown and when our Model updates, draws itself.</p>
<p>Notice the id is just a string; I actually use the el, or &#8220;HTML element&#8221; to set its html. The template method is an Underscore method to do cool stuff; suffice to say it refreshes the div with a newly updated Image tag with our correct URL from the model. The purists will decry this, saying that HTML should never be put into View&#8217;s and instead you should use a template library like I mentioned above.</p>
<p>Ignore the return this in the render function. That&#8217;s for chaining support, a method for getting functional programmers off, making code unreadable, and helping the browser swallow exceptions.</p>
<p>And now for the hack. You&#8217;ll notice if I want a global event system like Robotlegs, you just create your own eventBus, and shove the mofo on Backbone&#8217;s prototype. Here&#8217;s a <a href="http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/">longer explanation</a> if you care about why. That allows you to then send the application level event in the onImageClick callback.</p>
<p>One thing for those of you who remember ActionScript 2: notice the 3rd parameter of of the model.on. This ensures the callback is executed in the correct scope. It&#8217;s basically ensuring you don&#8217;t have to use <a href="http://www.adobe.com/support/documentation/en/flex/1/asdocs/mx/utils/Delegate.html">Delegate.create</a>. These are pretty hard to debug, too, since you&#8217;ll sometimes get &#8220;method is undefined&#8221; methods which aren&#8217;t true; it&#8217;s actually a null pointer exception since this refers to the function vs. the class. Just be sure to always set it.</p>
<h3>Dependency Injection</h3>
<p>Notice that all the dependencies, in this case the PersonModel, is already created and passed into the View&#8217;s constructor. In larger applications, this isn&#8217;t always the case, or gets unwieldy. There are various Dependency Injection frameworks out there to help with this, such as <a href="https://github.com/cujojs/wire">Wire</a>.</p>
<p>Robotlegs handled this via Dependency Injection as well as through Command startup conventions. Basically, as your application grew, you&#8217;d offload a lot of the startup to wiring up your dependencies, or instantiating them yourself if they required something more than a &#8220;new Thing&#8221;. Things such as &#8220;MainContext&#8221; would become &#8220;StartupCommand&#8221; which then broke off into &#8220;InitializeModels&#8221;, &#8220;InitializeMediators&#8221;, which even later broke off into &#8220;InitializeProductModels&#8221;, etc. You had a refactoring path.</p>
<p>You&#8217;ll eventually want to do the same with Backbone as your applications grow,Â especiallyÂ if your Collections get kind of large. The browsers have a lot better libraries &amp; functionality to serialize &amp; read your data back compared to Flash Player in the browser, so it&#8217;s not always a huge deal to save your data to disk. They also destroy easier too.</p>
<p>Here&#8217;s how you configure a <a href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton</a> OmnitureModel in Robotlegs:</p>
<pre lang="actionscript">// ApplicationContext.as
injector.mapSingleton(OmnitureModel);</pre>
<p>Here&#8217;s how you do it using Wire:</p>
<pre lang="javascript">// ApplicationContext.js
omniModel: {
   create: {
      module: "models/OmnitureModel'
   }
}</pre>
<p>Wire also supports a modicum of binding expressions so if you need some extra data initialized in your created class, whether constructor arguments or not, you can do so. This is invaluable for Backbone View&#8217;s who often need at least 1 Model reference when they boot up.</p>
<p>Although I&#8217;m still learning DI in JavaScript, I found Wire helpful in configuring Backbone Models to work with local data sources instead hardcoded service URL&#8217;s. You just create a locale application context js file (like a new Robotlegs Context file) to configure the application to use locale data sources instead. So far I&#8217;ve been only able to get this to work in a few browsers as you&#8217;ll see below.</p>
<h3>Local File Access</h3>
<p>Flash was nice in that it had a <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/Security.html#sandboxType">localTrusted</a>Â <a href="http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e3f.html">security sandbox</a> later with a unique per system file for <a href="http://blogs.adobe.com/penguinswf/2008/08/secrets_of_the_mmscfg_file_1.html">mms.cfg</a> configuration to allow secure sandboxes. Browsers aren&#8217;t like this.</p>
<p>Firefox requires <a href="http://stackoverflow.com/questions/3481977/is-there-a-way-to-bypass-javascript-jquerys-same-origin-policy-for-local-acce">some config</a> changed to allow this.</p>
<p><a href="http://stackoverflow.com/questions/4556429/disabling-same-origin-policy-in-safari">Safari</a> and <a href="http://stackoverflow.com/questions/3102819/chrome-disable-same-origin-policy">Chrome</a> still want you to launch it in a certain mode.</p>
<p>I still haven&#8217;t figured out IE.</p>
<p>I&#8217;ve been using <a href="http://www.charlesproxy.com/">Charles</a> for mapping to local directories on my machine. This is used to fool the browser into working, even for production URL&#8217;s, so should work in IE when I have more coffee.</p>
<p><a href="http://www.johnkpaul.com/">John Paul</a> suggested I use Underscore&#8217;s <a href="http://underscorejs.org/#wrap">wrap</a> function as another alternative which I haven&#8217;t tried yet.</p>
<h3>Modules / Packages / Dependencies</h3>
<p>As your application grows, you&#8217;ll quickly outgrow initializing everything in your index.html; ie you&#8217;ll start to get a lot of classes. While Backbone comes with Underscore to give you basic inheritance beyond Object.prototype, you still have no package solution like ActionScript 2/3/Java/Ruby/Python/PHP/Corona/C#&#8230; (hell, everyone but JavaScript) give you.</p>
<p>Additionally, you don&#8217;t have a dependency management solution; you have to manually control who&#8217;s loaded, and when. That is simply not feasible in a reasonably sized JavaScript application, even with 1 developer vs. 4.</p>
<p>This is where <a href="http://requirejs.org/">RequireJS</a> comes in.</p>
<p>Considering Require has to account for how you create &#8220;classes&#8221; in a language that provides basically (lol, basic&#8230; yeah&#8230; heh&#8230; sigh&#8230; :: takes a shot ::) 3 ways to do so (<a href="http://www.adobe.com/devnet/html5/articles/javascript-object-creation.html">Object.new</a>, Object.prototype, and closures), various libraries that have their own dependencies, as well as how all libraries handle putting themselves on the global objects (ie window, document, etc.) differently&#8230; Require has a lot of work to do on just cleaning up the language.</p>
<p>ActionScript 1 solved part of this via the <a href="http://livedocs.adobe.com/flashlite/3.0/docs/help.html?content=00004837.html">#initclip</a> / #endinitclip pragmas. You&#8217;d put those at the top of your class with a number, like #initclip 3, and you could then control the load order of classes.</p>
<p>ActionScript 2 solved the packages part by building packages that compiled down to object dot notation, and abstracted both that as well as the #initclip stuff away from developers.</p>
<p>ActionScript 3 gave you namespaces with traits to speed up prototype chain lookup speed.</p>
<p>JavaScript has none of that.</p>
<p>Require tries to do all of that. And then some, such as optimization. Just read the <a href="http://requirejs.org/docs/why.html">why</a>Â and you&#8217;ll get it. Backbone apps work just fine with Require, and I encourage you to do so to ensure your application can reasonably scale on a multi-person team right out of the gate.</p>
<p>Here&#8217;s how you use Robotlegs in a class within a package (set of nested folders):</p>
<pre lang="actionscript">// MainContext.as
package com.jxl.minecraftrecipes.rl
{
	import com.jxl.minecraftrecipes.rl.mediators.FavoritesRecipeViewMediator;
	import com.jxl.minecraftrecipes.rl.mediators.RecipeViewMediator;

	import flash.display.DisplayObjectContainer;

	import org.robotlegs.mvcs.Context;

	import views.FavoritesRecipeView;
	import views.RecipeView;

	public class MainContext extends Context
	{
		public function MainContext(contextView:DisplayObjectContainer=null, autoStartup:Boolean=true)
		{
			super(contextView, autoStartup);
		}

		public override function startup():void
		{
			this.injector.mapSingleton(FavoritesModel);

			mediatorMap.mapView(RecipeView, RecipeViewMediator);
			mediatorMap.mapView(FavoritesRecipeView, FavoritesRecipeViewMediator);

			super.startup();
		}
	}
}</pre>
<p>Here&#8217;s how you do the something similiar in Require:</p>
<pre lang="javascript">// config.js
(function() {
   require.config({
      baseUrl: "./js",
      optimize: "none",
      paths: {
         "../../libs",
         handlebars: "../../libs/handlebars/hbs"
      },
      packages: [
         {
            name: "underscore",
            location: "../../libs/underscore_132",
            main: "underscore",
         },
         {
            name: "backbone",
            location: "../../libs/underscore_132",
            main: "underscore",
         }
   });
}).call(this);</pre>
<p>Basically configure the root directory (&#8220;js&#8221;), set some paths so you can use them either as additional source paths, or short cut names (like I did with handlebars), and finally determine your packages: where they are and what their names are. Keep in mind Require has a strict coding convention for what packages are.</p>
<h3>Optimization</h3>
<p>When you compile a Flex or ActionScript application, here&#8217;s basically what happens:</p>
<ol>
<li>all MXML is converted to ActionScript</li>
<li>all ActionScript is converted to ABC byte code (small, procedural)</li>
<li>ABC is converted to MIR (a language JUST above machine code; easier to target different chipsets &amp; optimizations in MIR)</li>
<li>some MIR is converted to native code, some is compiled natively via JIT, and some just chills out</li>
<li>all of that is compressed via gzip with additional optimizations to shrink it to a small file size (remember, it was made this way when modems ruled t3h interwebz and bandwidth was tincy and faulty)</li>
<li>images are compressed, whether using PNG or JPEG</li>
<li>audio files are compressed (ADPCM, MP3, Speex, etc)</li>
<li>fonts are converted to 1 of the 3 font engines, sometimes decreasing file size as only certain glyphs are converted to specific vector graphics)</li>
<li>any other file is embedded and gzipped</li>
<li>all this is put into a single SWF file, usually on frame 2, with a class on frame 1 to show a preloader and &#8220;new&#8221; frame 2.</li>
</ol>
<p>Why is this good? You get an ultra compressed, self-contained, single HTTP request file with all dependencies delivered to the client in a streaming fashion. And it works. This is why we Flash Devs never got JavaScript&#8217;s eval, because our code is actually compiled. JavaScript in the browser has none of that.</p>
<ul>
<li>All files are un-optimized text. Seems trivial, but for large applications, this can add up. For smart phones and tablets, while sometimes fast, this costs people money.</li>
<li>Since there are multiple files, this is multiple HTTP requests. These take both time to create/destroy, and elongate how long it takes for your application to start and/or transition to a new section. This is really bad on some mobile devices, not just desktop. It&#8217;s REALLY fun to use these apps on slow VPN.</li>
<li>If a class isn&#8217;t loaded let and you try to use it, things break.</li>
<li>Browsers love to swallow null pointer exceptions making the above really challenging to debug.</li>
<li>While you could theoretically remember to load certain files in certain orders, God help you if you ever have to, heck, WANT to refactor. On a multi-person team, even with Git, you&#8217;re eff&#8217;d.</li>
</ul>
<p>Require has a variety of optimization tools that basically combine all your files into a single JS file, strip out all whitespace, convert all your variables to 1 letter variables, amongst other things. Basically makes your code unreadable, too;Â obfuscationÂ isn&#8217;t the goal here, though. There are many others too like <a href="http://www.crockford.com/javascript/jsmin.html">JSMIN</a> and Yahoo&#8217;s <a href="http://developer.yahoo.com/yui/compressor/">YUI</a>, many of which you can <a href="http://refresh-sf.com/yui/">use in a browser</a>.</p>
<p>Conclusions</p>
<p>As you can see, Backbone has a lot of the core features you need to build applications in JavaScript. It has Models that follow the typical Observer pattern of holding your data and broadcasting messages for those who care to know about changes. It has View&#8217;s (which act as Robotlegs Mediators or the Controller on top of PassiveView HTML) allowing you to handle the traditional race condition of &#8220;my data is ready, but my view is not&#8221; vs &#8220;my view is ready but my data is not&#8221; by both accessing Models directly and listening for messages via Underscore&#8217;s messaging system which you can make a global event bus if you wish. Finally, it&#8217;s Router allows you to marry your application as a <a href="http://jessewarden.com/2012/07/finite-state-machines-in-game-development.html">state machine</a> against the browsers&#8217; URL bar to support both deep linking, back/forward navigation, and history.</p>
<p>Riding on top of Underscore, it ensures you have all the basicÂ necessitiesÂ you need for making JavaScript easier to use. Although, I still think if you&#8217;re going to utilize JavaScript swapping out dynamic HTML for Views, then you really need a good templating engine such as Handlebars or Mustache.</p>
<p>The current pain point I&#8217;m still working on and haven&#8217;t figured out yet is unit testing Backbone models. On reasonable sized Flex projects that have issues, my first order of business is to break out the parsing logic and the service logic into separate classes so I can create them as units to be easily tested. This copious <a href="http://jessewarden.com/2012/04/consulting-chronicles-6-refactoring.html">refactoring</a> continues until &#8220;a Model&#8221; consists of a variety fo classes.Â Backbone puts all of them together into 1 class and with browsers having really strict local file access rules + the fact services are actually inside of it via jQuery Ajax calls, it has made it challenging to fake their service calls to fixtures/mocks&#8230; and test only 1 thing. Anyway, I&#8217;m still learning.</p>
<p>Hope this helps!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2012/08/backbone-js-for-flash-and-flex-developers.html/feed</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>Sencha Ext JS is Viable Technology Choice for Flex Developers</title>
		<link>https://jessewarden.com/2012/02/sencha-ext-js-is-viable-technology-choice-for-flex-developers.html</link>
					<comments>https://jessewarden.com/2012/02/sencha-ext-js-is-viable-technology-choice-for-flex-developers.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Tue, 14 Feb 2012 15:10:01 +0000</pubDate>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[coffeescript]]></category>
		<category><![CDATA[enterprise]]></category>
		<category><![CDATA[extjs]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[sencha]]></category>
		<category><![CDATA[touch]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=3015</guid>

					<description><![CDATA[Below, I describe my experiences with Ext JS after the Sencha Fast Track training, my challenges with doing browser based work in a consulting context, and my thoughts on why it matters to Flex Developers. I&#8217;m in a hurry. I don&#8217;t want a history lesson. Get comfortable, this is long. Preface I had the pleasure [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Below, I describe my experiences with Ext JS after the Sencha Fast Track training, my challenges with doing browser based work in a consulting context, and my thoughts on why it matters to Flex Developers.<br />
<span id="more-3015"></span></p>
<p><a href="#conclusions">I&#8217;m in a hurry</a>.</p>
<p><a href="#introduction">I don&#8217;t want a history lesson.</a></p>
<p>Get comfortable, this is long.</p>
<p><strong>Preface</strong></p>
<p>I had the pleasure of attending a 5 day fast track for <a href="http://sencha.com">Sencha&#8217;s</a> <a href="http://www.sencha.com/products/extjs/">Ext JS 4</a> in New York last week with my partners from <a href="http://webappsolution.com">Web App Solution</a>. Of the 13 people that attended, 7 were <a href="http://incubator.apache.org/flex/">Flex</a> Developers working on Enterprise Applications. Yakov and Victor from <a href="http://faratasystems.com/">Farata Systems</a>Â were there and <a href="http://universalmind.com">Universal Mind</a> had <a href="http://twitter.com/johnyanarella">John Yanarella</a> representing.</p>
<p>While the technical future of Flex is extremely bright and exciting, the business andÂ marketingÂ future of it is over. Adobe, with the community&#8217;s help, has ensured that it is in the best hands with the <a href="http://apache.org">Apache foundation</a>. With a multitude of capable, brilliant, and diverse contributors to the open source project, there areÂ definitelyÂ a lot of great things on the horizon for the next <a href="http://incubator.apache.org/flex/">Flex SDK</a>.</p>
<p>Adobe has also ensured, intentionally and unintentionally, it has a limited future which will ensure Flex is no longer invested in any technical capacity from small, medium, and large businesses unless absolutely essential, or under the radar.Â The mobile revolution has happened, and while Flash had the opportunity to play a pivotal role, Macromedia, and later Adobe have failed to take theÂ initiativeÂ and successfully execute on it.</p>
<p>While there is still a significant business &amp; technical advantage from a design, development, and workflow perspective in the <a href="http://adobe.com/products/air/">Adobe AIR</a> stack for developing &amp; deploying on <a href="http://android.com">Android</a> and <a href="http://apple.com/ios/">iOS</a>, Adobe has made it a clear that they perceive it is an opportunity they are not interested in pursuing on the developer front. This is a huge topic mostly discussed from a technical perspective in the community, and only a select few blog articles got it right from a business one&#8230; and even then, those missed it from a technical perspective.</p>
<p>Bottom line, Flex Developers are between a rock and a hard place in the industry right now.</p>
<p>The type of work they do for desktop web applications is different from what Flash Developers do, mainly in team size, project scope, and client base. It&#8217;s not as simple as &#8220;just use <a href="http://jquery.com">jQuery</a>, and move on&#8221;. While the tools &amp; runtime we use are technically sound, even clients who have a technical understanding of the marketplace &amp; toolset will not invest in a perceived abandoned platform. Server-side offerings do not offer the rich client experiences we&#8217;re used to creating. The plethora of frameworks in the web market, both open source and proprietary, do not offer the same tooling, performance, and expedient workflow we have on the Flash Platform.</p>
<p>&#8230; except <a href="http://www.sencha.com/products/extjs/">Ext JS</a>. Sort of.</p>
<p>As stated by John Yanarella at the training last week:</p>
<blockquote><p>&#8220;Out of all of the web based frameworks out there, Sencha&#8217;s Ext JS is the best safety net there is for Flex Developers.&#8221;</p></blockquote>
<p>It has theÂ necessaryÂ component framework, a growing company with enough resources &amp; funding at a specific size behind it, with a competent web &amp; mobile technical story that has the potential for critical mass within an Enterprise context.</p>
<p>Thus, given my company&#8217;s need to offer my clients an HTML5 alternative to Flex, Ext JS seems to fit the bill. Considering time is at a premium nowadays, the fast track <a href="http://www.sencha.com/training/">training</a> Sencha offers seemed like a great opportunity. And I love New York so any excuse to go there is great.</p>
<p>Given the whirlwind that was the past 3 months, as well as reflecting upon what I learned from the training, I thought it prudent to write down my thoughts here. There are a lot of Flex Developers who are looking for direction, so I&#8217;m hoping this is one for them to follow.</p>
<p><strong>Background</strong></p>
<p>As a Flex Developer faced with a forced career change driven by forces beyond my control based on the infamous events of November 9th, 2011, I had 2 choices. Do what I always did back in my 20&#8217;s and dive headlong into the unknown, or let the pioneers get the arrows in their backs as it were. Now that I run a business and am a father of 2 children, I don&#8217;t have the free time I used to back being single and W2. Flash &amp; Flex, even on death march projects, allowed me to get up in the morning fueled by the passion of using my favorite technology, and attack problems full bore.</p>
<p>Surveying the landscape, things were pretty grim&#8230; even for someone positive like me.</p>
<p>While the iOS stack had a clear advantage with both a growing developer base, mature tooling &amp; framework, and customers who actually paid for content, none of my large clients actually hadÂ initiativesÂ around iOS work. Enterprise applications, known for their copious amounts of input needs from the user, do not translate well to the small screen size and lack of keyboards on smart phones and tablets.</p>
<p>As such, while the uptick in service based software shops servicing the needs of clients who need iOS applications has increased, the scope of said projects is not as large and often is more consumer based. The latter is troubling as it&#8217;s hard enough utilizing ActionScript 1 in a deadline driven environment that Design Agencies employ; dodging technical debt for as long as possible in Objective C, even with superior tooling is not appealing when longer and more profitable projects exist with the opportunity to have competent peers beside me vs. being a lone wolf. Learning a lower-level toolset for shorter engagements that pay less makes it a non-starter.</p>
<p>Android, while being easier to deploy to as well as more easily iterating with your customer base, is notorious for it&#8217;s fragmentation, both programming and design. It&#8217;s hard enough for designers to lessen the overall experience via <a href="http://www.zeldman.com/2011/12/29/state-of-the-web-of-apps-devices-and-breakpoints/">responsive web design</a> to compensate for a variety of screen sizes. You now have developers who cannot turn as fast as designers can and thus have to spend more time on a platform that doesn&#8217;t generate nearly as much, if any, revenue from consumers compared to iOS. This doesn&#8217;t even broach the business topic of how do you lessen the maintenance cost on your customer when they have to hire both an iOS and Android developer, or some awesomely expensive hybrid who can do both, to handle both platforms. The other bizarre thing about Android is that it is taking the PC approach to competing on price with iOS and continually increasing market share, yet doesn&#8217;t seem to be generating the service revenue compared to iOS (ie people who own Androids don&#8217;t buy apps as much as those on iOS). Same problem as iOS: Invest in a lower-level technology with massive fragmentation for shorter projects that pay less money&#8230; again, non-starter.</p>
<p>The multi-development &amp; deployment problem was what the web was supposed to solve. While native development does give youÂ significantÂ user experience &amp; tooling advantages, Â  it seems wrong to invest my career for applications that my current client base do not target. Every single large client I&#8217;ve had treats mobile as either a fun skunkworks project,Â experimentÂ with no perceived ROI, or as a necessity with the minimal amount of money devoted to it, sometimes taken from another project&#8217;s budget ad hominem.</p>
<p>Both don&#8217;t bode well for a future career from a consulting perspective in mobile.</p>
<p>While consumers bringing their smartphones, tablets, and technology of choice to work has had a huge impact on large companies, most Enterprise customers still target the desktop web as the main avenue of both B2C &amp; B2B based revenue. While many have made huge and wonderful strides in providing value for their mobile websites, it&#8217;s clear many either provide a lot less functionality than their desktop counterparts, or strain at even that.</p>
<p>With large media companies it&#8217;s a little different. Studies have shown that tablets are better at allowing consumers to consume content whereas desktops/laptops are better for producing content. While &#8220;duh&#8221;, having studies like this made and corroborating themselves verifies what we already know. They have a vested interest in increasing consumers ability to purchase and access that content in a controlled manner.</p>
<p>The problem here is that the budgets for those projects doesn&#8217;t increase with the needed targets.</p>
<p>For example, while working on <a href="http://hbogo.com">HBOGO.com</a>, the initial release of the iPhone app did not allow you to watch videos. The Flex app we did at the time was the only way to view videos. Overtime, it was prudent to support both iPhone and iPad versions. A lot of companies, however, don&#8217;t magically get 2 budgets, 1 for the web and 1 for the iPad just because the iPad is so cool. While the GUI&#8217;s needed for iPhone and iPad are simpler, you still want to create the same user experience for the customer,Â especiallyÂ if they are using all 3 to access their content. The <a href="http://en.wikipedia.org/wiki/Project_triangle">Iron Triangle</a> verifies that something must give, and thus, the scope/functionality/user experience often does.</p>
<p>Investing in a mobile technology where consumers pay less, and larger businesses devote less capital to the same projects doesn&#8217;t bode well for investing the smaller portion. If I were back in 2002 still doing design agency work, I&#8217;d totally be an iOS developer right now. As a consultant who does more than build software, and who doesn&#8217;t see his clients changing their plans, I see no prudent reason to go the iOS/Android device route. &#8230;&#8230; beyond them being really fun (another story).</p>
<p><a href="http://www.appcelerator.com/">Appcelerator</a>, <a href="http://www.anscamobile.com/">Corona SDK</a>, <a href="http://www.sencha.com/products/touch/">Sencha Touch</a>, andÂ <a href="http://phonegap.com/">PhoneGap</a>, technologies which allow you to deploy to multiple mobile platforms with mostly the same code base and skillset,Â can be lumped in the same bag as native with the above perspective.</p>
<p>Why invest in technologies that offer less money and my clientelle isn&#8217;t using?</p>
<p>On the flip side, the HTML5 moniker has taken on a life of it&#8217;s own. While notÂ necessarilyÂ  representing the full JavaScript, HTML, CSS, and associated libraries &amp; frameworks stack, a lot of clients big and small have been sold the bill of goods that it solves the same multi-platform, multi-device problem that the Flex/Appcelerator/Corona/Touch/PhoneGapÂ attemptÂ to solve: single code base, single developer toolset, and multiple targets within their same organization.</p>
<p>I won&#8217;t get into theÂ phenomenonÂ that is HTML5. All you need to know of the context of this post is that a lot clients either suddenly think HTML, CSS, and JavaScript can provide the same experiences we can do in Flex for the same price using the same teams&#8230; or they know it&#8217;s false, but either their Board of Directors or Business Customers force them to use the tech anyway for political reasons that have nothing to do with engineering ones.</p>
<p><strong>The Challenges of the New Platform</strong></p>
<p>The issue, however, is that it&#8217;s not that straightforward. There are 5 main issues that the HTML/JS/CSS stack (which I&#8217;ll here after refer to as the HTML stack), have when coming from the Flex platform in a consulting context (there are more, but these are the ones that matter with regards to the context of this post). They are:</p>
<ol>
<li>DOM as a dynamic display technology</li>
<li>JavaScript lacking mature language constructs</li>
<li>There are larger problems for multiple Browser Vendors to solve</li>
<li>the industry&#8217;s libraries &amp; frameworks are young from an Enterprise context (yet not!?)</li>
<li>The Video Codec Issues</li>
<li>Tooling</li>
</ol>
<p><strong>The Document Object Model</strong></p>
<p>The HTML DOM wasn&#8217;t made to do the type of applications we do in Flash, more specifically Flex. Flash Player was developed specifically around cross platform visual fidelity with a web bent. More importantly, though, it was built around redraw. This perspective of &#8220;frames per second&#8221;, and continual improvements around the underlying <a href="http://blog.kaourantin.net/?p=82">timing of redraw</a>, building upon <a href="http://blog.kaourantin.net/?p=81">what a platform does well</a>, and then abandoning a &#8220;new&#8221; 5 year old display technology to support a <a href="http://blog.kaourantin.net/?p=138">GPU future</a>.</p>
<p>Browser vendors are doing some pretty amazing things with the DOM, from hardware accelerating the display,Â continuousÂ redraw optimizations, all the while doing their best to follow ever evolving standards amongst our changing technological landscape. &#8230;based on a tech designed and created to show text. That&#8217;s awesome.</p>
<p>Sadly, the redraw performance isn&#8217;t awesome. While a lot of Flash and Flex developers never really got the <a href="http://jessewarden.com/2007/01/invalidation-strategies-for-flash-player.html">purpose</a> and <a href="http://jessewarden.com/2008/03/how-to-fix-the-flash-cs3-components.html">value</a> of invalidation in Flash Player, even with a technology created for displaying and animating composited graphics, as your application scales, it&#8217;s easy to create a system that redraws too much. Invalidation helps mitigate (usually solve) that problem for 90% of the use cases in applications. In a nutshell, it means you can set properties on your visual components as much as you want to in a single thread and ensure it only actually redraws the screen 1 time.</p>
<p>For browser DOM&#8217;s, this is exemplified even with the drastic CSS improvements. The philosophy is to never redraw the DOM if you have to, and if you do, do so on the smallest section possible. Browser toolkits such as Ext JS, Â <a href="http://dojotoolkit.org/features/desktop">Dojo</a>, and some others do this very well. While they have the advantage of browser CSS to help mitigate some of the redraw performance drags, compensating for both past, current, and future browserÂ incompatibilityÂ in an easy to use &amp; scalable API shows just how brilliant some of those browser developers really are. Based on what I&#8217;ve continued to read, this seems to be getting better although not as fast, nor as widely deployed, as Flash Player did which means the problem isn&#8217;t going away soon and thus the need for x-browser, x-platform invalidation continues to be important. Thus, Ext JS&#8217; commitment to efficiently redraw the DOM is appealing.</p>
<p>One thing John brought up at the <a href="http://www.sencha.com/training/">Ext JS Fast Track training</a> last week was the lack of positive sales around hybrid solutions: using Flash Player and the HTML stack together. If you need to play video or animate/show a lot of composited objects, combining the 2 technologies together.</p>
<p><a href="http://hulu.com">Hulu</a>Â and <a href="http://youtube.com">YouTube</a> proved it can work with video and movie subscriptions. <a href="http://Grooveshark.com">Grooveshark</a>Â proved it can work with music (and video, heh). <a href="http://google.com/finance/">Google Finance</a> and <a href="http://google.com/analytics">Analytics</a> proved it can be done with charting. Â <a href="http://balsamiq.com">Balsamiq</a> proved it can be done with desktop designer tooling.</p>
<p>Bottom line, things are pretty bad but getting better slowly, and there are mitigation paths that can utilize Flash Player in the interim. Canvas is finally getting hardware acceleration across platforms also making it another another tool to help.</p>
<p>This doesn&#8217;t seem to be getting much play, but considering we&#8217;re all supposed to magically know a multitude of platforms, languages, and yet have multi-talented sub-contractors that meet that criteria and deliver the projects in the same time frame clearly means that option is also on the magical table.</p>
<p><strong>JavaScript in the Enterprise</strong></p>
<p>Surprisingly for me, JavaScript the language has dominated the discussion the past 3 months in where I&#8217;ve lurked in social media circles amongst the Flash &amp; Flex Developers. For those of us who grew up in the industry and our careers with Flash, it came quite as a shock for the industry to fall back in love with JavaScript.</p>
<p>While it made sense for server-side developers to reduce their code size as more logic goes to the client and their servers get faster and cheaper, we&#8217;re still a little confused as why the industry isn&#8217;tÂ salivatingÂ for a statically typedÂ <a href="http://wiki.ecmascript.org/doku.php?id=harmony:proposals">Harmony</a> (resurrected,Â non-elven remains of ECMA 4).</p>
<p>Most of us Flash turned Flex developers grew up using ActionScript 1. For those who don&#8217;t know, this is near exactly the same as JavaScript/ECMA 3. The difference is instead of doing an innerHTML on a div tag, you just call methods/properties on a Sprite. As our projects grew in scope and # of developers, the language started to show its scalability problems. You&#8217;d run into more and more null pointers fromÂ misspellings, even with better tooling to help provide code hinting. You&#8217;d also get errors, but no clue where they came from since there was no common way of handling errors in ActionScript 1.</p>
<p>Furthermore, if you didn&#8217;t provide source, the developer was screwed because there was no way to easily introspect API&#8217;s unless you read the documentation or source; things like <a href="http://aptana.com/">Aptana</a> didn&#8217;t exist back then. This also implied, however, that even though there were things that weren&#8217;t public, developers would still call them anyway if they didn&#8217;t understand your name spacing convention (such as using an underscore (_) prefix for private variables and method names). While <a href="http://lua.org">Lua</a> and other languages have <a href="http://www.lua.org/pil/15.2.html">tricks</a> using closures to emulate access modifiers, this never caught on in the early Flash world. The path for RIA&#8217;s at the time was larger projects with larger teams, and thus they adopted a more Java esque method of language development while still trying to match ECMA 4 as best they could.</p>
<p>Finally, loose typing/variants also made it harder (in theory&#8230; which has been proven wrong by Google&#8217;s V8) for Macromedia/Adobe compiler engineers to make the language run faster than JavaScript.</p>
<p>Thus, the natural evolution was for a strongly-typed language with proper packages and namespaces (or access modifiers like public/private) to help us address the larger applications we were developing. It did. It was, and is, awesome.</p>
<p>&#8230;for some. About the same time as I started getting more consulting, I also started noticing a larger awareness to the different types of businesses using Flash and Flex. In the Design Agency world, the majority of the work was 2 months to 2 days, and in between. The teams were often 1 developer; if there were more devs, they both weren&#8217;t on the project the whole 2 man months. They hardly ever payed their technical debt (unless you were a consultant with them). You started to see a strange love/hate relationship for a lot of these devs. In some cases ActionScript 3 helped these developers, who were on a deadline and often never paid their technical debt, manage said technical debt with AS3&#8217;s improved strong-typing and runtime exceptions with the ability to use loosely typed constructs when needed or in unknown territory.</p>
<p>On the flip side in the Flex world for larger companies that gave a flip about design, and more about feature count, the language constructs were barely enough. Constantly we&#8217;d get barraged from developers in more low-level languages like Java, C#, and C++ about why is AS3 is missing this or that (true Singletons, true Abstract classes, threads, blah blah blah), and how do you emulate such features.</p>
<p>It was very clear there was a split was growing. I could elaborate on all theÂ niceties, but suffice to say, the Flash Devs didn&#8217;t need all the language features &amp; strict complexity rules whereas the Flex Devs couldn&#8217;t get enough. Again, a simplification on the nuances of Â a thriving, diverse, and changing community, but accurate.</p>
<p>Most of the Flash devs have had little trouble beyond the first 2 hellish weeks of getting immersed back in the DOM, CSS, and JavaScript variant world&#8230; only with better tooling and libraries + choices than they had 7 years ago when they 1st abandoned it for more creative pastures.</p>
<p>The Flex devs, however, haven&#8217;t seemed to budge en-masse. We have people telling us we don&#8217;t need those things in a language, yet when we ask them to show us a large Enterprise Application that utilizes JavaScript, they either are using an intermediary language to compile to it (Java in Google GWT or Oracle ADF, C#/VB in .NET, or CoffeeScript), or just can&#8217;t deliver the goods. Same excuse us Flex developers gave the <a href="http://slashdot.com">Slashdotters</a> around &#8220;show me a cool app built with Flex&#8221;: &#8220;It&#8217;s behind the firewall&#8221;.</p>
<p>There&#8217;s also a lot of misunderstanding about simple things like OOP. Using Object.prototype for &#8220;emulated&#8221; classes is what I did for 4 years&#8230; I have no major qualms about going back. Ext JS in version 4 abandoned this practice as well. While I grew up with Object.prototype insanity and learned to love it, the debate vs. clsoure/function inheritance vs. Object.prototype rages still. If you care, Keith Peter&#8217;s has a <a href="http://www.bit-101.com/blog/?p=3420">good article on the nuances of it</a>, or you can read what I did to learn ActionScript, <a href="http://www.debreuil.com/docs/">Robin Debreuil&#8217;sÂ book</a>. Â There are others, but the point here is we Flex Devs expect classes not just for encapsulation, but createÂ organizedÂ code with a common workflow to share code amongst many developers. JavaScript wasn&#8217;t made for classes, but using Object.prototype or the closure method in a declarative manner works just fine (like <a href="http://impactjs.com/">ImpactJS</a> or Ext JS does).</p>
<p>While I like Keith&#8217;s take and respect his opinion, not having classes and encapsulation won&#8217;t work in large teams, often setup to fail at the outset by politics, nor all being Keith Peter&#8217;s caliber (me included). The other option to &#8220;not working&#8221; of course (Goonies never say die), which I&#8217;ll cover later, is that it&#8217;ll just take longer and/or we&#8217;ll accomplish less. The rules of <a href="http://en.wikipedia.org/wiki/The_Mythical_Man-Month">Mythical Man Month</a>, <a href="http://en.wikipedia.org/wiki/Technical_debt">Technical Debt</a>, etc.Â still apply regardless ofÂ Â language/platform. It&#8217;s worse in <a href="http://jessewarden.com/consulting-chronicles">Consulting</a> when coding software, extremely hard in it&#8217;s own right, is the least of your problems.</p>
<p><strong>Compiling to JavaScript</strong></p>
<p>In fact, some are so staunchly opposed to utilizing JavaScript as a serious language to build Enterprise Applications, that they&#8217;ve investigated alternatives to compile TO JavaScript using an intermediary language. This has long been the process for server-side platforms with a variety of templating engines out there that make it a hybrid process of injecting data into your HTML. The problem is, they either have a server-side bias, or aren&#8217;t ready for prime time in a large Enterprise Scale. Remember, you can&#8217;t just be good; you have to have money, a company of decent size behind the tech, funding, and have reached critical mass for your product.</p>
<p>While the reaction was very positive around the work Adobe was doing with <a href="http://blogs.adobe.com/bparadie/2011/11/19/what-is-falconjs/">FalconJS</a> for those in attendance at the <a href="http://blogs.adobe.com/flex/2011/12/an-update-on-flex.html">FlexSummit</a>, it was very clear to me it was a scienceÂ experiment with no hope in providing the needed migration path for Enterprises. The amount of work, resources, and time needed to bring it to Oracle ADF, Google GWT, or .NET caliber is clearly something Adobe didn&#8217;t seem willing to devote. That, combined with their clear direction of no longer focusing on developers.</p>
<p>Google <a href="http://www.dartlang.org/">Dart</a> seemed like a light at the end of the tunnel. It, too, however, seems to be a scienceÂ experiment of Google scale. It has all the hallmarks for a bright new project:</p>
<ul>
<li>Google is behind the engineering effort</li>
<li>has a strongly-typed language that, like CoffeeScript, not only sets out to improve upon JavaScript&#8217;s problems, but provide mature language constructs you need in larger applications within the language itself (unlike CoffeeScript&#8217;s/<a href="http://code.google.com/closure/compiler/">Google Closure&#8217;s</a>/<a href="http://typedjs.com/">TypedJS</a>Â annotations</li>
<li>has 2 <a href="http://www.dartlang.org/support/faq.html#hello-world-js-size">compilers</a>: 1 a Flex Developer would use (dartc) and 1 a Flash Developer would use (frog).</li>
<li>is based on Eclipse (good and bad, let&#8217;s just pretend the good parts here)</li>
<li>brought on <a href="http://infrequently.org/">Alex Russell</a> of <a href="http://dojotoolkit.org/">Dojo</a> fame to take a fresh look at the DOM event API</li>
<li><a href="http://futurescale.com/v3/">Cliff Hall</a> of <a href="http://puremvc.org/">PureMVC</a> fame (multi-language framework used a lot in Flex) made a <a href="https://plus.google.com/108661011132885730615/posts/Z2apdshvWnA">first version port for Dart</a>.</li>
</ul>
<p>&#8230;yet doesn&#8217;t seem a priority since while a web based technology, it still hasn&#8217;t reached critical mass, nor does it show any signs of doing so yet. I&#8217;m more concerned about the amount of resources I&#8217;m seeing being devoted; maybe there are more, and like all things Google, they just don&#8217;t advertise it. I really wish I could just parachute drop a Porter &amp; Bogusky contingent in Google someday&#8230;</p>
<p>So far, the only contender is <a href="http://coffeescript.org/">CoffeeScript</a>. Here is a <a href="http://bodil.tv/coffeescript-at-javazone">video</a> and <a href="http://bodil.github.com/coffeescript/#landing-slide">slideÂ presentation</a> to check out on if you have time. However, Ext JS uses declarative <a href="http://json.org/">JSON</a> + JavaScript. I have not seen any signs to see if Sencha is interested in porting Ext JS to Dart. Just say it&#8230; &#8220;Ext Dart&#8221; (pronounced &#8220;X Dart&#8221;); sounds like a dope <a href="http://www.youtube.com/watch?v=itm7SdwYTjo&amp;feature=fvst">dubstep</a> ninja weapon, right? You&#8217;d certainly get better jokes from non-tech savvy people at parties when someone hears you&#8217;re a &#8220;Flash Developer&#8221;.</p>
<p>The other problem is that you need everyone in your organization coding the same language. In product companies, it is TOTALLY fine to have a technology du jour with Ruby running your builds, PHP running your render farm, and Java running your back-end, but for development purposes on 1 particular platform, you standardize on a language and usually have company ordainedÂ standardsÂ on it. This is forÂ maintenanceÂ costs, and hiringÂ standards, and aÂ varietyÂ of other reasons that aren&#8217;t just around cost.</p>
<p>If anyone has CoffeeScript running atop Ext JS, let me know how you got your build process setup.</p>
<p><strong>Browser Issues</strong></p>
<p>Notice I&#8217;m specifically talking not just aboutÂ incompatibilitiesÂ between browsers, but missing features. For example, just 3<a href="http://blog.chromium.org/2012/02/future-of-javascript-take-peek-today.html">Â days ago</a> Google added weak collection keys into V8 (their JavaScript engine for Chrome). Developing data models with string based keys can be extremely hard for complex model logic. Having a Dictionary (or Object) that can use something other than a String as a key is extremely useful&#8230; until you have to remember to kill the key when the object is destroyed. Enter weak keys and queue the &#8220;woo hoo!&#8221;.</p>
<p>One of the great things about Google&#8217;s approach with Chrome is not only is it the fastest updating piece of software that matters in history (faster than Flash Player), but they iterate quickly on features. While we&#8217;d wait 18 months for AS2 and then 24+ months for AS3, and in between get language updates&#8230; JavaScript is getting that piece by piece. It&#8217;s a wonderful thing, but also brings up a larger issue.</p>
<p>What do you today?</p>
<p>You have to do SOMETHING. Given each browser implements different features different ways, and JavaScript&#8217;s functional + prototype nature, you can easily (*ahem*) abstract away these problems into a useable API that hides the differences. Certain low level things like maps can be tricky, however, and come at the cost of performance, libraryÂ maintenanceÂ costs, etc.</p>
<p>Fine, no big deal, you just move forward using an Object hash approach. We&#8217;ll just wait a couple of projects before maps + Dictionaries catch on in all browsers.</p>
<p>&#8230;but what about <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html">Web Worker</a> (also known as threads for web developers)? It&#8217;s only supported in IE9 while Firefox/Safari/Chrome are good to go. While you can emulate via green threading, this is a FAR cry from emulating the lack of getter/setters in older versions of IE, or even <a href="http://code.google.com/p/explorercanvas/">emulating Canvas for Internet Explorer 8 via a VML wrapper</a>. Those work. <a href="http://en.wikipedia.org/wiki/Green_threads">Green threading</a> is not the same thing as a separate process that ensures it doesn&#8217;t lock up your GUI thread. The lack of full browser support will prevent some features from actually working and there aren&#8217;t any fall backs that can be utilized.</p>
<p>For some charting/plottingÂ applications, these are essential features: no web worker, no application. Now in Flash, you&#8217;d just plan around upcoming features, both those you voted to be actual features, or those you knew were coming down the pipe. One tactic of design agencies, and Macromedia/Adobe in general was to have them launch a high profile app/site/widget to showcase these features upon launch.</p>
<p>If you are to inspect all upcoming features in browsers, not just JavaScript, but CSS, hardware &amp; display related, etc. it really slows down when we expect certain experiences in our applications. While Macromedia/Adobe would drag their feature on certain things like right click and threads, the process was generally the same:</p>
<ol>
<li>identify a problem you had on projects</li>
<li>bring it to your peers &amp; Macromedia&#8217;s attention</li>
<li>rally support through email list/blog/twitter posts/talking to company reps at conferences</li>
<li>make writing &amp; validating the use case easy</li>
<li>get community votes whenÂ desperate</li>
<li>await new feature(s) in upcoming Flash Player, beta test if lucky</li>
</ol>
<p>While this process for Chrome seems EXTREMELY quicker, for the rest of the browser market as a whole, including smart phones and tablets, not so.</p>
<p>My college professor said, &#8220;There will always be work to be done.&#8221; Unless we use hybrid implementations, clients will just have to live with the slower pace of innovation if they want broad adoption. I guess I&#8217;ll live, I&#8217;m just curious where my excitement will come from if the toys remain the same, or only 1 browser implements a new feature I can&#8217;t easily abstract. That, and it seems a lot of innovative projects will either start to be browser specific feature branches, or just wait for broader adoption amongst modern browsers. It&#8217;s sad. And frustrating for both my clients and my team.</p>
<p><strong>Wild West: Libraries and Frameworks</strong></p>
<p>What&#8217;s fascinating to me about the JavaScript landscape is how much longer it has been around with a lot more people and yet theÂ landscapeÂ with regards to frameworks and libraries is still in major flux on a few fronts.</p>
<p>In the Flash World, there were 2 frameworks that people would use, if ever: <a href="http://osflash.org/projects/arp">ARP</a> and&#8230; just kidding, 1. While the tweening libraries got a little out of control, and the component frameworks became pretty niche, overall there was a library for everything, sometimes with an alternative if you didn&#8217;t like one particular implementation. A lot were ported from otherÂ languages, like Java and C/C++.</p>
<p>Frameworks didn&#8217;t really start to rear their head until Flash RIA applications started to become mainstream, and Flex was born. The Java developers coming over didn&#8217;t see any common <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a>/<a href="http://martinfowler.com/eaaDev/ModelViewPresenter.html">MVP</a>/<a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">MVVM</a> frameworks that allowed them to manage copious amounts of code on the client side vs. middle tier. <a href="http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm">Cairngorm</a>, <a href="http://puremvc.org/">PureMVC</a>, <a href="http://swizframework.org/">Swiz</a>, <a href="http://www.spicefactory.org/parsley/">Parsely</a>, and <a href="http://robotlegs.org">Robotlegs</a> were born. Cairngorm is still around, but Swiz/Parsely get most of the play in the Flex world with PureMVC and Robotlegs hitting both Flash and Flex.</p>
<p>With exclusion of Cairngorm, all 3 have a lot in common. While everyone somehow manages to make their own implementation, learning one helps in learning another. Additionally, most never made it past a version 2, and even then most of the changes weren&#8217;t a dramatic workflow change.</p>
<p>JavaScript is nuts on the framework front. While the libraries themselves are great in that once you get over the burden of reviewing 5 of the same thing, the frameworks on the other hand are all over the map. Some are just query helpers with binding thrown in. Some are actually a certain group of existing libraries with a defined way of working with them, and thus named a framework&#8230; even though no code is actually associated with the framework itself. Worse is the versions can sometimes be drastically different. If few in #, this wouldn&#8217;t be a problem.</p>
<p>Worse, there are 100 times more people in the JavaScript community with their own opinions on what MVC means. What MVP means. What MVVM means. What the differences are between the 3. Their own descriptions for what the differences are between Passive View, Supervising Controller, and Presentation Model&#8230; and sometimes pretending (innocently) that the only thing that exists is MVC, period.</p>
<p>The other thing that is clear is that there are aÂ varietyÂ of applications (not progressively enhanced websites) that are done with JavaScript, and thus each framework targets that particular version. For example, PureMVC and Robotlegs have Mediators which make it easier for the View (what you actually see) to change a lot during the project, yet still keep its ability to get it&#8217;s data without race conditions, and have it produce theÂ necessaryÂ  user gestures through Events. Swiz on the other hand, had a Presentation Model injected into the View, and you had a nice API the View could call/get it&#8217;s data from. A lot of Swiz guys I talked to NEVER used the states features in Flex 4&#8230; nor saw the point. GUI changes didn&#8217;t affect PM API, they weren&#8217;t complex enough that you had to use mock interfaces for the PM&#8217;s to test View&#8217;s in isolation&#8230; so for this group, it worked well. In retrospect, this was a nice, natural evolution that happened.</p>
<p>I&#8217;m seeing the same thing in JavaScript, but it&#8217;s massively larger, and a lot of times you&#8217;re cherry picking either a specific feature of a specific library to be used with other ones, and you&#8217;re settling on a version. The last one is worrisome from a consulting perspective. When dealing with clients, Technical Architect/Directors want to ensure whatever framework you settle upon has good online documentation, you can hire people who know it, and it has a future. Using the same metrics I use to do so for frameworks in the Flash/Flex world is a little harder; just because its someones side science project doesn&#8217;t mean it&#8217;s not immensely useful, nor easy to learn.</p>
<p>The other challenge from a consulting perspective is leaving clients with work that they can support&#8230; or my firm would even want to get involved in. For example, there are copious reasons Ext JS 4 moved away from Object.prototype modifications. If you adopt a Ext JS 3 project from a client, you now adopt those problems even if you didn&#8217;t write it. With Flex projects, you eventually learned what problems there were from porting a Flex 2 app to 3, or what parts of mx were supported in Flex 4, and could find blog posts covering these challenges. With JavaScript, I&#8217;m finding a hard time finding commonality between the stacks that different companies are using.</p>
<p>I. Do. Not. Want&#8230; to be a non-Enterprise TA right now. Holy fish. Like, it&#8217;s 2008: &#8220;Yes, we&#8217;re using YUI version 2, it&#8217;s rad, has a large company backing it, and we can hire for it.&#8221; It&#8217;s 2012, and you&#8217;re either a jQuery, Sencha, or Dojo kid&#8230; oy vey.</p>
<p>So far, with the exception of Ext JS&#8217;s MVC implementation, it seems to have all of that solved in version 4 as best it can with the ability to have your own libraries added in with your own modified build process over theirs as well if you see fit to do so.</p>
<p><strong>Video Codecs</strong></p>
<p>No one has solved the codec problem yet. This is where HTML5 video justÂ doesn&#8217;tÂ work as advertised. I won&#8217;t go too much into this topic as for Enterprises, you&#8217;re usually more concerned about VOD, DRM, multicast and live streaming which Flash owns for desktop and HLS owns on iOS. More info about the <a href="http://www.longtailvideo.com/html5/">WTF</a> here and the <a href="http://transitioning.to/2012/01/the-world-of-pain-that-is-html5-video/">OMG</a> here.</p>
<p>I only bring it up because it&#8217;s just accepted in our world that video and compositing of it + assets is expected in our content, yet now&#8230; it&#8217;s not. Good designers can make it work, but the point here is from an integration perspective the cost of integrating that content.</p>
<p><strong>Tooling</strong></p>
<p>Lastly is tooling. While Aptana makes an attempt, it seems that Microsoft&#8217;sÂ <a href="http://www.microsoft.com/visualstudio/">Visual Studio</a> is the only IDE that seems to take web development seriously for those building large applications. Since me and a lot of people I know in Flex development use Mac&#8217;s, it seems our only alternative is JetBrain&#8217;s <a href="http://www.jetbrains.com/webstorm/">WebStorm</a>. Granted, they have other flavors of their IntelliJ IDE, Â but without commonly expectedÂ functionalityÂ like code hinting, intelli-sense, and re-factoring, it&#8217;s hard for use to take web development seriously.</p>
<p>There is a huge productivity cost that people seem to forget when you move from Eclipse/IntelliJ with those features to Notepad. When you have multiple developers, that time spent adds up, as does the lack of accuracy on your team&#8217;s velocity in solving issues.</p>
<p>In 2004, a lot of Java Developers tried out Flash. They then left. Adobe then created Flex. Some came. When Flex 2 came out, the runtime worked, the language worked, the components worked, but more importantly, the Eclipse IDE at the time&#8230; worked. The refactoring was, and still is not the best compared to IntelliJ and Visual Studio, but it&#8217;s enough for them to take it seriously. That&#8217;s when they came en masse, and peeps like <a href="http://en.wikipedia.org/wiki/Bruce_Eckel">Bruce Eckel</a> were like, &#8220;Flex is good stuff&#8221;.</p>
<p>Going into an Enterprise and telling developers they are no longer allowed to work on Enterprise software with intelli-sense and code hinting isn&#8217;t going to work. Thankfully Ext JS is working with a few tools vendors, and some, like WebStorm, can be customized to improve the hints you get, including on your own code.</p>
<p>At the end of the day, we Flex Developers are concerned about the overall reduced project velocity &amp; resolution prediction that comes with losing static typing (&#8220;What and where is the problem and when is it going to be resolved?&#8221;). For smaller projects with smaller teams, IÂ guaranteeÂ you the point is moot. In doing both, if you CAN do both, dynamic languages are so much faster and fun to develop quickly, and flexibly in. For 18 month, multi-developer teams on code that&#8217;s alive for 5 years, it doesn&#8217;t.</p>
<p><a name="introduction"></a><strong>Introduction</strong></p>
<p>As a business owner, we have to meet the needs of those clients that have adopted the HTML Stack, or feel they need to and cannot be convinced otherwise. In the following article I&#8217;ll cover what Ext JS is from a Flex Developer&#8217;sÂ perspective, why you should care, and some conclusions on how using it + Flex changes our business for the better.</p>
<p>As I mentioned before, the events of November 9th, 2011 shook the Flash &amp; Flex world to the core, and I had 2 choices: figure out where to go, or let other key members of the community figure it out.</p>
<p>I chose the latter plan: play <a href="http://www.elderscrolls.com/skyrim/">Skyrim</a> and disappear for 3 months to let it all shake out. If things hadn&#8217;t been figured out by key members of the community, I&#8217;d just figure them out for myself. It&#8217;d also be around the same time as <a href="http://en.wikipedia.org/wiki/Groundhog_Day">Groundhog Day</a>: If the Flex community saw their shadow, and freaked out, I could come out and help them weather the longer winter.</p>
<p>It&#8217;s been 3 months and so far, it seems all the Flash Devs went <a href="http://jquery.com">jQuery</a>/<a href="http://documentcloud.github.com/backbone/">Backbone</a> (or <a href="http://angularjs.org/#/">Angular</a>) whilst the Flex Devs are debating between <a href="http://dojotoolkit.org/">Dojo</a> and <a href="http://www.sencha.com/products/extjs/">Ext JS</a> (pronounced &#8220;X Jay S&#8221; if you&#8217;re French Canadian) (yes, I tried <a href="http://developer.yahoo.com/yui/">YUI</a> and left just as quickly). After talking with members of the community and doing some of my own research, it seems Ext JS is the right choice for the type of work I do. Like using Flash vs. Flex, it&#8217;s clear it may not be the right choice for you. If you&#8217;re a Flex Dev doing large, multi-developer projects, I&#8217;ll bet it IS the right choice. Read on.</p>
<p><strong>What is Ext JS?</strong></p>
<p>Ext JS is a component framework for building web applications atop JavaScript, HTML, and CSS. It&#8217;s made by a company called Sencha who also makes a mobile version called Sencha <a href="http://www.sencha.com/products/touch/">Touch</a>.</p>
<p>It&#8217;s attractive to Flex Developers because:</p>
<ol>
<li>It has components. Lots of components.</li>
<li>It has styling and theming features.</li>
<li>It has a Model architecture built around data store &amp; server CRUD operations.</li>
<li>It has charting components that do not utilize Flash Player (for good and ill)</li>
<li>It has awesome item renderers for grids.</li>
<li>It has classes for JavaScript with inheritance.</li>
<li>Layouts with Containers</li>
<li>Standard Focus Manager</li>
<li>Core Library with DOM helpers as well as JavaScript language extensions</li>
<li>A big company, with investment, and tons of docs who&#8217;ve adopted a prescriptive MVC framework.</li>
</ol>
<p>There&#8217;s a lot more, but that is what we Flex devs actually care about.</p>
<p><strong>How&#8217;s it work?</strong></p>
<p>Ext JS is a framework; a collection of classes, 3rd party technologies, and a prescribed methodology for building web applications. HTML is used to show the components. CSS is used to style and modify interactivity. JavaScript and declarative JSON is used tomake things appear and work.</p>
<p>JSON, traditionally used by Flash and Flex Developers for data transfer, is actually the main way you code Ext JS,Â similarÂ to how MXML makes up most of your GUI in Flex. Since JSON itself can be written in a declarative way, this is usually the core of how you define a lot of your application; both GUI and data. This JSON + JavaScript isÂ interpretedÂ to create classes, components, and listen to event handlers.Â Internally, the Ext library will redraw the GUI asÂ necessary, whether that&#8217;s modifying CSS styles on the DOM objects that visually represent them, or swapping out innerHTML wholesale.</p>
<p>You include a javascript library on your HTML page, code some boostrap JavaScript/JSON on the page, and voila, you have an Ext JS app. It can be as small as using 1 or 2 classes from the Ext JS library, to a full blown application that uses their components, their model classes, their MVC, their default module loader, their implied CSS abstraction layer, and their build system&#8230; up to you how much you want to use.</p>
<p><strong>Prescription &amp; 3rd Party Integration</strong></p>
<p>Sencha has to walk a fine line with Ext. From an Enterprise stand point, they have to lay the ground work for a prescriptive way to utilize their technology. You need to make a framework easy to work with, have good documentation, and not be too flexible that developers can all go their own way. This allows larger organizations to hire/cross-train easier, have those developers actually be successful with minimal investment, and basically ensure any skillset &#8220;knows how to build an app&#8221;.</p>
<p>It&#8217;s a sales pitch, yes, but it does need to try to work like that. In reality it never does, hence consultants like me existing, but that&#8217;s not the point. You don&#8217;t want many different ways to skin a cat from an architecture perspective. It&#8217;s fine if you cuddle your brackets, use TextMate to code, and prefer Mercury over Git&#8230; it&#8217;s not fine if you prefer MVVM over MVC, want to be intimate with the DOM, and the other developers in another part of the company on a companion product don&#8217;t. Unlike Design Agencies, Enterprise companies do have to pay their <a href="http://martinfowler.com/bliki/TechnicalDebt.html">Technical Debt</a>. In fact, I&#8217;d argue they pay more than they should, compensating in a bizarre karma like way for Design Agencies who get away it. You want to mitigate this problem by making something easy to use, easy to hack, but prescriptive enough that if you don&#8217;t know any better, you won&#8217;t cause undue costs down the line in the way your team built something.</p>
<p>JavaScript, currently, is all about libraries, more so than Flex and Flash was for a variety of reasons. Namely abstracting browser differences, abstraction over new features with fallbacks, and the sheer number of developers from a variety of backgrounds. Each company is going to use different libraries merely based on the number of library choices out there. The same goes for internal projects. A lot of companies have their own internal libraries utilized on products for their business, whether B2C or B2B. You need to be able to integrate with these in your native language.</p>
<p>Sencha needs to support prescribed direction in how you build web applications with the ability to support 3rd party libraries.</p>
<p>There are a few things they&#8217;ve done to facilitate this. Here are a few that matter.</p>
<p>First, they&#8217;ve abandoned Object.prototype as of Ext JS 4. If you&#8217;re a Flash Developer, you&#8217;ll remember having your language suddenly act different because some developer or 3rd party library overwrote a core property/method in Flash, and suddenly your entire application worked differently&#8230; or it only did it sometimes because of later loaded class. Unless you knew what you were doing, these were nearly impossible to debug since the documentation stated a method did one thing, but clearly during testing did another. Even if you did know what you were doing, there aren&#8217;t many language, nor tooling facilities to help you debug thisÂ inheritanceÂ mixinÂ whackness.</p>
<p>Considering JavaScript library inclusion amounts areÂ significantlyÂ higher than say Flash or Flex, the risk of collisions are higher. On multi-person teams across an organization, with already strained communication this can be horrible to try to resolve.</p>
<p>Also, from a module perspective (those of you using PureMVC multi-core or many Robotlegs Contexts will get this), you need to sometimes run may applications in parallel on the same page. Not having to worry about stomping on someone&#8217;s method/properties is a nice feeling to have.</p>
<p>Second, they&#8217;ve commited to <span style="text-decoration: line-through;"><a href="http://twitter.github.com/bootstrap/">bootstrap.js</a></span> their own bootstrap.js from a library/module perspective which supports both debug and production mode. With the build process, this allows you to develop with new classes on the fly, and in production mode actually have 1 file for you&#8217;re entire application. This is for speed &amp; ease of development purposes.</p>
<p>We take this for granted in Flash/Flex where all our classes are included, and zlib compressed in a minified bytecode format into a single SWF file.</p>
<p>Remember, Day 1 of Flash Development had 1 SWF. As a binary format, everything you needed was right there for you, ready when you started. The HTML stack was different. Everything is a bunch of files all loaded at different times from different places. As a coder, you know this is a nightmare to figure out. From a networking perspective, initiating a lot of HTTP requests to the server and downloading them in parallel is also slower. So JavaScript has a habit of allowing you through build processes to put all of your classes into 1 massive file to help alleviate the race condition pain as well as improve performance, compression, etc. However, during development or when building modules/lazy loading, you still need the option to load on the fly.</p>
<p>Third, their MVC is prescriptive. I won&#8217;t get into too much detail because as a Swiz/Robotlegs aficionadoÂ and PassiveView h8tr, I already want to use my own or Angular&#8230; anything but theirs. That doesn&#8217;t matter, though, the point here is that they&#8217;ve provided the built in mechnisms, it works great with the framework, and they have documentation on it as such. This ensures organizations take them more seriously, have a chance to at least be forced into some known structure, and you as a consultant have a chance of understanding how they did things if you come onto an existing project (assuming they didn&#8217;t just use Ext JS for it&#8217;s query syntax and get all intimate with the DOM&#8230; which you can do if you wish).</p>
<p><strong>That&#8217;s Great, Show Code</strong></p>
<p>Here is some Hello World code:</p>
<pre lang="html"><html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Ext JS Hello World</title>
		<link rel="stylesheet" type="text/css" href="/extjs4/resources/css/ext-all.css" />
		<script type="text/javascript" src="/extjs4/bootstrap.js"></script>
		<script type='text/javascript'>
			Ext.onReady(function()
			{
				Ext.Msg.alert('Welcome to Ext JS 4', 'Hello World!');
			});
		</script>	
	</head>
	<body>
	</body>
</html></pre>
<p>As you can see right off the bat, closures are the word of the day. Ext JS is full of either closures (anonymous functions or variables that equal functions) and/or JSON. You&#8217;ll intermingle both a lot.</p>
<p><strong>Components</strong></p>
<p>Components are the main reason most Flex Developers dig Ext. Not only are there are a lot of components, but some of the ones they have are better than their FlexÂ equivalents. And this, folks, is one of the reasons why software developers often tell you to try anotherÂ languageÂ or platform, at least 1 per year. You&#8217;ll see what the competition has, and YOU&#8217;LL GET PISSED OFF!</p>
<p>Why didn&#8217;t Adobe build this level of components for Flex? Why does Django, Rails, Coccoa, and countless other frameworks have a Model with optional Facade on top to support offline storage with online CRUD syncing out of the box&#8230; and Flex does not? How come our DataGrid didn&#8217;t come with built-in paging?</p>
<p>Enough ranting, <a href="http://www.sencha.com/products/extjs/examples/">check them out yourself</a> (scroll down, check out list on bottom left) while I cover a few here.</p>
<p><strong>T3h Ãœber Grid</strong></p>
<p>You&#8217;ll notice right off the bat their DataGrid is pretty bad ass. Three things I want to point out about it.</p>
<p><a href="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.49.36-AM.png"><img decoding="async" class="size-full wp-image-3023 alignnone" title="Screen shot 2012-02-13 at 11.49.36 AM" src="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.49.36-AM.png" alt="" width="259" height="43" /></a></p>
<p>Notice they have paging built-in. This is, in part, to their Model/Proxy/Store setup. In Flex, you had to code this yourself (don&#8217;t get me started on Blaze DS/LiveCycle).</p>
<p>&nbsp;</p>
<p><a href="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.49.58-AM1.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3025" title="Screen shot 2012-02-13 at 11.49.58 AM" src="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.49.58-AM1.png" alt="" width="308" height="252" srcset="https://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.49.58-AM1.png 308w, https://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.49.58-AM1-300x245.png 300w" sizes="auto, (max-width: 308px) 100vw, 308px" /></a></p>
<p>Notice their filtering actually has a GUI with a drop down menu to customize (and which YOU can customize) on how to filter the data. No server trip needed. Hot.</p>
<p><a href="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.50.20-AM.png"><img loading="lazy" decoding="async" class="alignnone size-full wp-image-3026" title="Screen shot 2012-02-13 at 11.50.20 AM" src="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.50.20-AM.png" alt="" width="611" height="410" srcset="https://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.50.20-AM.png 611w, https://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-11.50.20-AM-300x201.png 300w" sizes="auto, (max-width: 611px) 100vw, 611px" /></a></p>
<p>And finally&#8230; &#8220;row editing&#8221;. Yes, an entire row can be modified. You can also allow a row to be edited, but only allow certain columns in that row to be edited, as well as customize this renderer. Awesome, right?</p>
<p><strong>Charts</strong></p>
<p><a href="http://dev.sencha.com/deploy/ext-4.0.7-gpl/examples/charts/Area.html"><img loading="lazy" decoding="async" class="size-medium wp-image-3027 alignleft" title="Screen shot 2012-02-13 at 12.07.09 PM" src="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-12.07.09-PM-300x226.png" alt="" width="300" height="226" srcset="https://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-12.07.09-PM-300x226.png 300w, https://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-12.07.09-PM.png 805w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></p>
<p>Charts, like Grids, play a central role in a lot of financial &amp; insurance software. You see the data in lists and you visualize it in charts. Ext JS 3 used Flash, but now they use SVG (and I think VML in some cases) and no canvas. This ensures it&#8217;ll work without a plugin. The downside is you can&#8217;t print yet. They&#8217;re working on it, and there are a lot of server-side plugins where you can easily wire up the chart data to a button to have the server assemble a PNG or PDF for you to print so solutions do exist.</p>
<p><a href="http://dev.sencha.com/deploy/ext-4.0.7-gpl/examples/charts/Bar.html"><img loading="lazy" decoding="async" class="alignright size-medium wp-image-3028" title="Screen shot 2012-02-13 at 12.07.19 PM" src="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-12.07.19-PM-300x225.png" alt="" width="300" height="225" srcset="https://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-12.07.19-PM-300x225.png 300w, https://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-12.07.19-PM.png 804w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a>You&#8217;ll notice, too, that they are interactive. You can customize a lot of their display + tooltips I believe to degree usingÂ templatesÂ (I&#8217;ll go over that later). They also have the standard animation built in as well. From a sales perspective, these charts Â + the grids demo very well.</p>
<p>While we at <a href="http://webappsolution.com/">WASI</a> have our own <a href="http://webappsolution.com/what-products.html">Dashboard</a>, it&#8217;s nice to know you can accomplish the same style of application and product using Ext&#8217;s components to create Dashboards.</p>
<p><a href="http://dev.sencha.com/deploy/ext-4.0.7-gpl/examples/charts/FormDashboard.html"><img loading="lazy" decoding="async" class="size-medium wp-image-3029 alignnone" title="Screen shot 2012-02-13 at 12.07.32 PM" src="http://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-12.07.32-PM-300x248.png" alt="" width="300" height="248" srcset="https://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-12.07.32-PM-300x248.png 300w, https://jessewarden.com/wp-content/uploads/2012/02/Screen-shot-2012-02-13-at-12.07.32-PM.png 877w" sizes="auto, (max-width: 300px) 100vw, 300px" /></a></p>
<p><strong>Everything Else</strong></p>
<p>Everything else is what you&#8217;d expect your team would need from <a href="http://www.sencha.com/products/extjs/examples/#sample-4">Tabs</a> to <a href="http://www.sencha.com/products/extjs/examples/#sample-7">layouts</a> to <a href="http://www.sencha.com/products/extjs/examples/#sample-13">forms</a>. The layouts are a little tricky if you&#8217;re not a CSS/DOM savant, but again, they abstract a lot of that from you (including that weird IE vs. the rest of the world padding measurement insanity).</p>
<p>There are a lot of little innuendo features too that make a big overall difference like all windows having the capability of being resized with a resizer, from all sides.</p>
<p>The components all have the standard DOM interaction events usually abstracted away so you just add an event handler for it, and you can create your own as well.</p>
<p>Yes, they have drag and drop.</p>
<p>Yes, they have aÂ varietyÂ of ways to handle state, both in components and within your application itself.</p>
<p>Their drawing package uses SVG I think&#8230; not really sure why they aren&#8217;t using Canvas, but I&#8217;m sure they have their reasons.</p>
<p><strong>Localization &amp; Accessibility</strong></p>
<p>They have localization and accessibility built in. I had some concerns during the fast track course because it seems the localization requires the application to be totally reloaded just to have text changes take effect. Meaning, there aren&#8217;t default framework bindings to a resource manager like you do in Java or Flex.</p>
<p>Either this was a bug or we couldn&#8217;t figure it out, but bottom line the components built into Ext JS do work with it, and you can see their text match the language; we just couldn&#8217;t get this to work at runtime, only compile time which is fine.</p>
<p><strong>Event Model</strong></p>
<p>Just a quick note on the event model. In Flash Player, we have the standard ECMA event model in terms of capture, target, and bubble phase. Since IE is backwards from the rest of the world and is in the minority camp, Ext JS flips it around and gives you their own <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.direct.Event">Event</a> class as well.</p>
<p>They key difference, however, is that interaction burdens are put on developer, much like <a href="http://anscamobile.com">Corona SDK</a> does in <a href="http://www.lua.org/">Lua</a>. If you want to handle an event, you need to return true to ensure it doesn&#8217;t bubble up and get run. I&#8217;ve seen other frameworks which just code gen the event.stopImmediatePropagation() and event.preventDefault(), but not here&#8230; and sometimes you need to return true from event handlers vs. calling the event methods. I haven&#8217;t figured out yet where the consistency is.</p>
<p>Anyway, a small thing, but good that they abstract the browser differences for you and provide a common event class +Â mechanismÂ for you. The addEventListener and/or callback way of doing things will be extremely familiar. I believe they have an event bus, but it&#8217;s not like Robotleg&#8217;s Actor or PureMVC&#8217;s Notification system.</p>
<p><strong>Styling &amp; Theming</strong></p>
<p>If you know CSS, you know how to style and theme a Ext JS application. Yes, that&#8217;s it. I unfortunately didn&#8217;t get to see, nor play with, a lot of the skinning in the Fast Track, just styling. I&#8217;m not sure how much of the image issues in various browser they abstract away since you&#8217;re using your own CSS styles.</p>
<p>Ext provides some template theme CSS files for you that you can modify, both built in classes as well as Ext JS ones. Combined with <a href="http://sass-lang.com/">SASS</a>/Compass, this really makes things a lot easier to handle. If you&#8217;re not familiar with SASS, there are just 4 things you need to know:</p>
<ol>
<li>You write 1 CSS style, and it&#8217;ll generate the browser/vendor specific ones if any (1 line of SASS could be 3 lines of CSS)</li>
<li>You can utilize variables in your SASS code which helps dynamically create theÂ appropriateÂ CSS (like determining width/height on the fly, etc).</li>
<li>They actually treat it like css CLASSES&#8230; so all the inheritance feels like inheritance vs. some &#8220;I&#8217;m not really code, but I&#8217;ll pretend I know what OOP is&#8221;</li>
<li>SASS files get generated through Ruby&#8217;s Compass into CSS files for your project. You don&#8217;t write CSS; you write SASS and Ruby&#8217;ll regen the CSS for you.</li>
</ol>
<p><strong>Models, Proxies, and StoresÂ </strong></p>
<p>Most Flash and Flex projects I&#8217;ve worked on have some form of Value Objects (classes that hold data that represent a server-side entity with additional data the client needs), Models or Proxy classes that allow the client retain data and state, and service classes that form the basis of the CRUD operations with the server.</p>
<p>In branching out into other languages/frameworks/platforms, it&#8217;s clear most have a large sub-system and abstraction layer upon this setup. Django has Model, Rails has ActiveRecord (or did&#8230; been awhile), Coccoa has CoreData (amongst other things), and Java has all sorts of things. Even with the large influx of Java, Flex never really got that kind of abstraction unless you went with the full Blaze DS / LiveCycle stack. It was abstracted away enough that you could build both non-Blaze/non-LC apps and not know the difference, but the point is that it was clear Adobe didn&#8217;t think that was a core part of most apps, or rather that particular part could beÂ monetizedÂ in Enterprise only offerings.</p>
<p>Whatever the reasons, it&#8217;s a core need in a lot of applications nowadays. I need to persist data in RAM, on the client cache (whether SQL or cookies), and with the server. Using a Facade or Proxy to make this part not only easier, but allow client side validation, as well as being built into all components, is a huge win.</p>
<p>All you need to know is it&#8217;s like an ArrayCollection that can save both locally to disk as well as sync with the back end as well as work as a dataProvider to all your components. And yes, when the dataProvider updates, Ext JS will update your GUI controls. Yup.</p>
<p>Sencha has specific meanings in the Ext world between Model, Proxy, and Store so don&#8217;t necessarely think design pattern as each is completely different than the other.</p>
<p><strong>JavaScript and Core Classes</strong></p>
<p>While Ext JS primary value to Flex Developers is their component framework and browser insanity abstraction, they also have a plethora of helper/utility classes for JavaScript, CSS, and the DOM as well. You can actually just use Ext just with the DOM using their <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.DomHelper">DomHelper</a>, <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.DomQuery">DomQuery</a>, and your own JS stack if you wish as their helper classes alone are nice to have. Some of it is open source, not sure.</p>
<p>You&#8217;ll notice they actually have a layer over top of low-level functions of JavaScript like <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext-method-apply">apply</a>, they have their own version of <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Function-method-createInterceptor">Delegate</a> (yeah, <a href="http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00001842.html">remember</a> that <a href="http://jessewarden.com/2007/10/converting-as3-to-as2-and-surviving-as2-in-general.html">bullshit</a>? LIVE IT LOVE IT SUCKAZ AND THANK <a href="http://jessewarden.com/2010/04/steve-jobs-on-flash-correcting-the-lies.html">STEVE JOBS</a>Â FOR IT), as well as a rudimentary <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Function-method-bind">binding syntax</a>.</p>
<p>They support inheritance and package names for your components. Although I&#8217;ve never done Ext JS 3, it&#8217;s clear they are constantly improving because the syntax in 3 was nasty compared to 4.</p>
<p><strong>Templates</strong></p>
<p>I&#8217;m still learning about the world that is HTML Templates but suffice to say there are 2 main uses in Ext JS.</p>
<p>The first is custom components. Creating custom components in Ext JS is pretty straightforward; you just extend <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Component">Component</a> or <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.layout.container.Container">Container</a>,Â similarÂ to Flex. However, they&#8217;re creating the DOM for you. What if you want to create your own HTML elements based on some strange PSD/AI design comp the company Crayon Pusher sent you? You can create your own HTML and have the data actually bound into it through aÂ similarÂ binding syntax we&#8217;re used to.</p>
<p>The second is item renderers. Any type of list, whether a small Container, or an actual component within a DataGrid itemRenderer can use a template. This allows quick creation of an itemRenderer without having to write a lot of code if you want to. Pretty sick.</p>
<p><strong>MVC, MVP, MVVM, Your Mom</strong></p>
<p>I&#8217;m not going to go into their MVC too much. Suffice to say, they like the <a href="http://martinfowler.com/eaaDev/PassiveScreen.html">Passive View</a>Â and have no qualms with a Controller managing multiple Views (at least, that&#8217;s what the Fast Track implied, but they don&#8217;t have time in those types of courses to show you all avenues). Worse, their naming scheme assumes you have a flat file structure, so you don&#8217;t name something &#8220;MyModel&#8221;, just &#8220;My&#8221; because they&#8217;ll append a name to it anyway causing it to be MyModelModel. That, and I fail to see how a flat directory structure of model, view, controller will scale to an application of any reasonable size, even with Ext ability to use string namespace aliases to refer to your classes.</p>
<p>Keep in mind the instructor was only given 1 day to show 1 way to do MVC, and we didn&#8217;t get too much time to dive hard core into the internals. It was clear, though, none of us liked it, and already Flex 1 era framework ideas were churning to bring our ideas (and biases) to Ext JS.</p>
<p><strong>What Sucks</strong></p>
<ol>
<li>Built on JavaScript, not CoffeeScript or Dart</li>
<li>They have horrible naming conventions for optimization purposes that no longer matter in todays world.</li>
<li>Tooling</li>
</ol>
<p>The top of this post covers my major concerns about JavaScript for applications of this size. I&#8217;m not worried about performance, just team velocity compared to ActionScript. In my experiences with Lua and ActionScript 1, your velocity in the beginning tends to be faster, but you hit a plateau and the lack of strong-typing annihilates your teams velocity and ability to project accurately. Unit tests help, but are more of triage vs. a tool.</p>
<p>The naming conventions are bourne of an era no one should care about but they still do. We&#8217;re in a gray transition as browser makers bring the HTML Stack up to speed to build applications, so you can&#8217;t just full stop ignore all the lessons learned.</p>
<p>However, I&#8217;d argue, as would countless others, that code readability trumps performance concerns. This goes way beyond &#8220;premature optimization is the root of all evil&#8221;. On extremely large code bases, verbosity is a virtue. You want readable code that it is easy to understand, both for your team and for yourself.</p>
<p>Because of String lookup costs and theÂ abilityÂ for JavaScriptÂ minifiersÂ to only compress none-reserved words like &#8220;this&#8221;, countless techniques are used toÂ obfuscateÂ the code to compensate. That may have mattered back then, but it doesn&#8217;t matter now. Worse, though, is that the counter justification is that for larger code bases, you do in fact need to make every optimization you can which in turn I counter double fold:</p>
<ol>
<li>Readable code trumps performant code.</li>
<li>If this is such a concern, why are we using this over Flex again?</li>
</ol>
<p>More importantly, however, is for API development. API&#8217;s are given to people who you sometimes have no contact with, nor have any clue about their adeptness. Thus, you need to make it as easy and obvious as possible. For an Enterprise framework such as Ext JS, you&#8217;d think this would be top priority. It&#8217;s clear Ext JS has some highly experience web developers involved in developing the API. I respect their knowledge, but it&#8217;s time to change.</p>
<p>Examples include Ext.getCmp vs. Ext.getComponent, Ext.getEl vs. Ext.getElement, and baseCls vs. baseClass. It&#8217;s prevalent throughout the framework, and mixed in with good verbosity&#8230; which makes it worse.</p>
<p>Ext JS 4.5 clearly needs a name overhaul if they expect senior programmers to take it seriously. Considering it&#8217;s JavaScript with Ext JS&#8217;s alias support, you&#8217;d think this would be easier to do.</p>
<p>While <a href="http://www.sencha.com/products/designer/">Ext Designer</a> completely blows away <a href="http://www.adobe.com/products/flashcatalyst.html">Adobe Catalyst</a>, it still has some issues with regards to the code generated and code round trip/merging. While looking nice, the results are not always being correct. We had easily duplicatable issues where the code generated did not match what was in the IDE GUI. Still, an extremely useful tool for generating a lot of the needed visual component code.</p>
<p>Finally, the lack of out the box code IDE is a near deal killer, at least for strict TA&#8217;s we deal with at large organizations. I know <a href="https://twitter.com/__ted__">Ted</a> said they&#8217;re working on it. Without things like intellisense and code hinting, you&#8217;ll make it hard for people to take things seriously, as well as making it harder to learn for more traditional programmers who suddenly have none of their mature toolset available&#8230; like&#8230; Java Developers&#8230; who came to Flash&#8230; and left&#8230; and&#8230; then they created Flex Builder&#8230;</p>
<p><strong>Critical Mass</strong></p>
<p>It seems Sencha has all the hallmarks for success and reaching critical mass with Ext JS. This is the ONLY reason I and others have given them any attention. As previously mentioned, you need a mid-size company, with money, and a good product to have it adopted as a targetable platform for large organizations. Sencha seems to have all 3. That, and again their components are pretty cool.</p>
<p>As a consultant, their components, charts, Ext Designer, and website all demo nice as well making it easier to sell as an alternative to Flex.</p>
<p><strong>Mobile Story</strong></p>
<p>I won&#8217;t get into much here, but suffice it to say I&#8217;ve yet to see the mobile revolution impact our clients as much as it has impacted the Design Agency sphere. While both focused on consumers, for a lot of brands, smart phones and tablets are seen as a growth market, or the ONLY market, to reach certain demographics. All the statistics point to both the behavioral change of society using their devices to interact with the digital world vs. computers, yet those same statistics also who the desktop still being the leader in PRODUCING that content that the world consumes. Yet given that, the money doesn&#8217;t seem to be flowing in lock step.</p>
<p>As such, most initiatives have been &#8220;it&#8217;d be cool to blow some money on&#8221;, &#8220;we have to provide something for iOS, even if it&#8217;s crap&#8221;, and the most common &#8220;wait&#8230; this won&#8217;t make any money&#8221;. While I know there are a lot of device work going on out there, it&#8217;s just not in my consulting sphere, or if it is, it&#8217;s at a extremely low profitability area and thus not worth investing in.</p>
<p>For now, the same large interfaces that we make on desktops do not transfer at all to smart phones nor tablets. Just like how people started to taking their iPhone&#8217;s to work, and companies stopped installing company phones, and later with Macs so companies started offering Mac&#8217;s as well as PC&#8217;s&#8230; so too will this have to happen with tablets before large companies even have it on their radar as a focused set ofÂ initiatives.</p>
<p>Obviously this is dependent on industry type, but we&#8217;re just not seeing it in the financial/insurance area, only slightly in the media company area (which I might add are the only ones who seem to care about Android).</p>
<p>&#8230;but let&#8217;s pretend it DOES matter. Let&#8217;s say a Director wants to know your mobile portability story? What do you tell them?</p>
<p>With Flex it was pretty straightforward: 60% to 80% of your Service and Application Layer code could be ported, with no change, to have the same Flex desktop application work on iPhone, iPad, Playbook, and Android devices. The missing piece here, is the device&#8217;s web browser.</p>
<p>While I&#8217;m a huge/firm believe in a long term native future for devices, there are still many use cases when a consumer is in a hurry and hits a company&#8217;s website expecting it to work. Considering some Operators only allow some applications to be downloaded over Wifi vs. 3G, this makes the website more important since even 3G can act as Edge. If you&#8217;re a business traveller, regardless if you&#8217;re on AT&amp;T or Verizon, you know exactly what I&#8217;m talking about.</p>
<p>2 key examples include <a href="http://marriott.com">Marriott.com</a> and <a href="http://www.papajohns.com">PapaJohns.com</a>. I encourage you to play with both on your iPhone/Android&#8217;s web browser. You&#8217;ll notice they try to duplicate the native Â look &amp; feel paradigm. &#8220;It works like an app!&#8221;. Sometimes it works, sometimes it doesn&#8217;t. The responsiveness is the first thing you&#8217;ll notice that falls on it&#8217;s face. Apps just perform better, and consumers can tell. At least for now.</p>
<p>That&#8217;s not the point, though; notice how the functionality they need is forced to be simple because of the screen real estate being so small. There are a lot of use cases where even just a company mobile app is needed for its Desktop equivalent. Other times, you really do want to get as much information as possible from the user (a la Papa Johns). To me, Papa Johns is the perfect example of an application that an Enterprise would want on a phone, then they realize at the design/analyze phase/outset that most funtionality couldn&#8217;t be done, but shove in as much as they could anyway.</p>
<p>If you&#8217;re forced to comply, what do you do?</p>
<p>You use <a href="http://www.sencha.com/products/touch/">Sencha Touch</a>.</p>
<p>Now the same story applies like it did in Flex with 1 key differnence: Using <a href="http://phonegap.com/">PhoneGap</a>, you can now target everything. All devices including their web browser, all while sharing 60% to 80% of your Service and Application Layer code. In theory&#8230; I&#8217;ve heard a lot of negativity towards Sencha Touch v1, but apparently v2 is a lot better, haven&#8217;t investigated the code yet, just testing the components on devices.</p>
<p>Pretty cool, huh?</p>
<p><a name="conclusions"></a><strong>Conclusions</strong></p>
<p>If you haven&#8217;t read <a href="https://plus.google.com/109047477151984864676/posts/CVGJKLMMehs">JoÃ£o Saleiro&#8217;sÂ article</a>, and you&#8217;re a Flex Developer, I encourage you to do so. I&#8217;ve reached many of the same conclusions as he did. The comments also have a lot of good info as well. The most important being team velocity. Time is money. This isn&#8217;t important to just large companies, either.</p>
<p>There are a lot of things we can do better and faster in Flex for large scale applications. It doesn&#8217;t matter, however, for 2 reasons. First, while from a technical perspective Flex&#8217; future is bright, from a marketing and business one it&#8217;s over. The next 5 years are the sunset. Like FORTRAN and Cobol, companies invested billions, and those applications that run parts of their business don&#8217;t magically disappear overnight. Second, even if we know it may be a better solution for some use cases (many objects like Visio, highly dynamic interactions w/many redraws, compositing images &amp; video, etc), we&#8217;re ultimately beholden to what our clients want, even if we know what they need is different. Thus we have to do both: Flex and Ext JS.</p>
<p>Based on all of read and seen, next to Dojo, Ext JS is the best solution to utilize for HTML5 web application development if you are a Flex Developer dealing with large applications and teams. Their components, documentation, mobile story, company size, and growth show that they are close to reaching critical mass where it can be adopted by large companies as a viable product to use for things traditionally done by Flex. Additionally, a lot of what you already know carries over to Ext JS quite well. If you&#8217;re like me, you just need to freshen up on your DOM and CSS knowledge, and re-examine JavaScript with fresh eyes compared to the AJAX revolution bs of 7 years ago.</p>
<p>Furthermore, unlike other server-side solutions, Ext JS lends itself quite well to hybrid solutions with Flex being used for certain use cases and the HTML stack for others, all on the same project. You and/or your firm having the capability to provide both is immensely valuable. Utilizing Sencha Touch and PhoneGap, you now have multiple mobile options in yourÂ tool beltÂ as well.</p>
<p>For the record, I still believe using Ext JS will take longer and have a harder to track velocity compared to using Flex. That said, I&#8217;m still diving into Ext JS with a positive attitude.</p>
<p>Good luck!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2012/02/sencha-ext-js-is-viable-technology-choice-for-flex-developers.html/feed</wfw:commentRss>
			<slash:comments>21</slash:comments>
		
		
			</item>
		<item>
		<title>Using Flash to Skin Flex Components</title>
		<link>https://jessewarden.com/2011/10/using-flash-to-skin-flex-components.html</link>
					<comments>https://jessewarden.com/2011/10/using-flash-to-skin-flex-components.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Wed, 26 Oct 2011 00:21:03 +0000</pubDate>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[skinning]]></category>
		<category><![CDATA[swc]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=2960</guid>

					<description><![CDATA[I&#8217;ll add more later&#8230; busy&#8230; package { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.BlendMode; import flash.display.DisplayObject; import flash.geom.ColorTransform; import flash.geom.Matrix; import mx.core.UIComponent; [DefaultProperty("children")] public class FlashSymbolContainer extends UIComponent { private var _children:Array; private var childrenDirty:Boolean = false; public function get children():Array { return _children; } public function set children(value:Array):void { if(value != null) { _children = [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I&#8217;ll add more later&#8230; busy&#8230;</p>
<p><iframe loading="lazy" width="640" height="360" src="http://www.youtube.com/embed/EYC5Ube331I?hd=1" 
frameborder="0" allowfullscreen></iframe></p>
<p><span id="more-2960"></span></p>
<pre lang="actionscript">package
{
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.BlendMode;
	import flash.display.DisplayObject;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	
	import mx.core.UIComponent;
	
	[DefaultProperty("children")]
	public class FlashSymbolContainer extends UIComponent
	{
		
		private var _children:Array;
		private var childrenDirty:Boolean = false;
		
		public function get children():Array { return _children; }
		public function set children(value:Array):void
		{
			if(value != null)
			{
				_children = value;
				childrenDirty = true;
				invalidateProperties();
			}
		}
		public function FlashSymbolContainer()
		{
			super();
			
			width 	= 300;
			height 	= 200;
		}
		
		protected override function commitProperties():void
		{
			super.commitProperties();
			
			if(childrenDirty)
			{
				childrenDirty = false;
				redraw();
			}
		}
		
		private function redraw():void
		{
			if(_children == null)
				return;
			
			var len:int = _children.length;
			if(len == 0)
				return;
			
			for(var index:int = 0; index < len; index++)
			{
				var obj:DisplayObject = _children[index] as DisplayObject;
				if(obj == null)
				{
					throw new Error("Children must be of type DisplayObject.");
					return;
				}
				
				if(obj.parent)
					obj.parent.removeChild(obj);
				
				addChild(obj);
			}
		}
	}
}</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2011/10/using-flash-to-skin-flex-components.html/feed</wfw:commentRss>
			<slash:comments>22</slash:comments>
		
		
			</item>
		<item>
		<title>Why Robotlegs For Games?</title>
		<link>https://jessewarden.com/2011/08/why-robotlegs-for-games.html</link>
					<comments>https://jessewarden.com/2011/08/why-robotlegs-for-games.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Sun, 07 Aug 2011 18:10:54 +0000</pubDate>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[corona]]></category>
		<category><![CDATA[designpatterns]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[mvc]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=2777</guid>

					<description><![CDATA[Why Robotlegs for Games? The following covers why you would utilize the Robotlegs MVC architecture in a lightweight, Lua game for Corona. I&#8217;ll discuss the refactoring reasoning, the common problems you run across in game architecture, and their solutions with their pro&#8217;s and con&#8217;s discussed. Finally, I conclude on how Robotlegs helps solve these common [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" style="padding-right: 8px;" src="http://jessewarden.com/archives/blogentryimages/corona-robotlegs-games.jpg" alt="" width="300" height="232" align="left" /><strong>Why Robotlegs for Games?</strong></p>
<p>The following covers why you would utilize the <a href="http://robotlegs.org">Robotlegs</a> MVC architecture in a lightweight, <a href="http://lua.org">Lua</a> game for <a href="http://www.anscamobile.com/corona/">Corona</a>. I&#8217;ll discuss the refactoring reasoning, the common problems you run across in game architecture, and their solutions with their pro&#8217;s and con&#8217;s discussed. Finally, I conclude on how Robotlegs helps solve these common issues, specifically in a Lua &amp; Corona context.</p>
<p>I&#8217;ve started the port of Robotlegs to Lua to work in Corona if you&#8217;re interested in <a href="http://jessewarden.com/2011/08/robotlegs-for-corona.html">learning more</a>.</p>
<p><strong><span id="more-2777"></span>Refactor First</strong></p>
<p>In learning Lua &amp; Corona, I quickly ran into 2 problems with the game I&#8217;m working on. The main code controller became way too large to manage. It wasn&#8217;t quite a God object (yes, the anti-pattern) because a lot of the View&#8217;s themselves handled some of the necessary messaging &amp; logic. Regardless, time to refactor.</p>
<p>The first thing was to start using classes. Lua doesn&#8217;t have classes. There are a bunch of resources out there that explain how to do them in various incarnations. I went with a version that Darren Osadchuk, creator of the <a href="http://www.ludicroussoftware.com/corona/simple-oop-with-inheritance-in-corona/">Corona bundle</a> for TextMate.</p>
<p>The second thing was to start using packages. Lua doesn&#8217;t have packages. There are various ways of implementing them which are all confusing as hell. The easiest way is to just put your code in a folder and use that path in the require function, but you can&#8217;t utilize folders for Android in the latest build of Corona at the time of this writing.</p>
<p>These are the low hanging fruit of re-factoring, and has made a huge difference in code readability &amp; maintainability.</p>
<p><strong>Burdens of Encapsulation</strong></p>
<p>The downside of OOP is that it&#8217;s encapsulated. While making something a black box with internally managed state &amp; implied reusability is good on the surface, it pushes the burden of managing communication between those encapsulated objects to someone ones.</p>
<p>You have 3 options: globals, messaging dependencies, or mediation.</p>
<p><strong>Global Variables: The Good</strong></p>
<p>Most people agree global variables are badâ€¦ in larger software development. In smaller scoped software gaming, not so much. Let&#8217;s explore their benefits.</p>
<p>In a lot of languages, globals are part of the language design, irrespective of how the runtime and tools/IDE&#8217;s handle them. Some languages make them first class citizens with mechanisms and rules around how they&#8217;re often used. This makes them formalized, accepted, AND useful. This is important to understand.</p>
<p>If it&#8217;s formalized, it means the language designers deem their usage acceptable, AND expected.</p>
<p>If it&#8217;s accepted, it means others will use them, incorporate them into their projects, libraries, and training &amp; writing materials. This also means it&#8217;s then promoted amongst the community, solutions and coding strategies/solutions are built around it. This doesn&#8217;t make it inherently &#8220;good&#8221;, just accepted in that particular community.</p>
<p>If it&#8217;s useful, the majority of people will use it if their job is using that language as opposed to hobbyists, or those who continue to explore the language and try different ways to solve similar problems with it off of their employer&#8217;s clock.</p>
<p>In Lua, globals are all 3. Formalized via _G, very similar to ActionScript 1&#8217;s _global, accepted in that people do in fact use them (unknowingly a lot I&#8217;d wager), and useful since the syntax to utilize globals is terse; a Lua hallmark. Notice both have the preceding underscore to ensure they don&#8217;t interfere with the developer&#8217;s potential to create a variable called G or global. While ActionScript 1 has some security implementations to prevent certain loaded SWF&#8217;s from writing/modifying existing definitions, they had the same mechinism with strorage, first via _level&#8217;s on a per SWF basis, and later a formalized _global. Lua takes it a step farther with a series of facilities to change &#8220;which&#8221; globals your using, etc. It&#8217;s also used in package naming strategies, OOP, etc.</p>
<p>As a globally accessible table, access to _G is fast. Fast is good in game development. You want to be part of the solution, not part of the problem.</p>
<p><strong>Global Variables: The Bad</strong></p>
<p>This differs from traditional software development. If you come from any formal software development, globals are considered extremely bad practice. There is a common strategy to use the Singleton design pattern to &#8220;get away with it&#8221;. Even those are considered bad practice when over used. In fact, Singletons are often created merely because the language doesn&#8217;t offer a formalized way of doing global variables (like ActionScript 3 vs. ActionScript 1).</p>
<p>Why? The 3 main reasons are application state coupling, access control, and preventing testability.</p>
<p><strong>Application State Coupling</strong></p>
<p>Application State Coupling refers to the state of your application being dependent on usually a series of global variables. I won&#8217;t get into the why&#8217;s, but <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> and it&#8217;s <a href="http://martinfowler.com/eaaDev/ModelViewPresenter.html">MVP</a> derivatives (<a href="http://martinfowler.com/eaaDev/PassiveScreen.html">Passive View</a>, <a href="http://martinfowler.com/eaaDev/SupervisingPresenter.html">Supervising Controller</a>, <a href="http://martinfowler.com/eaaDev/PresentationModel.html">Presentation Model</a>) have solved most of the state problems. They keep visual state in the View&#8217;s (or anything that&#8217;s a GUI that you can see), and application logic &amp; state in the Model layer somewhere. Your application is no longer coupled to a single variable being a specific value for your application to run, to exhibit a certain bug, etc. Each piece can (usually, hehe) be run independently, and if there is a problem, you know where to look, or at least where NOT to look.</p>
<p>An example is if your player is dying too quickly, you know the problem isn&#8217;t in the player code, or the controller code, but rather somewhere in the model where his life state is being access/set/updated. If you used a global, it&#8217;d probably be set in player itself, or perhaps by an enemy bullet that hit him, etc. No clue where to look.</p>
<p>Another side effect is adding new global variables. This leads to certain parts of your application expecting the globals to be a certain value at certain times. If they aren&#8217;t, things don&#8217;t work. Because they are many different places, it becomes extremely time consuming for you to debug and track down because you don&#8217;t necessarily know who is expecting what to be set to what, and why. This is more caused by access control, howeverâ€¦</p>
<p><strong>Access Control</strong></p>
<p>Access Control refers to who can access your data, and how. In Flash &amp; Flex apps that are smaller, we&#8217;ll usually use the server as access control. Meaning, while we provide a GUI to allow people to create, edit, and delete users from a database for example, the actual PHP/Ruby/Python/Java on the server is the access control. No matter what we do in the <a href="http://adobe.com/products/flex">Flex</a>/<a href="http://adobe.com/products/flash">Flash</a>, we can be assured the server (usuallyâ€¦ *sigh*) will ensure we don&#8217;t delete people we&#8217;re not allowed to, delete users en-masse, put illegal characters into their name, etc. Basically anything that would corrupt the data and screw the up the GUI.</p>
<p>In Flex/Flash apps, and nowadays in larger JavaScript web applications, you have a notion of &#8220;application logic&#8221; or &#8220;application state&#8221;. This is because this state is no longer on the server. It used to be with some web applications, usually in the session. When you go add something to your cart on Amazon.com, it&#8217;s not stored on the page that much beyond to show you a slight graphical change. Once you change pages, that JavaScript &amp; HTML page state is now gone and replaced with a new oneâ€¦ but it remembers what you added. It does this because the state is saved on the server since the client needs to be stateless if the user refreshes the page to go to another one.</p>
<p>We don&#8217;t have that problem as much in Flash/Flex apps. We don&#8217;t go to pages insomuch as new &#8220;Views&#8221;. These views, or graphical representations of a GUI that have internal state, are still in the same SWF embedded in the same page in a browser that doesn&#8217;t go anywhere (same thing for an <a href="http://adobe.com/products/air">AIR</a> app on the desktop or on a mobile device). Therefore, someone has to be responsible for holding the data in a variable or series of variables, and updating it when the server gives you new data.</p>
<p>These are usually classes called &#8220;Models&#8221;, and they&#8217;ll usually mirror their server-side equivalents in terms of CRUD operations: create, read, update, and delete. Where they differ is how much of the server-side provided data is parsed, error handling, data access control, and how that server-side data is set internally.</p>
<p>Suffice to say, good Model classes are encapsulated, ensure application logic is accessed by a public API that ensures security, doesn&#8217;t allow the internal data to be corrupted, and does all this within reason. An example is our Player&#8217;s health. If every enemy collision and bullet out there has access to the player&#8217;s health, we have no easy way to track down who may be potentially doing the math wrong on calculating the new hit-points and setting them to invalid values, or thinking the player is dead when she&#8217;s not, etc. If you have a PlayerModel, you can ensure your problem&#8217;s regarding hit-points and letting the world know about player death is in one place, and problems with said state (how much health does the player currently have) starts in that class and those who access him. Access control in this case refers to ensuring the PlayerModel only exposes methods to increment/decrement the Player&#8217;s hit-points vs. allowing them to be set to -16, or NaN/Nil, etc. You don&#8217;t even have to worry about this; you just don&#8217;t allow it to happen.</p>
<p>Thus, the burden on accessing and setting hit-points correctly is pushed to someone else; those who access PlayerModel. THIS is where you look for bugs, but again, you need to ensure only a set few have access to the data access layer (PlayerModel).</p>
<p>In short, Models centralize data access, ensure it&#8217;s correct, testable, and <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a> and prevent incorrect access errors, (i.e. global.playerHitPoints = &#8220;dude, pimp!&#8221;).</p>
<p><strong>Preventing Testability</strong></p>
<p>This third problem isn&#8217;t necessarily around unit-testing and <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a> (Test Driven Development), but more around just ripping the class out, putting in a simple main.lua, and seeing if it works. If it has dependencies, they get dragged with itâ€¦ and you have to instantiate and setup those guys. Suddenly quickly confirming some class or method works or not becomes a time consuming process that&#8217;s painful. If you can&#8217;t test something in isolation, you&#8217;ll have huge problems down the road isolating problems in a timely fashion.</p>
<p>Globals by their very nature are&#8217;t testable because they&#8217;re variables, not encapsulated classes. While Lua has some neat mechanisms to encapsulate globals in certain contexts, somewhere, someone is setting a global to some value in their own way. If a class depends on this global, that global must be set the same way before you test the class that relies on the global. Since you may not know who set the global a certain way, that global may not be the same in your test environment vs. in the game proper.</p>
<p><strong>Global Conclusions</strong></p>
<p>While globals in Lua are fast, formalized, and accepted, you must be aware of the rules so you can break them with confidence. First, keep in mind if you want to get something done, premature optimization is the root of all evil. With that in mind, ask yourself the quick question: Does creating a data access control class/layer around your globals to ensure it&#8217;s DRY and secure add so much overhead that the speed makes your game un-playable?</p>
<p>I&#8217;ve found this not to be the case in my implementations in Lua and ActionScript. They run fine, are encapsulated, and succeed in good access control. Thus, while globals are accepted in Lua, implementing a good coding practice via a data access layer does not adversely affect my performance while increasing my productivity in DRY&#8217;er code that&#8217;s easier to test with good encapsulation.</p>
<p><strong>Messaging Dependencies</strong></p>
<p>We&#8217;ve seen how globals can work to allow multiple View&#8217;s to talk to each other directly or indirectly via variables they all reference, or even methods/tables. We&#8217;ve also see how this leads to bad things like harder to find bugs and spaghetti code (you change 1 thing that adversely affects something else seemingly unrelated) as well as making refactoring more challenging than it needs to be.</p>
<p>One way to allow encapsulated objects to communicate is through messaging systems, also know as notifications or events (we&#8217;ll just call them events because that&#8217;s what ActionScript and Corona use). When something happens inside the object, such as a user clicking something, or some internal property changes, it&#8217;ll emit an event. There are 3 types of events we&#8217;re concerned with: local, global, and event context.</p>
<p>A local event is an event issued from an object/table. In ActionScript, anything that extends EventDispatcher, including DisplayObjects (things you can see), can emit events. In Lua, only DisplayObjects can; you have to build your own for regular tables as Lua doesn&#8217;t have an event system. So, if I create a wrapper table in Lua, I can then register for events from that table, and later when it emits them, I&#8217;ll hear them. Those are local events; events dispatched from an object/table directly. Although event objects/tables have the target property on them so I know where they come from, USUALLY event responders are not that encapsulated, and make the assumption that the event is coming from a specific object/table.</p>
<p>A global event is one that&#8217;s received, but we have no clue where it came from. At this point, we&#8217;re inspecting the event object itself to find context. If it&#8217;s a collision, then who collided with who? If it&#8217;s a touch event, then what was touched, and how? Global messaging systems are used for higher-level events and concerns. While you usually won&#8217;t have global events for touches because your mainly concerned with handling the touch event locally, a pause event for example could of been issued from anywhere, and while you don&#8217;t care who issued it, you&#8217;re more than capable of handling it (stopping your game loop, pausing your player&#8217;s movement, etc).</p>
<p>To properly handle an event, we need context. Context is basically the data the event, or message, has stored internally so when the handler gets it, he knows how to handle it. If the event is a touch event, cool, start moving. If it&#8217;s a touch release event, cool, stop moving. If it&#8217;s a collision, is it a bullet? If so, take less damage than say a missile hitting. Is the bullet&#8217;s velocity higher? If so, take more damage than usual. This context is what allows the encapsulation to happen. You issue a message, provide context, and whoever gets it doesn&#8217;t necessarily HAVE to know where it came from; they&#8217;ll have enough information to know how to handle it.</p>
<p>For Corona DisplayObjects, this is easy. You just use dispatch an event. But for Model/data access objects, not so much. You don&#8217;t want the overhead of a DisplayObject to just to send messages, so you build your own. This implies another class/table with the capability of sending/receiving messages. This means your classes will have a dependency on this object. For example, if I want to test my Model class in a brand new main.lua, it&#8217;ll bring along/require the messaging class. This is a dependency. One of the threads (just like OOP, encapsulation, keeping things DRY, don&#8217;t optimize too early, etc) you want to keep in the back of your head is to keep the dependencies low. You don&#8217;t want a class to have too many dependencies. Like globals, dependencies can cause spaghetti code, hard to test &amp; debug situations, and overall just hard to manage code.</p>
<p>Corona makes the event dispatching dependency invisible with DisplayObjects because it&#8217;s built in. Not so for regular tables. Somehow, you have to put this dependency in every class. You can either create a public setter for it, and pass in an instance, or just reference a class globally in a base class. Both are a dependency, the latter just requires a lot less work and code.</p>
<p>Downside? It&#8217;s a dependency. You also force this implementation on everyone who wishes to utilize your class. If you make the messaging system events, 2 things happen. First, people using Corona get it because it&#8217;s the exact same API and functionality (excluding bubbling) that developers are used to. Secondly, it&#8217;s interchangeable and works with Corona DisplayObjects. The best solution would be to do Dependency Injection/Inversion of Controlâ€¦ but I haven&#8217;t figured out how to do this in Lua yet, and I&#8217;m not sure Lua supports metadata annotations. Considering it&#8217;s dynamic, you CAN inject things like this at runtime, but someone, somewhere has to do so. Why do so when every object requiring messaging needs the same mechanism? Thus, the pragmatic thing is to build it in.</p>
<p>Also, more importantly, DOES this messaging system add more performance overhead than using simple globals? To make the question harder to answer, can you make tighter coupling of your code and still get things done?</p>
<p>It&#8217;s been my experience, if you make things easier to use with less coupling, you&#8217;re more productive in the last 10% of your project. While coupling makes things easy in the beginning, it&#8217;s a farce; it has more than an exponential cost at the end.</p>
<p>Besides, you can always increase coupling easily; it&#8217;s removing coupling later that&#8217;s hard. If you need to optimize, great, you can. If not, great, no more work to do; you can instead focus on features. Usually, though, you&#8217;ll know pretty quick if you do iterative builds if a messaging system is making a huge performance impact on your game on not. The only surprises you&#8217;ll get is you spend days on something without a build. Do a small test, see if there is a noticeable difference. Sometimes you&#8217;ll have n-problems you won&#8217;t find till your game gets to a specific size which are unfortunate. An example is a charting component that works great building up to 5000 data points, but suddenly DRASTICALLY slows down beyond that.</p>
<p>These problems aren&#8217;t the fault of the API. If you take a step back, the &#8220;30,000ft view&#8221;, usually it&#8217;s the implementation that&#8217;s at fault, not the code itself.</p>
<p>For example, a little history lesson. Back when ActionScript 1 development was increasing in scope, we went through 4 different messaging systems. The first was the built-in one for Mouse and Keyboard, etc. It was only partially available; there wasn&#8217;t a MovieClip one. So, we used ASBroadcaster; an undocumented one inside of Flash Player. It had a known bug with removing a listener during a dispatch, and other things. Then Bokel released a version on top of that fixed it. Then Adobe created EventDispatcher, mirroring the ECMA one. They then built this into the Flash Player for Flash Player 9&#8217;s new virtual machine.</p>
<p>There were others that came out after ActionScript 3 was born. <a href="http://puremvc.org">PureMVC</a> had notifications in it for an easier port to other platforms &amp; languages. Robert Penner created <a href="http://flashblog.robertpenner.com/2009/09/my-new-as3-event-system-signals.html">Signals</a> for a light-weight, object poolable, quick to develop in C#-esque messaging system.</p>
<p>As you can see, why the bottleneck for most larger Flash &amp; Flex 1.x applications at the time was EventDispatcher, even when they built it into the runtime in C, developers opt-ed for a slower system built by themselves to solve different problems.</p>
<p>So why the continuous talk about performance questions in this section when I rail against premature optimization? Because messaging is the core of any app, or game. The choice you make is the largest impact on what you&#8217;re building, both from performance and from a development perspective. Yes, you can just use direct access to objects, or callbacks, but that&#8217;s not very encapsulated, nor DRY, and is a pain to re-factor later if you need. Messages via Events are more encapsulated, and less coupled, but have a performance impact. Additionally, only DisplayObjects use the internal C implementation; your own uses interpreted Lua with whatever JIT&#8217;ing/machine/voodoo conversion Corona does.</p>
<p>Traditionally, it&#8217;s easy to switch to events from callbacks, but not the other way around. While the performance impact isn&#8217;t that large to utilize a DisplayObject and use the built-in event messaging, based on some benchmarks, this isn&#8217;t a good idea to build upon.</p>
<p><strong>Mediation</strong></p>
<p>The third option is using the <a href="http://flexblog.faratasystems.com/2007/09/26/applying-the-mediator-design-pattern-in-flex">Mediator pattern</a>. Once you have 2 encapsulated objects that need to talk to each other, you utilize a class that handles the communication. It takes the message from ViewA and sends that to ViewB. When ViewB wishes to talk to ViewA, it sends the message and the Mediator relays it.</p>
<p>All the MVC/MVP articles go over A LOT about the different things a View should/should not do,Â particularlyÂ with it&#8217;s needs for data and how to show it. Regardless of the implementation, it&#8217;s generally understood that someone such as a Mediator or a Presenter handels the responses from a View. If it&#8217;s a Presenter, it&#8217;s a dependency in the View, and the View calls methods on it. This allows the actual logic behind both responding to View user gestures (like when I touch a button on the phone) to not muddy up the View (muddy up means TONS of code that has nothing to do with displaying graphics, putting into groups, setting up Sprite Sheets, etc), and allows you to test the behavior in isolation.</p>
<p>Mediator&#8217;s areÂ similar, although, the View has no idea he/she has a Mediator, and the Mediator has the View reference passed into it by someone else. Again, more encapsulation, yet SOMEONE has to have the burden of setting up this relationship. In ActionScript this is easy; Robotlegs just listens for the Event.ADDED_TO_STAGE/REMOVED_FROM_STAGE events and creates/destroys based on an internal hash/table. In Lua, you don&#8217;t have any DisplayObjects events, so you have to manually do it.</p>
<p>Either way, if you DON&#8217;T Mediate your View&#8217;s, you&#8217;ll eventually have a lot of code in there that has to &#8220;know&#8221; about other objects. This&#8217;ll be either a global reference, or a dependency&#8230; and we&#8217;ve already talked about why those things are bad to do. Additionally, tons of code in general is bad; having a View just focus on graphical things and emitting events people outside would care about while the logic can be put elsewhere makes it easier to manage. When you open a View class; you know pretty quickly what you&#8217;re looking at is just GUI specific code.</p>
<p>There&#8217;s another more important aspect of Mediation that isÂ similarÂ to messaging and that is system events that affect Application Logic.</p>
<p>For example, many things in a game care about a Player&#8217;s health.</p>
<ul>
<li>the Sprite that represents the player; it needs to show different graphics for how much health it has</li>
<li>a health bar at the top right of the screen that fills up with green the more health the player has</li>
<li>sounds that play when the player loses and gains health</li>
</ul>
<p>If you use globals, you&#8217;d have all 3 handled by the actual Player sprite class. It&#8217;d update it&#8217;s internal health and update the global variables. Those who have references to the globals would be informed when that value changes. Additionally, you&#8217;ve now wired them together if you do this. If you change one, you&#8217;ll break the other.</p>
<p>Using a Mediator allows:</p>
<ul>
<li>the player and the health bar both the capability to react to the change in the hit points in an encapsulated way. If you change how the Player and HealthBar look/work, the actual logic on how yo do that is centralized to either them, or their Mediators&#8230; and usually Mediators are like 1 line of actual code to change.</li>
<li>The application logic of how hit points are updated and changed to be done in 1 place. As your game grows and different enemies need to do different types of damage to your player, and sometimes react differently depending on how much health the player has, this is all done and updated in 1 place. It&#8217;s DRY, and easy to find where the logic bugs are.</li>
<li>A side effect of this is&#8230; the Mediator pattern (lolz). You can have View&#8217;s the capability of talking to each other without having tight coupling.</li>
</ul>
<p>The most important feature is solving the classic race condition of is the data ready for a View when he&#8217;s created, or is it null and he has to wait. Using Medaitors, you don&#8217;t have this problem. In the onRegister, you just set it if you have it on whatever Model(s) you need, else just wait for the Model(s) to be updated and inform the view.</p>
<p>&#8230;I wouldn&#8217;t say totally solved; handling &#8220;null&#8221; or &#8220;nil&#8221; is still a challenge for developers even in simple View&#8217;s. Those are good problems to have, though vs. race conditions.</p>
<p>If you enter the optimization phase of your game and want to remove events, use callbacks, and have hard-wired references, that&#8217;s fine if benchmarks truly identify that you need theÂ performanceÂ gains. Usually, though, Mediator communication isn&#8217;t your bottle neck, it&#8217;s collisions, lack of object-pooling, and how messages are handled.</p>
<p><strong>Quickie on Commands</strong></p>
<p>Commands are just formalized Controller logic. In fact, in other frameworks, they&#8217;re simply Controller classes with methods. They&#8217;re called &#8220;Commands&#8221; because they do 1 thing&#8230; and can potentially undo it. If you&#8217;ve ever used an Adobe Product, a few of them like Dreamweaver, Fireworks, Flash, and Photoshop will have a Command list, also called &#8220;History Panel&#8221;. In Flash and Fireworks, you can even get the code for these Commands. The line blurs here once you lump them all together, but in my experience, good Controllers have 2 things in common:</p>
<ol>
<li>They contain the only code in the application that updates the Models (update/delete in CRUD for internal data)</li>
<li>They contain all application logic&#8230; or at least share the burden with the Models.</li>
</ol>
<p>For #1, this is important in tracking down bugs and keeping your code DRY. You always know who&#8217;s changing your Player&#8217;s hit points, who&#8217;s actually applying your level up rewards, etc. If you can test your Models in isolation, and they&#8217;re good&#8230; then you know who to blame. This is good because again, they tend to often start by being 1 line functions with the potential to grow to 30 to 60&#8230; not a bad way to start life, nor grow. Small, readable code.</p>
<p>For #2, whether you have a Controller class function, or a Command, SOMEONE in your application needs to &#8220;load the level data&#8221; from your level editor. SOMEONE needs to handle the fact that your player just drank a health potion, but he&#8217;s also wearing a Ring of Health Boost + 2, and this positively affects the effects of the health potions she drinks. SOMEONE needs to handle calling the loadSaveGame service, ensuring it worked, and updating all the Models with theirÂ relevantÂ Memento data.</p>
<p>This orchestrator of pulling everyone together, to read multiple Models and &#8220;make decisions&#8221;, they&#8217;re the brains of your application. For performance reasons, a lot of Controller logic is often done directly in game views, even if it just references a Controller class for ensuring logic is somewhat DRY.</p>
<p>There&#8217;s a lot of loathing in the community by those with a moreÂ pragmaticÂ bent, or just on smaller code bases with shorter deadlines. The overhead associated with them completely negates their perceived value when you can just call a centralized Controller logic function via&#8230; a function call vs. some event that magically spawns some other class that has 1 function with a bunch of injected dependencies. Just depends in you read that last sentence and go &#8220;Makes sense to me, don&#8217;t see what the issue with it is&#8230; &#8221; or &#8220;w&#8230;t&#8230;f&#8230; why!?&#8221;.</p>
<p><strong>Conclusions</strong></p>
<p>Remember, the above is all complete bs. If you or your team have a way of building games that works for you, great. This is just helpful tool I&#8217;ve found in Flash &amp; Flex application development, and it seems to help me in Corona games, specifically around the GUI/HUD portions. I still have globals in my collision routines for speed purposes, hehe.</p>
<p>Additionally, it&#8217;s a great teaching tool, too. <a href="http://joelhooks.com">Joel Hooks</a> got someÂ similarÂ schlack like I did in using <a href="http://puremvc.org">PureMVC</a> when he was first starting out in Objective C for iPhone. Providing a comfortable &amp; familiar framework of development really helped him learn and have context how the new language &amp; platform work with certain concerns; it&#8217;s how he shipped his first app on the app store. Same with me in Corona&#8230; and game development.</p>
<p>Finally, this isn&#8217;t an all or nothing approach. You can just use it on the parts you need, or perhaps just to learn. I find its helped me learn a lot about Lua and Corona, as well as having theÂ flexiblyÂ to change the API of my Player and Enemies without affecting how the GUI itself around the game works. In true spirit of total disclosure, I&#8217;ll report on any adverse overhead if I find it.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2011/08/why-robotlegs-for-games.html/feed</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
		<item>
		<title>Robotlegs For Corona</title>
		<link>https://jessewarden.com/2011/08/robotlegs-for-corona.html</link>
					<comments>https://jessewarden.com/2011/08/robotlegs-for-corona.html#comments</comments>
		
		<dc:creator><![CDATA[JesterXL]]></dc:creator>
		<pubDate>Sun, 07 Aug 2011 18:09:48 +0000</pubDate>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[ActionScript]]></category>
		<category><![CDATA[corona]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[games]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[lua]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[robotlegs]]></category>
		<guid isPermaLink="false">http://jessewarden.com/?p=2788</guid>

					<description><![CDATA[What I started a port of the popular Robotlegs framework for building Flash &#38; Flex ActionScript 3 applications to Lua for the Corona SDK. Why Longer post here. The short version: Lua &#38; Corona and hardcore game development are new to me. I&#8217;ve dabbled and had a few projects, both professional and personal, over the [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" style="padding-right: 8px;" src="http://jessewarden.com/archives/blogentryimages/corona-robotlegs-lua.jpg" alt="" width="220" height="220" align="left" /><strong>What</strong></p>
<p>I started a port of the popular <a href="http://robotlegs.org">Robotlegs</a> framework for building <a href="http://adobe.com/products/flash/">Flash</a> &amp; <a href="http://adobe.com/products/flex/">Flex</a> ActionScript 3 applications to <a href="http://lua.org">Lua</a> for the <a href="http://www.anscamobile.com/corona/">Corona</a> SDK.</p>
<p><strong><span id="more-2788"></span>Why</strong></p>
<p>Longer post <a href="http://jessewarden.com/2011/08/why-robotlegs-for-games.html">here</a>.</p>
<p>The short version: Lua &amp; Corona and hardcore game development are new to me. I&#8217;ve dabbled and had a few projects, both professional and personal, over the past decade, but nothing like the full-time opportunities/gigs I&#8217;m getting now that mobile hasÂ legitimizedÂ an alreadyÂ legitimizedÂ industry. Utilizing Robotlegs has made the GUI/HUD development for games super simple in a foreign and strange land. It&#8217;s also helped me learn more about Lua &amp; Corona by breaking out of my comfort zone from within a comfort zone. Motivation is a fragile thing that must be cared for &amp; nurtured. This helps me not get frustrated when I hit brick walls with the limited time I have in researching new technologies.</p>
<p>Keep in mind this is one the design goals, and thus helpful features of <a href="http://puremvc.org">PureMVC</a> being ported to other platforms.</p>
<p>&#8230;also, I figured it&#8217;d help others.</p>
<p><strong>Where</strong></p>
<p>You can <a href="https://github.com/JesterXL/Robotlegs-for-Corona">get it on Github</a>; it has an example in there too to show you one way to use it.</p>
<p><strong>How</strong></p>
<p>You just require the classes in, and extend the rest. Some gotchas if you&#8217;re an ActionScript 3 Developer:</p>
<ol>
<li>I haven&#8217;t figured out Lua&#8217;s annotations and metadata strategies. As such, you have to manually inject dependencies.</li>
<li>This includes manually mediating your Views via context:createMediator/removeMediator(viewInstance).</li>
<li>Another gotcha is put a classType property on your Views till I figure out how to do reflection in Lua.</li>
</ol>
<p><strong>When</strong></p>
<p>Keep in mind this isn&#8217;t an official port, nor is it finished. I&#8217;m still learning and it&#8217;s a proof of concept. I&#8217;m finding I&#8217;m only using it for game GUI and HUD stuff; and that&#8217;s like only 5% to 20% of the game code&#8230; so while it&#8217;s helpful for both learning &amp; development, I&#8217;m sure there are strategies/ideas I&#8217;m not thinking about that you&#8217;re welcome to add/modify, etc.</p>
<p>Hope this helps you!</p>
<p>Download/Modify &#8211; <a href="https://github.com/JesterXL/Robotlegs-for-Corona">Robotlegs for Corona on Github</a>.</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jessewarden.com/2011/08/robotlegs-for-corona.html/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
	</channel>
</rss>
