<?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>.:. blog.screenshot.at .:. Flash, Flex, RIA .:. &#187; Flex</title>
	<atom:link href="http://www.screenshot.at/blog/category/flash/flex-flash/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.screenshot.at/blog</link>
	<description>This blog is about Flash, Flex, RIA related stuff</description>
	<lastBuildDate>Mon, 11 May 2015 18:06:51 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.38</generator>
	<item>
		<title>Dependency Injection with code generation</title>
		<link>http://www.screenshot.at/blog/2012/03/30/dependency-injection-with-code-generation/</link>
		<comments>http://www.screenshot.at/blog/2012/03/30/dependency-injection-with-code-generation/#comments</comments>
		<pubDate>Fri, 30 Mar 2012 20:56:02 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Blog Entry]]></category>
		<category><![CDATA[Code Generation]]></category>
		<category><![CDATA[Nucleo]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=727</guid>
		<description><![CDATA[Why another Dependency Injection framework? One thing nearly all DI frameworks have in common, is the use of reflection to obtain the extra information needed to inject the objects. The downside of this approach is that reflection in general (and particularly in Flash) is pretty slow. This will probably not matter much for smaller application, [&#8230;]]]></description>
				<content:encoded><![CDATA[<p><strong>Why another Dependency Injection framework?</strong></p>
<p>One thing nearly all DI frameworks have in common, is the use of <span class="hl">reflection</span> to obtain the extra information needed to inject the objects.<br />
The downside of this approach is that reflection in general (and particularly in Flash) <strong>is pretty slow</strong>. This will probably not matter much for smaller application, but for large apps you can save several seconds of start-up time if you are not using reflection.</p>
<p>Unfortunately there is no solution out there beside a <a href="http://code.google.com/p/funk-as3/" target="_blank">project</a> from <a href="http://blog.joa-ebert.com/" target="_blank">Joa Ebert</a>, who is using a different approach. I wrote about this in another <a href="http://www.screenshot.at/blog/2012/01/31/dependency-injection-without-reflection/" target="_blank">blog entry</a>.</p>
<p>Another solution would be to use <span class="hl">code generation</span>.<br />
With code generation you can inspect your code base at <strong>compile-time</strong> and write the information needed to a class.</p>
<p>I have added such a project to the nucleo library at <a href="https://github.com/ManfredKarrer/nucleo.io" target="_blank">github</a>.</p>
<p><span class="hl">So how does it look like and how is it used?</span><br />
Here are a few code snippets from the <a href="https://github.com/ManfredKarrer/nucleo.io/blob/master/src-example/InjectMojitoExampleRunner.mxml" target="_blank">mojito example</a> at github:</p>
<p>First we need the <strong>generated class</strong> for the constructor parameter keys. This will be created by an ant task, more about this later.</p>
<pre>[code lang="actionscript3"]public class ConstructorParameters extends AConstructorParameters {
protected override function config():void {
constructorParameterKeys[BarProvider] = [IWaitress];
constructorParameterKeys[Bar] = [IWaitress];
constructorParameterKeys[Client] = ["theFewSpanishWords", IBar];
constructorParameterKeys[Waitress] = ["isInTheMood"];
}
}[/code]</pre>
<p>You need to create the <strong>Config</strong> class which contains the mappings of the objects used for injection.<br />
It passes an instance of the ConstructorParameters class to the AConfig super class.</p>
<pre>[code lang="actionscript3"]public class MojitoConfig extends AConfig {

public function MojitoConfig() {
super(new ConstructorParameters());
}

override protected function setup():void {
mapInterface(IClient).toClass(Client).asSingleton();
mapParameterName("theFewSpanishWords").toInstance("¡Muchas gracias guapa!");
mapInterface(IBar).toProvider(BarProvider).asSingleton();
mapInterface(IWaitress).toClass(Waitress).asSingleton();
mapParameterName("isInTheMood").toInstance(true);
}
}[/code]</pre>
<p>Then the <strong>setup</strong> can be done. After that you can access some root object and use this.</p>
<pre>[code lang="actionscript3"]// first we need our Config. This is the place where our injection
// mappings are defined.
var config:MojitoConfig = new MojitoConfig();

// createInjector is a package level function used for convenience
// to get the injector
injector = createInjector(config);

// we take the root object out of the injector. The other objects will
// be injected just in time when they are needed.
var touristInBarcelona:IClient = injector.getObject(IClient);[/code]</pre>
<p>Beside this, there are no traces left from the framework.</p>
<p>The Classes which gets created by the DI container are straight classes with constructor parameters totally unaware of the framework.<br />
They don&#8217;t need any &#8220;Inject&#8221; Metadata tag. They does not know anything from the DI framework and how they get created. This is <strong>not their responsibility</strong>.</p>
<p>I think this is violated by the use of the Metadata at other DI frameworks. There the class has the information inside itself that a DI container is used for creating an instance of this class. I think this should be only the responsibility of the outer world using this class like a factory or the DI container.</p>
<p>But back to the project.</p>
<p><span class="hl">How does it work internally?</span></p>
<p>Basically the injection works pretty simple as a chained instantiation of all the dependent objects, starting with the first object requested from the injector:</p>
<pre>[code lang="actionscript3"]var touristInBarcelona:IClient = injector.getObject(IClient);[/code]</pre>
<p>This will create an instance of the class which is mapped to the key IClient. In our case it is the Client class.</p>
<pre>[code lang="actionscript3"]mapInterface(IClient).toClass(Client).asSingleton();[/code]</pre>
<p>For creating the Client class it <strong>looks up in the ConstructorParameters</strong> Class and get the information to create the 2 arguments needed there:<br />
The instance mapped to &#8220;theFewSpanishWords&#8221; and an object of the class mapped with the key IBar.</p>
<pre>[code lang="actionscript3"]constructorParameterKeys[Client] = ["theFewSpanishWords", IBar];[/code]</pre>
<p>For creating an object of the Bar class it will need other objects as well, so the chain goes on like this until all objects needed are resolved.</p>
<p>The<strong> binding key</strong> can be an <strong>Instance</strong>, a <strong>Class</strong> or a <strong>String</strong> (named annotation).</p>
<p>For the named annotation I use a simple <strong>convention</strong>:<br />
The parameter name must be the same as the annotation name in the Config class, like the &#8220;theFewSpanishWords&#8221; in the example. I think there is no reason not to use this simple and sensible convention and it makes life much easier and there is no need to add a Metadata for packing in this information.</p>
<p>I only support <strong>constructor injection</strong> as I prefer this style and it lets the class stay free of any Metadata.<br />
Property or method injection could also be added but then you need to mark them with Metadata. As they would be invoked directly after the class is created i don&#8217;t see any reason why not to add these injected data to the constructor.</p>
<p><span class="hl">Now have a look to the code generation:</span></p>
<p>I used the <a href="https://github.com/teotigraphix/as3-commons-jasblocks" target="_blank">as3-commons-jasblocks</a> project which is using <a href="http://www.antlr.org/" target="_blank">ANTLR</a>. With this Java project you can read in your sources and it creates an object tree with all the elements of your code (abstract syntax tree). From this you can comfortably grab the constructor parameters and write (again with jasblocks) them into a class file.</p>
<p>I packed this into an <strong>ant task</strong>, as ant is pretty easy to use, good integrated into the IDEs and well known.<br />
In the ant task you need to setup 2 parameters:</p>
<ul>
<li>The source directories (as comma seperated list)</li>
<li>The target directory for the generated Class.</li>
</ul>
<p>To automatically trigger the code generation for the ConstructorParameters Class before the compilation, you can use the built-in support for ant tasks of the IDE.</p>
<p>In FlashBuilder and IntelliJ there are easy ways to achieve this. So if the setup guarantees to always run the ant task before the compilation, the ConstructorParameters Class will be always up to date.</p>
<p>Here a quick description<strong> how to do this in FlashBuilder</strong>:</p>
<ul>
<li> Right-click in the project and open the project properties.</li>
<li> Under Builder add a new Ant Builder before the Flex (compile) builder.</li>
<li> Under Main point to the build file:  eg. ${workspace_loc}/${project_name}/build/build.xml</li>
<li> Under JRE: select separate JRE</li>
</ul>
<p><img class="alignnone size-full wp-image-777" title="flashbuilder" src="http://nucleo.io/wp-content/uploads/2012/03/flashbuilder.png" alt="flashbuilder" width="609" height="389" /></p>
<p>That&#8217;s it.</p>
<p>In <strong>IntelliJ</strong> you need to set an &#8220;Execute On&#8221; event (&#8220;Before Compilation&#8221;) to the ant task target. Then it will be executed just before the compilation.</p>
<p><img class="alignnone size-full wp-image-776" title="intellij" src="http://nucleo.io/wp-content/uploads/2012/03/intellij.png" alt="intellij" width="490" height="316" /></p>
<p>If you don&#8217;t like to use the code generation you can also write this class by yourself of course, you just have to maintain it and it violates the DRY principle.</p>
<p><span class="hl">A few words about code generation in general:</span></p>
<p>For some people code generation has a kind of bad smell and they don&#8217;t like to rely on it.</p>
<p>I think it is a very powerful tool to get around the <strong>limitations of the language</strong> and to <strong>outsource boiler plate code</strong>.<br />
And if you use Flex you are using it anyway even if you are not aware of it. Flex use a lot of code generation behind the scenes (add the -keep compiler flag to see it) for creating ActionScript code out of MXML, css files, RPC or Data Binding.</p>
<p>I think for the <strong>coding experience</strong> and <strong>productivity</strong> it is not only the potential of the language which counts, but also the <strong>features of the tools</strong> (IDE) you are working with.<br />
What would you (as a developer writing code) benefit much from a type system if you would write your code in a primitive text editor without any code completion or error highlighting (the old Flash IDE was like this, I cannot imagine anymore how to work that way).</p>
<p>With these tools you can get also over the shortcomings of a language.</p>
<p>So I think when you hit the limitations of the language or runtime, it is valid to go in this direction and add features to help you to write clean and fast code.</p>
<p>There are also some <strong>limitations</strong> and the project is at the moment just a kind of <strong>&#8220;proof of concept&#8221;</strong>. It is not bulletproof yet and not tested in a production environment!</p>
<p>So use it at your own risk. I added comments and TODOs in the Java source code about known issues.</p>
<p>One limitation is about <strong>external library</strong> (swc) files.</p>
<p>With the as3-commons-jasblocks project you can only inspect the code base you have as source code, but not the code compiled into libraries.</p>
<p>There are some solutions (like <a href="http://www.flagstonesoftware.com/transform/" target="_blank">flagstone</a>) to access this as well, but I have not added this yet.</p>
<p>With the <strong>providers</strong> (see docs and example code) you always can get around any problems with classes out of your control like 3rd party libraries.</p>
<p>Beside this I think DI should only be used in a limited scope of a project (module).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2012/03/30/dependency-injection-with-code-generation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dependency Injection without Reflection</title>
		<link>http://www.screenshot.at/blog/2012/01/31/dependency-injection-without-reflection/</link>
		<comments>http://www.screenshot.at/blog/2012/01/31/dependency-injection-without-reflection/#comments</comments>
		<pubDate>Tue, 31 Jan 2012 21:46:21 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Api]]></category>
		<category><![CDATA[As3]]></category>
		<category><![CDATA[Bind]]></category>
		<category><![CDATA[Boilerplate Code]]></category>
		<category><![CDATA[Compromise]]></category>
		<category><![CDATA[Constructor Arguments]]></category>
		<category><![CDATA[Context Class]]></category>
		<category><![CDATA[Custo]]></category>
		<category><![CDATA[Custom Fashion]]></category>
		<category><![CDATA[Drawback]]></category>
		<category><![CDATA[Ebert]]></category>
		<category><![CDATA[Eberts]]></category>
		<category><![CDATA[Explaination]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Funk]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Guice]]></category>
		<category><![CDATA[Interface Class]]></category>
		<category><![CDATA[Joa]]></category>
		<category><![CDATA[Mappings]]></category>
		<category><![CDATA[Mylist]]></category>
		<category><![CDATA[Myscope]]></category>
		<category><![CDATA[Negative Impact]]></category>
		<category><![CDATA[Party Library]]></category>
		<category><![CDATA[Performance Drawbacks]]></category>
		<category><![CDATA[Performance Matters]]></category>
		<category><![CDATA[Provid]]></category>
		<category><![CDATA[Provider Code]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[Special C]]></category>
		<category><![CDATA[Swc]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=641</guid>
		<description><![CDATA[Joa Ebert has written a Dependency Injection framework as part of his funk-as3 library. Basically his API is orientated on Google Guice and does not use reflection, which is great, because reflection is pretty expensive regarding performance. And Performance matters. We reduced the start-up time of our application from 8 seconds to 3 seconds just [&#8230;]]]></description>
				<content:encoded><![CDATA[<p><a href="http://blog.joa-ebert.com" target="_blank">Joa Ebert</a> has written a <a href="http://code.google.com/p/funk-as3/wiki/IoC" target="_blank">Dependency Injection framework</a> as part of his <a href="http://code.google.com/p/funk-as3/" target="_blank">funk-as3</a> library.</p>
<p>Basically his <strong>API</strong> is orientated on <strong><a href="http://code.google.com/p/google-guice/" target="_blank">Google Guice</a></strong> and <span class="hl">does not use reflection</span>, which is great, because reflection is pretty expensive regarding <span class="hl">performance</span>.</p>
<p>And Performance matters. We reduced the start-up time of our application from 8 seconds to 3 seconds just by removing <a href="http://www.springactionscript.org/" target="_blank">Spring Actionscript</a> and using a pure factory-based DI which does not use reflection and has no performance overhead. The code was also better to manage then the XML based solution of Spring Actionscript. Other frameworks which are more in the Guice-style would be nice to use but have the same negative impact on performance, so it was a No-Go for us. The drawback of our factory-based solution compared to Guice-style frameworks was, that it was not so easy and nice to use and more boilerplate code has to be written.</p>
<p>When stumbling over Joa Eberts DI framework I first wanted to use it directly as 3rd party library but I got some problems with the compiled swc. So I started to build my own small DI framework based on previous ideas in this direction and refined with some of his ideas and a similar API style. Unfortunately I cannot share the code but I can give the basic ideas.</p>
<p><span class="hl">So let&#8217;s get started:</span></p>
<p>First you need to <strong>setup</strong> the Locator. It&#8217;s a one-liner and is done like this:</p>
<pre>[code lang="actionscript3"]myLocator = Locator.getLocator("myScope", myContext);
[/code]</pre>
<p>The explanation for this will follow later.</p>
<p>Further you have a <strong>Context Class</strong> (the Module in Guice) where you <span class="hl">define the bindings</span> of what you want to get injected for a special Interface, Class or named annotation.</p>
<p>Additionally you define if the object should be only created once (asSingleton) or every time newly.</p>
<pre>[code lang="actionscript3"]// Interface to Class
bind(ITestInterface).to(TestImpl).asSingleton();
 // String annotation to Class
bind("myList").to(ArrayCollection);
// Interface to instance
bind(IResourceManager).to(resourceManager).asSingleton();
[/code]</pre>
<p>To support also some special classes which are outside of your control (3rd party) you can use a Provider to get an instance created in a custom fashion in the Providers getObject() method.</p>
<pre>[code lang="actionscript3"]// String annotation to Provider
bind("myServcice").to(RemoteObjectServiceProvider).asSingleton();
[/code]</pre>
<p>When you want to <span class="hl">inject these objects</span> somewhere in your Classes, just write inject(bindingKey) to obtain the instance defined in the Context.</p>
<p>But when <strong>not using reflection</strong> we are facing some problems.</p>
<p>Without reflection you don&#8217;t have information at run-time about the constructor arguments. This is a problem when creating the classes. One solution to prevent this problem is to use only <strong>constructors without arguments</strong>.</p>
<p>Instead of the classical way like here:</p>
<pre>[code lang="actionscript3"]public function TestClass(testInstance:ITestInterface) {
    this.testInstance = testInstance;
}[/code]</pre>
<p>We assign the mandatory members directly in the constructors body with the inject call.</p>
<pre>[code lang="actionscript3"]public function TestClass() {
    testInstance = inject(ITestInterface);
} [/code]</pre>
<p><strong>Another solution</strong> would be to <strong>register the Class with it&#8217;s parameters annotations explicitly </strong> to the framework, so the information what needs to be injected when creating this Class is available.</p>
<p>Something like this (you can use a static function call as it is specific to the class, so it could be located directly above the Constructor):</p>
<pre>[code lang="actionscript3"]registerClass(TestClass).withParams([ ITestInterface, "myList" ]);
public function TestClass(testInstance:ITestInterface,
                           myList:ArrayCollection) {
    this.testInstance = testInstance;
    this.myList = myList;
}[/code]</pre>
<p>This would have the drawback that you need to maintain changes in the parameters in 2 places, and additional code needs to be written.</p>
<p>My preferred solution <strong>without constructor arguments</strong> has the drawback that the mandatory parameters are <strong>not visible in the signature of the constructor</strong>.<br />
So both has some small penalties, but the good thing is it has <strong>zero overhead performance-wise</strong> and it is as<strong> easy to use</strong> like the classic Guice style injection. </p>
<p>Of course you can use the injection in properties or methods as well. But i prefer the constructor injection for all mandatory dependencies, so it&#8217;s more clear what a class needs initially.</p>
<p><strong><span class="hl">So how does it work:</span></strong></p>
<p>Technically it is not real injection but more like the <a href="http://java.sun.com/blueprints/patterns/ServiceLocator.html" target="_blank">Locator pattern</a>.<br />
You have a Dictionary where you define the mappings of keys (Interface, Class or named annotation as String) to instances, Classes or Providers.</p>
<p>What happened when calling the<strong> inject()</strong> method inside the Locator?<br />
It looks up for the value stored for the given key.<br />
That can be:</p>
<ul>
<li>An instance, so return it.</li>
<li>A Class, so create an instance of this Class and return it.</li>
<li>A Provider. Create an instance of the Provider and call the getObject() method to get back an instance which is created in a customized way and return this instance.</li>
</ul>
<p>The optional<strong> asSingleton()</strong> call is handling the behavior if the object is cached or not.</p>
<p><strong>So why not use the <a href="http://martinfowler.com/articles/injection.html#ServiceLocatorVsDependencyInjection" target="_blank">Locator pattern</a>?</strong></p>
<p>When using the Locator  pattern you need the instance of the Locator. You can pass the Locator in the constructor to not rely on a static dependency inside your class.<br />
That would be fine, but there is a more elegant way.</p>
<p>You can use a <a href="http://www.ericfeminella.com/blog/2008/05/06/package-level-function-closures-in-actionscript/" target="_blank">package level function</a> (native Flash Functions like getTimer() or trace() are using this technique), so you can call directly the function without reference to the Locator. Inside the function it forwards the call to the package level property which got assigned the reference to the Locator from the setup. The &#8220;dependency&#8221; is only the package in which these 2 files are defined. If you follow a clear architectural structure this results in the positive side effect, that your Locator is used only in the correct scope and protects from cross-scope misuse.</p>
<p>Note that the file name must be the same like the Function or Property names (inject.as, myInjector.as) and only one Function/Property is allowed.<br />
Here are code examples like these 2 files could look like:</p>
<pre>[code lang="actionscript3"]package org.yourDomain.yourProject {
	public function inject(bindingKey:Object):Object {
		return myInjector.inject(bindingKey);
	}
}[/code]</pre>
<pre>[code lang="actionscript3"]package org.yourDomain.yourProject {
	import org.yourDomain.Injector;
	public var myInjector:Injector;
}[/code]</pre>
<p>The myLocator property gets the concrete Locator instance assigned at the setup.</p>
<pre>[code lang="actionscript3"]myLocator = Locator.getLocator("myScope", myContext);[/code]</pre>
<p><span class="hl">Scopes:</span></p>
<p>When having a single project you probably don&#8217;t need to use different scopes, but this becomes important for larger projects. As different projects are normally using different root packages,  the projects root package would be a perfect candidate for the scope key.<br />
When you add the package level property and function file into these packages, you have in every project the access to the right scope of your Locator (need to import them where used).</p>
<p>The <strong>Locator implementation</strong> is pretty straight forward.</p>
<p>It does the management of the scopes as well as the mapping and handling (creation) of the instances when the inject() is called. I used the fluent interface style but you could implement the Binding also with a plain function and parameters.</p>
<p><span class="hl">Some final discussion:</span></p>
<p>So you may ask that <strong>fetching dependencies is not the same like injecting</strong> them, and classes should get the dependencies from outside instead of fetching them from inside.</p>
<p>Yes that is basically true.<br />
But <strong>why it is better</strong> to get it injected?</p>
<p>Because normally to fetch something you need a reference to the container from where you get it. In classical ServiceLocator patterns it is mostly a Singleton.</p>
<pre>[code lang="actionscript3"]ServiceLocator.getInstance().getObject("myObject");[/code]</pre>
<p>Better would be to inject the ServiceLocator in the constructor, so the provider of your dependencies is free configurable and you don&#8217;t need to change your class if you want to use a different implementation of the provider.</p>
<p>It is <span class="hl">not about getting or fetching</span>, it it about to keep the class clean from static dependencies.</p>
<p>With the solution using package level functions it is <strong>less code</strong> needed to be written and has the benefit to implement a <strong>scope mechanism</strong> which can serve as <strong>protection</strong>.</p>
<p>Maybe it depends on the architecture and structure of the project if this approach makes sense. Another solution would be to pass the scope to the Constructor of the Class and lookup for the Locator inside the constructor with the scope key. Or simply pass the already resolved Locator instance typed as Interface to the Constructor.</p>
<p>So using it a bit different, the <strong>good old ServiceLocator mimics the fancy Guice-style Dependency Injection</strong> without really hurting, but saving a lot of performance.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2012/01/31/dependency-injection-without-reflection/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Flex 3 vs. Flex 4</title>
		<link>http://www.screenshot.at/blog/2011/03/31/flex-3-vs-flex-4/</link>
		<comments>http://www.screenshot.at/blog/2011/03/31/flex-3-vs-flex-4/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 20:55:42 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[163]]></category>
		<category><![CDATA[Flex 3]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Viers]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=599</guid>
		<description><![CDATA[Jack Viers has posted a great performance comparision between Flex 3 to Flex 4 components. Unfortunately the Flex 4 components suffer from big performance decrease (163% slower). But just read the article it is very profound discussed there.]]></description>
				<content:encoded><![CDATA[<p><a href="http://jackviers.blogspot.com" target="_blank">Jack Viers</a> has posted a great performance <a href="http://jackviers.blogspot.com/2011/03/flex-3-vs-flex-4a-performance.html" target="_blank">comparision</a> between Flex 3 to Flex 4 components.</p>
<p>Unfortunately the Flex 4 components suffer from big performance decrease (<span class="Apple-style-span" style="font-family: Arial,Helvetica,sans-serif;">163% slower). But just read the article it is very profound discussed there.<br />
</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2011/03/31/flex-3-vs-flex-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unity will support Flash platform</title>
		<link>http://www.screenshot.at/blog/2011/02/28/unity-will-support-flash-platform/</link>
		<comments>http://www.screenshot.at/blog/2011/02/28/unity-will-support-flash-platform/#comments</comments>
		<pubDate>Mon, 28 Feb 2011 16:22:42 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flashplayer]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex Builder]]></category>
		<category><![CDATA[Unity3D]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[3d World]]></category>
		<category><![CDATA[Alternatives To Flash]]></category>
		<category><![CDATA[Animation Tool]]></category>
		<category><![CDATA[Applica]]></category>
		<category><![CDATA[Competitor]]></category>
		<category><![CDATA[Deep Impact]]></category>
		<category><![CDATA[Derivates]]></category>
		<category><![CDATA[Desktop Apps]]></category>
		<category><![CDATA[Development Environment]]></category>
		<category><![CDATA[Flash Player]]></category>
		<category><![CDATA[Flashbuilder]]></category>
		<category><![CDATA[Great News]]></category>
		<category><![CDATA[Inventors]]></category>
		<category><![CDATA[Iphone]]></category>
		<category><![CDATA[Linux Player]]></category>
		<category><![CDATA[Mac Apps]]></category>
		<category><![CDATA[Mac Pc]]></category>
		<category><![CDATA[Pc Desktop]]></category>
		<category><![CDATA[Unity Web]]></category>
		<category><![CDATA[Web Application Development]]></category>
		<category><![CDATA[Web Player]]></category>
		<category><![CDATA[World Flash]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=557</guid>
		<description><![CDATA[Great news!: Unity will support the Flash platform in future! Wow that is really an exciting move! I have had recently a look to Unity in search for alternatives to Flash, and was wondering why they are not supporting the Flash Player. They already supports a lot of different platforms, but Flash was missing. I [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Great news!: <a href="http://blogs.unity3d.com/2011/02/27/unity-flash-3d-on-the-web/comment-page-2/#comment-22481" target="_blank">Unity will support the Flash platform in future!</a><br />
Wow that is really an <span class="hl">exciting move!</span></p>
<p><img class="alignnone size-full wp-image-569" src="http://www.screenshot.at/blog/wp-content/uploads/2011/02/bildschirmfoto-2011-02-28-um-1741381.png" alt="" width="573" height="240" /></p>
<p>I have had recently a look to <a href="http://unity3d.com/unity/" target="_blank">Unity</a> in search for <span class="hl">alternatives to Flash</span>, and was wondering why they are not supporting the Flash Player. They already supports a lot of different platforms, but Flash was missing. I thought the technical limitations and differences would be a too hard barrier.</p>
<p>But now they released the news that they are working on the support for exporting Unity projects to the Flash platform as well as to Android, IPhone (and the rest of the I&#8230; derivates), XBox, Mac/PC desktop apps and their Unity Web Player (Linux Player is in development). It is becoming a real tough multi-platform tool! This could have a deep impact, as Unity seems from technological point of view much more advanced then Flash and the main barrier for using it in the web, was the low player penetration of the Unity Web Player. So it was locked to the special cases where the installation of a new plugin is no problem for users, but unfortunately for 90% of the mainstream clients and projects this is a no go. But with this strategy they will get in one move the support of the 99% penetration of the flash player (ok, with the latest player version that is not correct, but people don´t care so much about an update of the Flash Player then about a new installation of an unknown plugin).<br />
And Adobe is getting a real strong competitor, so hopefully they are forced to pay more attention to performance and development environment. The current Flashbuilder is compared to the tools available for Java or .NET not very competitive, to express it friendly. I have not worked with Unity yet, but will use the next opportunity to try it out.</p>
<p>I am also wondering how much they can cover outside the classical 3D world? Flash has started as a pure animation tool and has become a main player for web application development. I bet the inventors didn´t expect this. So why should not Unity become a tool also for classical applications, 3D comes free if needed, and it seems that <span class="hl">3D</span> will become more and more an <span class="hl">intrinsic part of up to date software</span>. 3D-TV sets and Mobiles are currently the hot thing and I think it´s only a question of (hopefully not too much) time, until 3D displays are common also at desktops. 3D content will be the missing link then.</p>
<p><span class="hl">Unity is just ready to take off!</span></p>
<p>Looking forward also to the new Flash Player (<a href="http://www.adobe.com/newsletters/edge/january2011/articles/article1/" target="_blank">Molehill</a>) which brings GPU-accelerated 3D to the Flash platform.</p>
<p><iframe title="YouTube video player" width="530" height="328" src="http://www.youtube.com/embed/tgwi0lWgX8w?hd=1" frameborder="0" allowfullscreen></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2011/02/28/unity-will-support-flash-platform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Flex Life Cycle</title>
		<link>http://www.screenshot.at/blog/2011/01/20/flex-life-cycle/</link>
		<comments>http://www.screenshot.at/blog/2011/01/20/flex-life-cycle/#comments</comments>
		<pubDate>Thu, 20 Jan 2011 23:41:16 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[Architects]]></category>
		<category><![CDATA[As2]]></category>
		<category><![CDATA[As3]]></category>
		<category><![CDATA[Assumptions]]></category>
		<category><![CDATA[Auto Layout]]></category>
		<category><![CDATA[Bwin]]></category>
		<category><![CDATA[Containers]]></category>
		<category><![CDATA[Developers]]></category>
		<category><![CDATA[Explanations]]></category>
		<category><![CDATA[Flash Player]]></category>
		<category><![CDATA[Life-Cycle]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Performance Bottlenecks]]></category>
		<category><![CDATA[Performance Penalty]]></category>
		<category><![CDATA[Synchronous Code Execution]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=498</guid>
		<description><![CDATA[After working 10 years with Flash and 3 years with Flex I am still not convinced that the Flex Life Cycle is necessary. I discussed this topic already with many developers but nobody could really give me a satisfying answer. So I spread out my thoughts now to the public in the hope to get [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>After working 10 years with Flash and 3 years with Flex I am still not convinced that the <span class="hl">Flex Life Cycle</span> is necessary.</p>
<p>I discussed this topic already with many developers but nobody could really give me a satisfying answer.<br />
So I spread out my thoughts now to the public in the hope to get some valuable feedback.</p>
<p>Of course I am familiar with the concept of the <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=ascomponents_advanced_2.html" target="_blank">Flex Life Cycle</a> and the &#8220;<a href="http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/" target="_blank">elastic racetrack</a>&#8221; behavior of the Flash Player.</p>
<p>The reason why I am not a friend of this concept is because it introduces an <span class="hl">asynchronous code execution</span> where a synchronous code execution would be much easier and faster.</p>
<p>In all my ActionScript based projects it was never necessary to use this pattern and defer code execution to another frame (or Render Event).<br />
At bwin we have built a similar application as the current Flex-based <a href="https://www.bwin.com/de/livebets.aspx" target="_blank">Live Betting application</a> previously in AS2, with a lot of complex components and auto layout containers, without running into any serious problems.<br />
And to be honest the performance of the AS2 project felt somehow the same as the Flex version. But AS3 is about 10 times faster (of course that´s a bit too simple said and we did not measure the difference, but I am not the only one complaining about poor Flex Performance).</p>
<p>So isn´t it valid to <span class="hl">question the concepts Flex is based on?</span></p>
<p>I am sure the architects at Adobe have had good reasons why they decided to introduce this pattern.<br />
In the Docs and Blogosphere one can find several papers about it, but none of these explanations satisfied me, and some are not telling the full truth (that code execution is deferred to another frame).</p>
<p>So I try to discuss <span class="hl">some assumptions</span> for possible reasons:</p>
<ul>
<li>Avoid Performance bottlenecks</li>
<li>Keep the Frame-rendering fluidly</li>
<li>Avoid Performance penalty from unintended repeated method (setter) calls</li>
<li>Pattern for separating different concerns</li>
<li>Problems with reading out the measurements of DisplayObjects before they are rendered on screen</li>
<li>Problems with complex execution flow from auto-layout containers code</li>
</ul>
<p>So let me add my thought to these points:<br />
<strong>Avoid Performance bottlenecks</strong></p>
<p>That was my first assumption when I started with Flex, that this pattern is used to avoid performance bottlenecks. First I thought there is a hidden mechanism for detecting code execution which is running too long and delay this execution to the next frame. After checking out the SDK code I found out that it is simply delaying the 3 phases to 3 &#8220;half-frames&#8221; (Render Events and Enter Frame Events). So if you have really heavy code your player is still freezing up for a certain time and the Life Cycle does not give you any support for solving this problem.</p>
<p>That leads to the next argument:<br />
<strong>Keep the Frame-rendering fluidly</strong></p>
<p>Delaying the render code to the next frame helps the Flash Player running more smoothly and fluidly. That is basically true, but in my opinion 90% of the time the Life Cycle is wasting performance. For me it is a bad trade to get maybe at startup time some more fluidly running pre-loader animation but startup time takes much longer.</p>
<p>Why the Life Cycle is wasting Performance?<br />
Because code which normally would be executed in one frame is now executed over 2 frames (or more).</p>
<p>There is another related issue with performance:<br />
<strong>Avoid Performance penalty from unintended repeated method (setter) calls</strong></p>
<p>Assume that in a large project it could be hard to control the execution flow so that it could happen that setting a text or layout property to a component is not only applied once but unintended multiple times.<br />
For this scenario the Life Cycle helps because the call to the setter of the property is relatively cheap, so if the setter is called 10 times instead of once it will not hurt much. Then at commitProperties the property is only applied once to the component.<br />
Again some weird scenarios with multiple invocations of commitProperties will not hurt much because the applying of the property to the component should be protected by a “changed” flag (see best practice with the Flex Life Cycle).<br />
Also if you need for layout code some measurements the pattern helps to avoid unnecessary and repeated code executions.<br />
BUT &#8211; is poorly written code really the reason why this pattern was introduced? It is true that it gives you some kind of fault tolerance, performance-wise. I guess this argument should not count in professional software development, and in fact it is dangerous because it could hide some deeper problems. If your setters are called more then once, why not look for the reason and clean it up?<br />
I know in complex situations this could be sometimes hard, and under real life circumstances and time pressure you have to deal with something like this. But it should not count as a criteria for such a basic framework design decision.</p>
<p>I made also some measurements to check out the performance penalties for repeatedly called setters:</p>
<p>With 100 000 iterations applying a changing text to a TextField (in a AS3 project) I got these results:</p>
<p>1. Case:<br />
Setting the text property to a variable in a loop and then applying the already stored text to the TextField again in a loop:</p>
<pre>[code lang="actionscript3"]setText(): 119ms
applyStoredText(): 481ms
[/code]</pre>
<p>In contrast to applying the property directly to the TextField:</p>
<pre>[code lang="actionscript3"]
setAndApplyText(): 2879ms
[/code]</pre>
<p>So you can see it is much slower in the 2. Case, so the Life Cycle really helps here, because it only applies the last stored property and not the changing values in between. But again &#8211; setting multiple times unnecessary property values is another problem.</p>
<p>The same test with setting the x position does not deliver such a big difference, in fact it is nearly the same time consumed (40+52 vs. 114)</p>
<pre>[code lang="actionscript3"]setXPos(): 40ms
applyStoredXPos(): 52ms
setAndApplyXPos(): 114ms
[/code]</pre>
<p>Let´s continue with the next point:<br />
<strong>Pattern for separating different concerns</strong></p>
<p>To have a kind of pattern which separates different concerns is basically a cool thing. So you have your code block for setting properties, another method where the properties are applied to the component, a method where the measurement is defined and another one for the layout code.</p>
<p>I have no really argument against this pattern, but I don´t know why it is necessary to defer some code of these phases to the next Frame. The execution of the Life Cycle methods could have been triggered also at the Render Event, then there would not have been any delay to another frame, even it still would add this nasty asynchrony.</p>
<p>So this pattern could make development easier but introduce asynchronous behavior where we lived in a beautiful synchronous Flash world before. In my opinion: Not a good trade.</p>
<p>What else?<br />
<strong>Problems with reading out the measurements of DisplayObjects before they are rendered on screen</strong></p>
<p>Remembering back to some of my Flash projects I have had sometimes strange problems with TextFields and measurement when setting text and using autosize. But I could not reproduce these problems in a test case anymore. So I am not sure if that was caused by some other stuff or maybe by differences in some older Flash Player versions? But at least in my situations these problems could always be solved without deferring code to another Frame. But at this point I am not sure if there are certain use cases where you cannot read out the size of a DisplayObject (TextField) before it is actually rendered to the screen. If there are such cases this would be a valid argument, but then I am wondering why this could not be solved on the Flash Player level instead of solving this problem at a Framework level.</p>
<p>And my last point:<br />
<strong>Problems with complex execution flow from auto-layout containers code</strong></p>
<p>I can imagine that complex situations with nested auto layout containers could be sometimes really tricky to handle. To avoid recursions or unnecessary calls for any possible situation in a generic framework is a tough challenge.</p>
<p>But also in complex situations it is a deterministic behavior, so it should be possible to solve this without the Life Cycle pattern as well. From my experience there was no problems with auto layout containers, but of course in normal project development you have limited use cases and we were not forced to deal with all the possible use cases, like Flex has to do as a generic framework.</p>
<p>So finally I don´t have any idea for the real reason why Adobe has introduced the Life Cycle.<br />
Maybe it seemed that it could help solving a lot of tricky problems (auto layout containers, mixing MXML with AS code,&#8230;) and was considered as a good pattern to make development easier. Maybe the fact that Flash has a strong support for Event driven programming and the Flash developers are already used to handle this asynchrony, led to this decision?<br />
Maybe is was a strategic decision to make Flex easier for new developers without Flash background, who were not familiar with the Flash Players frame-based execution model?</p>
<p>I don´t know. I really would appreciate if someone from the Flex Team could illuminate this topic.</p>
<p>I just have made the experience that many things where much more transparent, cleaner and faster in pure ActionScript then in Flex, and i think the Life Cycle is one of the reasons for that.<br />
I really like the <span class="hl">API of Flex</span> but I am wondering why Adobe don´t give more attention to performance, specially for large scale applications.</p>
<p>Any comments or insights are highly appreciated!</p>
<p>P.S.: Just found an interesting <a href="http://guyinthechair.com/tag/layoutmanager/" target="_blank">post</a> related to this. I 100% agree what Paul Taylor says about UIComponent, but that is another story. Ever heard about <a href="http://reflex.io/" target="_blank">Reflex</a>? Sounds pretty promising!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2011/01/20/flex-life-cycle/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A question of style</title>
		<link>http://www.screenshot.at/blog/2010/01/08/a-question-of-style/</link>
		<comments>http://www.screenshot.at/blog/2010/01/08/a-question-of-style/#comments</comments>
		<pubDate>Fri, 08 Jan 2010 00:03:02 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[Button Color]]></category>
		<category><![CDATA[Button Style]]></category>
		<category><![CDATA[Compiler]]></category>
		<category><![CDATA[Constructor]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[Css Code]]></category>
		<category><![CDATA[Css File]]></category>
		<category><![CDATA[Css Files]]></category>
		<category><![CDATA[CSSStyleDeclaration]]></category>
		<category><![CDATA[Custom Components]]></category>
		<category><![CDATA[Definitions]]></category>
		<category><![CDATA[Developers]]></category>
		<category><![CDATA[External Css]]></category>
		<category><![CDATA[Mx]]></category>
		<category><![CDATA[Mxml]]></category>
		<category><![CDATA[Null]]></category>
		<category><![CDATA[Selectors]]></category>
		<category><![CDATA[Strange Problems]]></category>
		<category><![CDATA[Style]]></category>
		<category><![CDATA[Swf]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=454</guid>
		<description><![CDATA[If you ever had some strange problems with styles in Flex, you might want to know how styles are internally handled and implemented. Ok this post will not cover too much of all the stuff going on there, but a bit of the basics how styles are finding their way from the css file to [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>If you ever had some strange problems with styles in Flex, you might want to know how styles are internally handled and implemented.<br />
Ok this post will not cover too much of all the stuff going on there, but a bit of the basics <span class="hl">how styles are finding their way</span> from the css file to your component.</p>
<p>Lets assume that we have a css file with type selectors and class selectors, a module based application and some custom components which are designed the way that you can use them out of the box and that they can be individually skinned and styled by other developers reusing them. That´s what custom components are for, right?</p>
<p>So the first question is:<br />
<span class="hl">How are the styles compiled into your swf file?</span><br />
Assume that they are defined in an external css file. You know you can compile css files to swf files and load them at runtime or simply compile them into your application at compile time with a simple assignment  like this:</p>
<pre>[code lang="actionscript3"]
<mx:Style source="assets/styles.css"/> 
[/code]</pre>
<p>Here is the content of our simple css:</p>
<pre>[code lang="actionscript3"]
Button
{
	color: #990000;
}
.myCustomStyle1
{
	color: #009900;
}
 /*
     some additional styles here...
     like Button.myCustomStyle2
*/
[/code]</pre>
<p>That´s what we will use for our example here.</p>
<p>In this case the MXML compiler creates a bunch of classes and inserts the css definitions right into a method called from the constructor in the generated Applications class.</p>
<pre>[code lang="actionscript3"]
public function StyleExample() {
	mx_internal::_StyleExample_StylesInit();
}
mx_internal function _StyleExample_StylesInit():void {
	var style:CSSStyleDeclaration;
	// Button
	style = StyleManager.getStyleDeclaration("Button");
	if (!style) {
		style = new CSSStyleDeclaration();
		StyleManager.setStyleDeclaration("Button", style, false);
	}
	if (style.factory == null) {
		style.factory = function():void {
			this.color = 0x990000;
		};
	}
	// myCustomStyle1
	style = StyleManager.getStyleDeclaration(".myCustomStyle1");
	if (!style)
	{
		style = new CSSStyleDeclaration();
		StyleManager.setStyleDeclaration(".myCustomStyle1",
                                           style, false);
	}
	if (style.factory == null)
	{
		style.factory = function():void
		{
			this.color = 0x009900;
		};
	}
	// similar code follows here....
}
[/code]</pre>
<p>I only pasted the relevant code, so this is not complete but should give the basic idea.<br />
So what happens here?<br />
<span id="more-454"></span><br />
A CSSStyleDeclaration is created for the given stylename or class if it´s not already existing in the StyleManager (at a modular application some other application could have already created this style). Then the definitions from the css file (here the color property) are added to the factory function.<br />
It is interesting that the class selectors and type selectors are treated the same way regarding storing the style object in the StyleManager. It is simply the selector name which is used as the key in the _selectors Object (hashtable). Only the &#8220;.&#8221; in the selector name is the visible difference.</p>
<pre>[code lang="actionscript3"]
    public function setStyleDeclaration(
                                selector:String,
                                styleDeclaration:CSSStyleDeclaration,
                                update:Boolean):void
    {
        styleDeclaration.selectorRefCount++;

        _selectors[selector] = styleDeclaration;

        // Flush cache and start over.
        typeSelectorCache = {};

        if (update)
            styleDeclarationsChanged();
    }
[/code]</pre>
<p>The CSSStyleDeclaration has also a defaultFactory which is used if there is no factory defined (no css file). Additionally there is an overrides Object which is used to store styles set at runtime vial setStyle(), but this will not be further considered yet.<br />
This leads us to the next part:<br />
<span class="hl">How should a default style be applied to a custom component?</span></p>
<p>How Flex is handling this? The MXML compiler generates a bunch of style classes:<br />
For instance a style class for the Button:</p>
<pre>[code lang="actionscript3"]
public class _ButtonStyle
{
    public static function init(fbs:IFlexModuleFactory):void
    {
        var style:CSSStyleDeclaration =
                         StyleManager.getStyleDeclaration("Button");
        if (!style)
        {
            style = new CSSStyleDeclaration();
            StyleManager.setStyleDeclaration("Button", style, false);
        }
        if (style.defaultFactory == null)
        {
            style.defaultFactory = function():void
            {
                this.fontWeight = "bold";
                this.paddingTop = 2;
                this.cornerRadius = 4;
                this.textAlign = "center";
                this.verticalGap = 2;
                this.horizontalGap = 2;
                this.skin = mx.skins.halo.ButtonSkin;
                this.paddingLeft = 10;
                this.paddingBottom = 2;
                this.paddingRight = 10;
            };
        }
    }
}
[/code]</pre>
<p>This class is added to the mixins array at the generated _StyleExample_mx_managers_SystemManager class.<br />
The <span class="hl">mixins</span> are a strategy to get injected some code at application startup before anything else is instantiated. It calls the static init method, so it is executed before the actual classes constructor is called.<br />
A similar strategy with a static initializer is used in some classes in the datavisualisation package to pack some default styles into a component, so that there is no dependency that there are some styles assigned to the component from outside.<br />
That´s seems to be a pretty nice way to setup the default style a component needs. If the user of the component wants to set some different styles, it can be applied easily via css, styles set in mxml or at runtime via setStyle (if possible, this should be done in the preInitialize phase to avoid performance penalties).</p>
<p>One thing which should be considered when using styles (specially in a large application with modules) is the fact that the style declarations are stored with the selector name as key in an Object (hashtable). So if 2 developers are using the <span class="hl">same selector name</span> they end up with a conflict that the later instantiated module will use the already created style and not the one which was compiled to the module.<br />
The same applies if you use the same stylename inside one application, the first one used wins.<br />
To get rid of this problem a kind of namespace strategy can be used ([modulename] + &#8220;stylename&#8221;). Unfortunately the Flex framework does not give any support for this problem.<br />
Tell me if you know a more elegant solution!</p>
<div id="gmBFtt" style="border: 1px solid black ! important; margin: 0px ! important; padding: 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; left: 194px ! important; top: 1926px ! important; visibility: visible ! important; display: inline ! important; width: auto; height: auto ! important; position: absolute ! important; text-align: left ! important; z-index: 1410065406 ! important;">
<div style="border-bottom: 1px dotted black ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; padding-bottom: 2px ! important; padding-top: 2px ! important;"><span id="bfconfigButton" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: pointer ! important;" title="Language configuration">Lang</span><span id="bfdetectButton" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: pointer;" title="Detect and set language">Detect</span><span id="bflangsSpan" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: pointer ! important;" title="From English To German (switch direction)">en&gt;de </span><span id="bfsvcSpan" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: pointer ! important;" title="Translation service: Yahoo (switch service)">Yahoo</span><span id="bfclipboardSpan" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: copy ! important;" title="Copy result to clipboard">C</span><img id="bffishImg" style="border: medium none  ! important; margin: 0px ! important; float: none ! important; vertical-align: top ! important; cursor: pointer ! important; display: inline ! important;" title="Click to translate" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAOCAYAAAA8E3wEAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1QUUDyoqJjAqRwAAAN1JREFUOMu1lMkVwyAMBYe0JGpCNUFNVk3k4AUwxPGS+ILxkzX8jyTH/Sfu9nrmJ3cXlnMASyWRPwd2d5XlHCBZn1BthcbRAdxTZQDI8k3mQzg11rhF+QZ9jdNOcQib6GFQYJYgCFucSRf6GsLU6wEY5yubTFqF2yq1vRwr3INXdQUWG+je1pELX4ED1wDyRAR0WfuAA9gloITyvsFMIMgYInYRqF6rO9Sqz9qkO5ilyo0o3YBwJ+6vrdQonxWUQllhXeHcb/wabMPkP2n81ocAIoLZrMqn/4y2RwP8DcQ+d6rT9ATiAAAAAElFTkSuQmCC" alt="" /></div>
<div style="background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; width: auto;">MXML</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2010/01/08/a-question-of-style/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Some nice tools and resources</title>
		<link>http://www.screenshot.at/blog/2009/05/09/some-nice-tools/</link>
		<comments>http://www.screenshot.at/blog/2009/05/09/some-nice-tools/#comments</comments>
		<pubDate>Sat, 09 May 2009 09:07:01 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Compiler]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flashplayer]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex Builder]]></category>
		<category><![CDATA[CSS Inspector]]></category>
		<category><![CDATA[Decompiler]]></category>
		<category><![CDATA[flexformatter]]></category>
		<category><![CDATA[Free Libraries]]></category>
		<category><![CDATA[Hp]]></category>
		<category><![CDATA[Libraries]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Opensource]]></category>
		<category><![CDATA[Security Analysis Tool]]></category>
		<category><![CDATA[Security Issues]]></category>
		<category><![CDATA[Security Tool]]></category>
		<category><![CDATA[swfscan]]></category>
		<category><![CDATA[Wishlist]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=362</guid>
		<description><![CDATA[My wishlist for a CSS inspector has had been already fulfilled: http://code.google.com/p/fxspy A great code formatter as Eclipse plugin for Flex Builder: http://code.google.com/p/flexformatter Download: http://sourceforge.net/projects/flexformatter/ HP has published a security analysis tool for Flash content. It´s also a decompiler to inspect the Actionscript code: SWFScan Good overview about security issues in Flash: http://www.owasp.org/index.php/Category:OWASP_Flash_Security_Project http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps.html A [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>My wishlist for a <a href="http://www.mieuxcoder.com/data/2007/12/FlexSpy-1.2/dashboard.html" target="_blank">CSS inspector</a> has had been already fulfilled: <a href="http://code.google.com/p/fxspy" target="_blank">http://code.google.com/p/fxspy</a></p>
<p>A great code formatter as Eclipse plugin for Flex Builder: <a href="http://code.google.com/p/flexformatter" target="_blank">http://code.google.com/p/flexformatter</a><br />
Download: <a href="http://sourceforge.net/projects/flexformatter/" target="_blank">http://sourceforge.net/projects/flexformatter/</a></p>
<p>HP has published a security analysis tool for Flash content. It´s also a decompiler to inspect the Actionscript code: <a href="https://h30406.www3.hp.com/campaigns/2009/wwcampaign/1-5TUVE/index.php?key=swf&amp;jumpid=go/swfscan" target="_blank">SWFScan</a></p>
<p>Good overview about security issues in Flash:<br />
<a href="http://www.owasp.org/index.php/Category:OWASP_Flash_Security_Project" target="_blank">http://www.owasp.org/index.php/Category:OWASP_Flash_Security_Project</a><br />
<a href="http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps.html" target="_blank">http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps.html</a></p>
<p>A great resource for open source flash/flex tools and projects: <a href="http://www.flashchemist.com/104-free-opensource-apis-libraries-and-tools-for-the-flash-platform.html" target="_blank">http://www.flashchemist.com/104-free-opensource-apis-libraries-and-tools-for-the-flash-platform.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2009/05/09/some-nice-tools/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The infamous callLater()</title>
		<link>http://www.screenshot.at/blog/2009/05/05/the-infamous-calllater/</link>
		<comments>http://www.screenshot.at/blog/2009/05/05/the-infamous-calllater/#comments</comments>
		<pubDate>Tue, 05 May 2009 23:03:24 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flashplayer]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[anatomy of a frame]]></category>
		<category><![CDATA[Asynchronism]]></category>
		<category><![CDATA[AVM2]]></category>
		<category><![CDATA[CallLater]]></category>
		<category><![CDATA[Half-Fram]]></category>
		<category><![CDATA[Layout Engine]]></category>
		<category><![CDATA[Layout Mechanism]]></category>
		<category><![CDATA[Life-Cycle]]></category>
		<category><![CDATA[Marshalled Slice]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Phased Instantiation]]></category>
		<category><![CDATA[player events]]></category>
		<category><![CDATA[player render]]></category>
		<category><![CDATA[prerender event]]></category>
		<category><![CDATA[Render]]></category>
		<category><![CDATA[Sean Christmann]]></category>
		<category><![CDATA[UsePhasedInstantiation]]></category>
		<category><![CDATA[user code]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=298</guid>
		<description><![CDATA[At my first posts I wrote about my favorite Flex feature: Databinding Now I will take a look at the opposite, IMHO the most precarious &#8220;feature&#8221; in Flex: callLater() If you have a dodgy problem that a certain property is not available when it already should be and you ask someone at flexcoders you often [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>At my first posts I wrote about my favorite Flex feature: Databinding<br />
Now I will take a look at the opposite, IMHO the most precarious &#8220;feature&#8221; in Flex: <span class="hl">callLater()</span></p>
<p>If you have a dodgy problem that a certain property is not available when it already should be and you ask someone at <a href="http://tech.groups.yahoo.com/group/flexcoders/" target="_blank">flexcoders</a> you often get the advice, <em>&#8220;try callLater&#8221;</em> for a quick work-around. Sometimes this helps, but it leaves a bad smell, because often it´s just hiding some other problems in the code.<br />
So when we worked on a large-scale Flex application we have used it sometimes in the beginning, but after a while we decided to avoid callLater. To find and solve the real problem is simply the better solution &#8211; and we never needed it again &#8211; there was always another solution to solve a particular problem (maybe we just have had luck).</p>
<p>Unpleasantly we get confronted with the fact that callLater is used inside the Framework at the <strong>heart of the layout engine</strong>.<br />
We struggled with some strange problems. For instance we got a NullPointer exception in the updateDisplayList method of a custom component, which has already been cleaned up properly and removed from the displayList. It turned out that the layout mechanism delayed with callLater an invocation of updateDisplayList but our stuff there has already been removed and threw an exception.<br />
It was not hard to fix, but it demonstrated us that some asynchronous stuff was going on behind the scenes which was out of our direct control.</p>
<p>So for me callLater leaves always a certain bad smell.</p>
<p>Unfortunately I never found time to really investigate how it´s implemented and what are the concepts behind it.<br />
So it was time to <span class="hl">catch up</span> with this issue:<br />
CallLater is basically a method in UIComponent which delays a passed function to the next <strong>EnterFrame OR Render</strong> event.<br />
Often in den docs it´s just described that it will delay to the next frame, which is not correct because it could be that your function is executed already at the Render Event, which happens in the same frame and is the last opportunity where User code can be executed before the screen is rendered.</p>
<p>For more details about the internal concept of a frame in Flash and the relevant events see the great article by <a href="http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/" target="_blank">Sean Christmann</a>:</p>
<p>Here is a good illustration from his article about the <strong>anatomy of a frame</strong> in Flash:<br />
<span id="more-298"></span><br />
<img class="alignnone size-full wp-image-308" title="marshalledsliceexport" src="http://www.screenshot.at/blog/wp-content/uploads/2009/05/marshalledsliceexport.png" alt="marshalledsliceexport" width="500" height="220" /></p>
<p>All functions passed to callLater are queued up in an array and are executed at the EnterFrame event or Render event. It is possible that the executed function has some other callLater invocations again, so the final execution sequence could be delayed over several frames.</p>
<p>CallLater is used inside the Flex Framework in several classes. The main use case is probably inside the <strong>LayoutManager</strong>.<br />
There is a concept called <strong>phased instantiation</strong> which means basically that at application start-up the 3 phases in the UIComponents life-cycle (validate properties, validate size and validate displayList) are not executed in one pass, but are delayed with callLater to 3 half-frames. <strong>Half-frame</strong> because the Render event happens in the same frame as the EnterFrame event.<br />
This should reduce performance peaks at application-startup and should increase the UIs responsiveness.<br />
You can also use it later on in your application if you have to render heavy stuff, to balance the load across frames.</p>
<p><span class="hl">So far so good. But&#8230;</span><br />
First let me emphasis that I am sure that the SDK architects has had some good reasons for implementing callLater, but it <strong>introduces an asynchronism</strong> which could be hard to control. Normally with async stuff you have an event driven approach, so you get informed when the async task is done.<br />
With callLater it´s not so clear when the last callLater is really finished. There is an UpdateComplete event in UIComponent and LayoutManager which helps to get informed when the last callLater is executed, but in-between, you don´t have control about the distinct moments of your function calls.</p>
<p>Another issue is that you cannot control if your heavy load is really spread over 2 frames. It could be that it is just executed inside one frame at the EnterFrame event and at the Render event, so it could be that you don´t win anything from the load-balancing perspective.</p>
<p>Performance-wise there could also be perceptible delays caused by repeatedly callLater executions.</p>
<p>I guess there are many special situations in the framework code (probably mostly measurement stuff) which are difficult to handle, but i guess it <em>should</em> be possible (maybe I am too optimistic?).</p>
<p>There seems to be a problem to get the correct measurement when you set a new text in a TextField before the frame is actually rendered (see <a href="http://tech.groups.yahoo.com/group/flexcoders/message/121060" target="_blank"> this post</a> at flexcoders), but if this is an unsolvable problem then it should be urgently fixed in the Flash Player.</p>
<p>References@livedocs:<br />
<a href="http://livedocs.adobe.com/flex/3/langref/mx/core/UIComponent.html#callLater()" target="_blank">callLater()</a><br />
<a href="http://livedocs.adobe.com/flex/3/langref/mx/managers/LayoutManager.html#usePhasedInstantiation" target="_blank">usePhasedInstantiation</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2009/05/05/the-infamous-calllater/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Wishlist: CSS Inspector/Live-Editor for Flex</title>
		<link>http://www.screenshot.at/blog/2009/04/28/wishlist-css-inspectorlive-editor-for-flex/</link>
		<comments>http://www.screenshot.at/blog/2009/04/28/wishlist-css-inspectorlive-editor-for-flex/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 20:11:54 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Flex Builder]]></category>
		<category><![CDATA[Adobe Bugbase]]></category>
		<category><![CDATA[Css Editor]]></category>
		<category><![CDATA[CSS Tools]]></category>
		<category><![CDATA[Custom Components]]></category>
		<category><![CDATA[Different Styles]]></category>
		<category><![CDATA[Download Adobe]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Element]]></category>
		<category><![CDATA[Flex Components]]></category>
		<category><![CDATA[Flex Style Exlorer]]></category>
		<category><![CDATA[Love]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Stuff]]></category>
		<category><![CDATA[Vote]]></category>
		<category><![CDATA[Web Developer]]></category>
		<category><![CDATA[Web Developers]]></category>
		<category><![CDATA[Wishlist]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=271</guid>
		<description><![CDATA[At styling and changing my blog theme, i really fall in love with Web Developers (Firefox addon) CSS tools. Just rollover or select an element and see the css used. Edit it live and see immediately the changes. How nice would it be to have something inside Flex Builder? For re-styling or adopting Flex projects [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>At styling and changing my blog theme, i really fall in love with Web Developers (<a href="https://addons.mozilla.org/de/firefox/addon/60" target="_blank">Firefox addon</a>) CSS tools.<br />
Just rollover or select an element and see the css used. Edit it live and see immediately the changes.<br />
How nice would it be to have something inside Flex Builder?<br />
For re-styling or adopting Flex projects this would be a great helper-tool, specially if you edit custom components from other developers.</p>
<p>If you feel this would be a nice feature, <a href="https://bugs.adobe.com/jira/browse/FB-19065" target="_blank">vote</a> for it on the <a href="https://bugs.adobe.com/jira/browse/FB-19065" target="_blank">Adobe Bugbase</a>.</p>
<p>You probably have seen already the <a href="http://examples.adobe.com/flex3/consulting/styleexplorer/Flex3StyleExplorer.html" target="_blank">Flex Style Explorer</a>. It gives a good overview of the different styles of the standard Flex components.</p>
<p>BTW: Did you know that parts of Flex Builder are open source (the derived stuff from Eclipse)? You can download it at <a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=4b243413&amp;sliceId=1 " target="_blank">Adobe</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2009/04/28/wishlist-css-inspectorlive-editor-for-flex/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>DataBinding under the hood (part 3): Generated Code</title>
		<link>http://www.screenshot.at/blog/2009/04/26/databinding-under-the-hood-part3-generated-code/</link>
		<comments>http://www.screenshot.at/blog/2009/04/26/databinding-under-the-hood-part3-generated-code/#comments</comments>
		<pubDate>Sun, 26 Apr 2009 00:28:40 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[compiler settings]]></category>
		<category><![CDATA[DataBinding]]></category>
		<category><![CDATA[Flex Compiler]]></category>
		<category><![CDATA[Generated Code]]></category>
		<category><![CDATA[Mixin Classes]]></category>
		<category><![CDATA[Mxml]]></category>
		<category><![CDATA[Precompiler]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=230</guid>
		<description><![CDATA[So now lets get our hands dirty and check out the generated code which is created behind the scenes. When you compile a Flex application the compiler runs the compilation in 2 steps: The mxmlc compiler generates a lot of Actionscript classes The compc compiler compiles from the generated classes plus your custom classes the [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>So now lets get our hands dirty and check out the <span class="hl">generated code</span> which is created behind the scenes.</p>
<p>When you compile a Flex application the compiler runs the compilation in 2 steps:</p>
<ul>
<li>The mxmlc compiler generates a lot of Actionscript classes</li>
<li>The compc compiler compiles from the generated classes plus your custom classes the swf file</li>
</ul>
<p>These 2 steps are normally not visible, because the generated code is not stored in your project. If you add the compiler argument <em>-keep</em> (or <em>-keep-generated-actionscript=true</em>) in your compiler settings in Flex Builder, you will see a <em>generated</em> folder inside the src folder containing a lot of Actionscript files.</p>
<p>There are different kinds of files generated:</p>
<ul>
<li>Classes defining the default style for Flex components</li>
<li>Classes holding the Resourcebundle properties</li>
<li>Classes for embedded skins</li>
<li>Classes for Flex Application setup</li>
<li>Classes for Flex DataBinding</li>
</ul>
<p>The style, skin and property files are out of our scope here and has no direct relation to this topic.<br />
The classes which are used for setting up a Flex Application are our entry point, but will not be discussed in detail (even it would be very interesting to have a closer look to Mixins, [Frame] metadata tags and all these exotic stuff&#8230;).</p>
<p>So lets look at our <strong>relevant classes</strong> for DataBinding (all others has been removed):</p>
<p><img class="alignnone size-full wp-image-238" title="generated3" src="http://www.screenshot.at/blog/wp-content/uploads/2009/04/generated.gif" alt="generated" width="342" height="190" /><br />
<span id="more-230"></span><br />
The entry-point of our Flex application is <span class="hl">_DBGC_mx_managers_SystemManager</span>.<br />
This class extends SystemManager. The SystemManager is the main class and the first DisplayObject added to the stage. It does a lot of setup stuff.<br />
At the first frame in our MovieClip the preloading is handled. At the second frame the Application (DBGC) is instantiated. In the static info() method the mixins classes are defined. At frame 2 the mixin classes are inited via the static method call init().</p>
<p>The <span class="hl">DBCG</span> class (file: DBCG-generated.as) is our Application class.<br />
Here the MXML components are converted to UIComponentDescriptors which handles the instantiation of these Components.<br />
At initialize() an array of Binding objects are created.<br />
The Binding class use anonymous functions for resolving the source and destination properties.</p>
<pre>[code lang="actionscript3"]
var binding:Binding = new mx.binding.Binding(this,
    function():String
    {
        var result:* = (bindableVO.myBindableProp);
        var stringResult:String = (result == undefined ? null : String(result));
        return stringResult;
    },
    function(_sourceFunctionReturnValue:String):void
    {

        myLabel.text = _sourceFunctionReturnValue;
    },
    "myLabel.text");
[/code]</pre>
<p>The <span class="hl">_DBGCWatcherSetupUtil</span> creates an array of PropertyWatcher objects, setup the relationship for chains and pass the Binding object to the PropertyWatcher.</p>
<pre>[code lang="actionscript3"]
watchers[0] = new mx.binding.PropertyWatcher("bindableVO",
    { propertyChange: true },[ bindings[0] ], propertyGetter);
watchers[1] = new mx.binding.PropertyWatcher("myBindableProp",
    { propertyChange: true },[ bindings[0] ], null);
watchers[0].updateParent(target);
watchers[0].addChild(watchers[1]);
[/code]</pre>
<p>After the basic setup execute() is called on every Binding object.<br />
Here is the complete code:</p>
<pre>[code lang="actionscript3"]
override public function initialize():void
{
 	mx_internal::setDocumentDescriptor(_documentDescriptor_);

	var bindings:Array = _DBGC_bindingsSetup();
	var watchers:Array = [];

	var target:DBGC = this;

	if (_watcherSetupUtil == null)
	{
		var watcherSetupUtilClass:Object = getDefinitionByName("_DBGCWatcherSetupUtil");
		watcherSetupUtilClass["init"](null);
	}

	_watcherSetupUtil.setup(this,
				function(propertyName:String):* {
                                     return target[propertyName];
                                },
				bindings,
				watchers);

	for (var i:uint = 0; i &lt; bindings.length; i++)
	{
		Binding(bindings[i]).execute();
	}

	mx_internal::_bindings = mx_internal::_bindings.concat(bindings);
	mx_internal::_watchers = mx_internal::_watchers.concat(watchers);

	super.initialize();
}

private function _DBGC_bindingsSetup():Array
{
    var result:Array = [];
    var binding:Binding;

    binding = new mx.binding.Binding(this,
        function():String
        {
            var result:* = (bindableVO.myBindableProp);
            var stringResult:String = (result == undefined ? null : String(result));
            return stringResult;
        },
        function(_sourceFunctionReturnValue:String):void
        {

            myLabel.text = _sourceFunctionReturnValue;
        },
        "myLabel.text");
    result[0] = binding;

    return result;
}
[/code]</pre>
<p>So lets jump into the <span class="hl">Binding</span> Class. This is a regular Framework class.<br />
The execute() method is basically applying the source value to the destination. In-between there is a lot of error handling going on, but basically it´s nothing else as reading out a value and setting it to the destination. No event dispatching is included until now.</p>
<p>The setting of the value happens on start-up. If the bindable property changes later, event dispatching comes in.<br />
This happens in the <span class="hl">PropertyWatcher</span> class:<br />
An event handler is added at the source object and the PropertyWatcher is listening for the defined event type. It is invoked with weak reference, so the fact that MXML Bindings cannot be removed will not lead to memory leaks.<br />
The event handler checks if the dispatched PropertyChangeEvent contains the same property name as our PropertyWatcher represents and calls notifyListeners() if the property name matches.<br />
On every Binding object which is registered as listener watcherFired() is called.<br />
And here again the execute() method is responsible for passing the value from the source over to the destination.</p>
<p>The last missing link is the class which dispatch the PropertyChangeEvent.<br />
The <span class="hl">BindableProperty</span> (file: _BindablePropertyVO-binding-generated.as) is the place where this happens.</p>
<pre>[code lang="actionscript3"]
[Bindable(event="propertyChange")]
public function get myBindableProp():String
{
    return this._834029286myBindableProp;
}

public function set myBindableProp(value:String):void
{
    var oldValue:Object = this._834029286myBindableProp;
    if (oldValue !== value)
    {
        this._834029286myBindableProp = value;
        this.dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this,
                                  "myBindableProp", oldValue, value));
    }
}
[/code]</pre>
<p>Here the gettter/setters are created for our [Bindable] property. The compiler defines &#8220;propertyChange&#8221; as event type &#8211; [Bindable(event=&#8221;propertyChange&#8221;)] and dispatches a PropertyChangeEvent if the value has changed.<br />
If the class containing the bindable property is not a subclass of EventDispatcher the compiler set the classes interface of BindableProperty to IEventDispatcher, adds the methods of IEventDispatcher and uses an instance of EventDispatcher via composition.</p>
<p>Note that this code is only generated when you don´t use custom events in the [Bindable] metadata tag ([Bindable(event=&#8221;myCustonEvent&#8221;)]).</p>
<p>I don´t know how this class is linked into the Application, it has no reference anywhere. I guess the compiler do this job behind the scenes, as well as with the interface classes and some other stuff.</p>
<p>Lets have a look to the <span class="hl">moments when DataBinding is executed:</span></p>
<p>At <strong>Application start-up</strong> the Binding is executed  for the first time.<br />
Here is the call stack (Breakpoint at Binding.execute():</p>
<p><img class="alignnone size-full wp-image-248" title="dbseq1" src="http://www.screenshot.at/blog/wp-content/uploads/2009/04/dbseq1.gif" alt="dbseq1" width="613" height="188" /></p>
<p>Due the fact that the component is not created yet, the Binding fails in a catch Block at wrapFunctionCall() in the Binding class. The catch block is pretty slow, i am wondering why this initial execute() is not prevented? At least the try/catch could be replaced with a check against null  which is much faster then falling into the catch block. I guess in large applications this could noticeable slow down start-up time.</p>
<p>At the time the <strong>component is added to the Application</strong> executeBinding() is called and triggers the second execute().</p>
<p><img class="alignnone size-full wp-image-249" title="dbseq2" src="http://www.screenshot.at/blog/wp-content/uploads/2009/04/dbseq2.gif" alt="dbseq2" width="613" height="321" /></p>
<p>At this point the component is valid but there is only the value passed which is defined in the property declaration. This value is often not set at this momens so it is null.</p>
<p>If you setup your initial value at the <strong>initialize</strong> event a third run will be triggered:</p>
<p><img class="alignnone size-full wp-image-250" title="dbseq3" src="http://www.screenshot.at/blog/wp-content/uploads/2009/04/dbseq3.gif" alt="dbseq3" width="590" height="494" /></p>
<p>You can prevent this if you set the value right at the variable declaration (if possible) and so prevent to trigger DataBindings third round.</p>
<p><span class="hl">Conclusion</span><br />
Finally we are through the basic parts how DataBinding is working behind the scenes. To go further it´s best to step through the generated code and try out different scenarios.<br />
We only have had a look into Binding in MXML. If you use BindingUtils just the code for event dispatching from the [Bindable] metadata tag is created.</p>
<p>The generated code for DataBinding with MXML do a lot of error handling. it´s clear that it has some performance drawbacks but gives the benefit that it is very fault-tolerant. You also should consider that there are a lot of different features and use cases for Binding (functions, expressions, 2-way Bindings,&#8230;) which has to be handled.</p>
<p>For large applications BindingUtils are the better choice and prevents several performance drawbacks, specially at start-up time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2009/04/26/databinding-under-the-hood-part3-generated-code/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
