SlideShare a Scribd company logo
Diving in the  Data Binding Waters Michael Labriola Digital Primates
Who are you? Michael Labriola Senior Consultant at Digital Primates Flex Geek Component Developer Flex Team Mentor
Who were you? Michael Labriola Software Engineer Embedded Systems Developer Reverse Engineer
What is this session about? This session is part of my continuing quest to teach Flex from the inside out. Learn what the Flex framework is really doing and you are more likely to use it successfully, respect its boundaries and extend it in useful ways
One more reason Let’s call it “Game Theory”. If you know how something works really well, you know which rules you can bend and just how far you can bend them before they break.  Sometimes you can even find really creative ways out of difficult situations
Standard Disclaimer I am going to lie to you a lot… a whole lot Even at this ridiculous level of detail, there is much more All of this is conditional. So, we are just going to take one route and go with it
Data Binding Defined Data Binding is the magical process by which changes in a data model are instantly propagated to views.
Now Really Defined Data Binding is not magic It is a relatively complicated combination of generated code, event listeners and handlers, error catching and use of meta data through object introspection
Still on the Soap Box Data Binding works because Flex (which I am generically using here to mean precompiler, compiler and framework) generates a lot of code on your behalf.
Transformation When you use Data Binding, the Flex compiler generates code for you.. A lot of code So, the following example becomes.. package valueObject { [Bindable] public class Product { public var productName:String; } }
Generated Code p ackage valueObject { import flash.events.IEventDispatcher; public class ProductManualBinding implements IEventDispatcher {   private var dispatcher:flash.events.EventDispatcher = new flash.events.EventDispatcher(flash.events.IEventDispatcher(this));   [Bindable(event="propertyChange")]   public function get productName():String {   return _productName;   }   public function set productName(value:String):void {   var oldValue:Object = _productName;   if (oldValue !== value) {   _productName = value;   dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this, "productName", oldValue, value));   }   }   public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, weakRef:Boolean = false):void {   dispatcher.addEventListener(type, listener, useCapture,   priority, weakRef);   }   public function dispatchEvent(event:flash.events.Event):Boolean {   return dispatcher.dispatchEvent(event);   }   public function hasEventListener(type:String):Boolean {   return dispatcher.hasEventListener(type);   }   public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void {   dispatcher.removeEventListener(type, listener, useCapture);   }   public function willTrigger(type:String):Boolean {   return dispatcher.willTrigger(type);   } } }
Most Importantly public class ProductManualBinding implements IEventDispatcher {   private var dispatcher:EventDispatcher = new  EventDispatcher(IEventDispatcher(this));   [Bindable(event="propertyChange")]   public function get productName():String {   return _productName;   }   public function set productName(value:String):void {   var oldValue:Object = _productName;   if (oldValue !== value) {   _productName = value;   dispatchEvent(PropertyChangeEvent.createUpdateEvent(this,  "productName", oldValue, value));   }   }
Only Half of the Equation Data Binding is about changing a model and having the view react So, the generated code for the following view becomes… [Bindable] private var product:Product; <mx:Label id=&quot;myLbl&quot; text=&quot;{product.productName}&quot;/>
The Other 7/8 override public function initialize():void { var bindings:Array = []; var binding:Binding; binding = new mx.binding.Binding(this, function():String { var result:* = (product.productName); var stringResult:String = (result == undefined ? null : String(result)); return stringResult; }, function(_sourceFunctionReturnValue:String):void { myLabel.text = _sourceFunctionReturnValue; }, &quot;myLabel.text&quot;); bindings[0] = binding; var watchers:Array = []; watchers[0] = new mx.binding.PropertyWatcher(&quot;product&quot;,{propertyChange: true},[ bindings[0] ], function(propertyName:String):* { return target[propertyName]; } ); watchers[1] = new mx.binding.PropertyWatcher(&quot;productName&quot;,{productNameChanged: true}, [bindings[0]],null); watchers[0].updateParent(target); watchers[0].addChild(watchers[1]); for (var i:uint = 0; i < 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(); }
Starting at the Top The generated code overrides the initialization function to add all of the generated code into startup The first relevant thing it does for us it to create an Array of mx.binding.Binding objects. These objects are responsible for executing bindings.. (moving values from the binding source to the destination.)
mx.binding.Binding Instances of this class accept a  document, srcFunc, destFunc and destString as parameters. The document is the target of the work. The srcFunc returns the value used in the binding. The destFunc assigns it to the destination. The destString is the destination represented as a String… more on that later
Binding in our Example var bindings:Array = []; var binding:Binding; binding = new mx.binding.Binding(this, function():String { var result:* = (product.productName); var stringResult:String = (result == undefined ? null : String(result)); return stringResult; }, function(_sourceFunctionReturnValue:String):void { myLabl.text = _sourceFunctionReturnValue; }, “ myLbl.text&quot;); bindings[0] = binding;
Watchers Still in the initialize method, the generated code creates an array of mx.binding.PropertyWatcher objects The objects are responsible for noticing a change and, among other things, notifying the binding objects that they should execute
mx.binding.PropertyWatcher Instances of this class accept the propertyName, an object that indicates which events are broadcast when the property has changed, an array of listeners and a propertyGetter function The listeners are any Binding instances created for the property. In this case, the property getter is an anonymous function that returns the value of the property binding.
Watchers in our Example watchers[0] = new mx.binding.PropertyWatcher(&quot;product&quot;, {propertyChange: true},[ bindings[0] ],  propertyGetter ); watchers[1] = new mx.binding.PropertyWatcher(&quot;productName&quot;, {productNameChanged: true}, [bindings[0]],null); watchers[0].updateParent(target); watchers[0].addChild(watchers[1]);
Chains Data Binding Expressions are rarely simple names of properties. They are often chains.  For example: <mx:Text id=&quot;myText&quot; text=&quot;{user.name.firstName.text}&quot;/>
Execution After the watchers are setup, the generated initialize function loops through all of the Binding objects and calls their execute() method. This method cautiously attempts to set the destination value to the source value, first ensuring that we aren’t already in process or an in an infinite loop.
Value Changed One important thing to note about this process which often trips up new users to databinding: A value on an object is only set if it is differnet (oldValue !== value) What impact does this have on Objects? Arrays?
Ways to Bind This explains how binding is setup if the bindings are declared in MXML. There are ways to handle binding in ActionScript: mx.binding.utils.BindingUtils mx.binding.utils.ChangeWatcher. Manually adding event listeners
The differences You cannot:  include ActionScript code in a data binding expression defined in ActionScript. include an E4X expression in a data binding expression defined in ActionScript.  include functions or array elements in property chains in a data binding expression defined this way
Also MXML provides better warning and error detection than any of the runtime methods
BindingUtils BindingUtils provides two methods which do this work for you at runtime bindProperty and bindSetter The first one is used with public properties. The second is used with getter/setters.
bindProperty Syntax public static function bindProperty(site:Object, prop:String, host:Object, chain:Object, commitOnly:Boolean = false):ChangeWatcher For example: public function setup():void { BindingUtils.bindProperty(someOtherTextFiled, “text”, someTextInput, &quot;text&quot;); }
bindSetter Syntax public static function bindSetter(setter:Function, host:Object, chain:Object, commitOnly:Boolean = false):ChangeWatcher For example: public function updateIt(val:String):void { someOtherTextFiled.text = val.toUpperCase(); } public function setup():void { BindingUtils.bindSetter(updateIt, someTextInput,  &quot;text&quot;); }
The Chain The chain is a rather complex parameter that can take on multiple forms… for instance, it can be a: String containing the name of a public bindable property of the host object.  An Object in the form: { name: property name, getter: function(host) { return host[property name] } }.  A non-empty Array containing a combination of the first two options that represents a chain of bindable properties accessible from the host. For example, to bind the  property host.a.b.c, call the method as:  bindProperty(host, [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;], ...).
ChangeWatcher public function setup():void { ChangeWatcher.watch(textarea, &quot;text&quot;,  watchMeAndReact); } public function watchMeAndReact(event:Event):void{ myTA1.text=&quot;done&quot;; } You can also unwatch() something..
Manual Event Listeners You could, but… The data binding code swallows a bunch of errors on your behalf, to handle things like null values, etc… your code will crash if you don’t take the same care
What does this mean? Binding is just a contract between two objects.  One object explains that it will broadcast an event when it changes and details what event that will be Another object waits for that event to occur and updates the destination when it occurs
propertyChange Even though the propertyChange is the default event that Flex uses when you auto-generate binding code, you can change it if you use your own getters and setters. For example:
Not propertyChange private var _productName:String; [Bindable(event='myProductNameChanged')] public function get productName():String { return _productName; } public function set productName( value:String ):void { _productName = value; dispatchEvent( new Event('myProductNameChanged') ); }
Not getter/Setter You will need to broadcast this event somewhere else. [Bindable(event='myProductNameChanged')] public var productName:String;
Double Down private var _productName:String; [Bindable(event='serverDataChanged')] [Bindable(event='myProductNameChanged')] public function get productName():String { return _productName; } public function set productName( value:String ):void { _productName = value; dispatchEvent( new Event('myProductNameChanged') ); }
Models, Oh Models The propertyChange event is broadcast by default for every property setter that is auto-generated How do you think that scales in a giant application model? What happens?
Binding to Unbindable Putting some of this to use
Lazy Load Putting some of this to use
Random Closing Tips Any users of describeType out there…. Make sure you use the DescribeTypeCache var info:BindabilityInfo = DescribeTypeCache.describeType(parentObj). bindabilityInfo;
Q & A Seriously? You must have some questions by now?
Resources Blog Aggregator (All of the Digital Primates) http://blogs.digitalprimates.net/ My Blog Specifically http://blogs.digitalprimates.net/codeSlinger/
Ad

More Related Content

What's hot (16)

09 Application Design
09 Application Design09 Application Design
09 Application Design
Ranjan Kumar
 
Web technology javascript
Web technology   javascriptWeb technology   javascript
Web technology javascript
Uma mohan
 
MVC 2.0 - A Breakthrough
MVC 2.0 - A BreakthroughMVC 2.0 - A Breakthrough
MVC 2.0 - A Breakthrough
Constantin Dumitrescu
 
9 services
9 services9 services
9 services
Ajayvorar
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
laxmi.katkar
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
tutorialsruby
 
AJAX
AJAXAJAX
AJAX
Gouthaman V
 
JDBC (JAVA Database Connectivity)
JDBC (JAVA Database Connectivity)JDBC (JAVA Database Connectivity)
JDBC (JAVA Database Connectivity)
HimanshiSingh71
 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
Boulos Dib
 
Ajax-Tutorial
Ajax-TutorialAjax-Tutorial
Ajax-Tutorial
tutorialsruby
 
Open sourcing the store
Open sourcing the storeOpen sourcing the store
Open sourcing the store
Mike Nakhimovich
 
Sword fighting with Dagger GDG-NYC Jan 2016
 Sword fighting with Dagger GDG-NYC Jan 2016 Sword fighting with Dagger GDG-NYC Jan 2016
Sword fighting with Dagger GDG-NYC Jan 2016
Mike Nakhimovich
 
Android networking in Hindi
Android networking in Hindi Android networking in Hindi
Android networking in Hindi
Vipin sharma
 
Metaworks3
Metaworks3Metaworks3
Metaworks3
uEngine Solutions
 
Data binding w Androidzie
Data binding w AndroidzieData binding w Androidzie
Data binding w Androidzie
The Software House
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出第一次用Parse就深入淺出
第一次用Parse就深入淺出
Ymow Wu
 
09 Application Design
09 Application Design09 Application Design
09 Application Design
Ranjan Kumar
 
Web technology javascript
Web technology   javascriptWeb technology   javascript
Web technology javascript
Uma mohan
 
JDBC (JAVA Database Connectivity)
JDBC (JAVA Database Connectivity)JDBC (JAVA Database Connectivity)
JDBC (JAVA Database Connectivity)
HimanshiSingh71
 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
Boulos Dib
 
Sword fighting with Dagger GDG-NYC Jan 2016
 Sword fighting with Dagger GDG-NYC Jan 2016 Sword fighting with Dagger GDG-NYC Jan 2016
Sword fighting with Dagger GDG-NYC Jan 2016
Mike Nakhimovich
 
Android networking in Hindi
Android networking in Hindi Android networking in Hindi
Android networking in Hindi
Vipin sharma
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出第一次用Parse就深入淺出
第一次用Parse就深入淺出
Ymow Wu
 

Similar to Diving in the Flex Data Binding Waters (20)

Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Barry Gervin
 
Flex3 Deep Dive Final
Flex3 Deep Dive FinalFlex3 Deep Dive Final
Flex3 Deep Dive Final
RJ Owen
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Knoldus Inc.
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0
PhilWinstanley
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
kaven yan
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
Krzysztof Szafranek
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
Ciklum Ukraine
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
Anand Kumar Rajana
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Subramanyan Murali
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
Naresh Jain
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
PSTechSerbia
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
Sergey Bolshchikov
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilder
Andres Almiray
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
Ali Parmaksiz
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
Vadym Khondar
 
Flex Building User Interface Components
Flex Building User Interface ComponentsFlex Building User Interface Components
Flex Building User Interface Components
Ahmad Hamid
 
Android workshop
Android workshopAndroid workshop
Android workshop
Michael Galpin
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Barry Gervin
 
Flex3 Deep Dive Final
Flex3 Deep Dive FinalFlex3 Deep Dive Final
Flex3 Deep Dive Final
RJ Owen
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0
PhilWinstanley
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
kaven yan
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
CiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
Ciklum Ukraine
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
Naresh Jain
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
PSTechSerbia
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilder
Andres Almiray
 
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
Ali Parmaksiz
 
Reactive programming every day
Reactive programming every dayReactive programming every day
Reactive programming every day
Vadym Khondar
 
Flex Building User Interface Components
Flex Building User Interface ComponentsFlex Building User Interface Components
Flex Building User Interface Components
Ahmad Hamid
 
Ad

More from michael.labriola (19)

Optimizing Browser Rendering
Optimizing Browser RenderingOptimizing Browser Rendering
Optimizing Browser Rendering
michael.labriola
 
Randori design goals and justification
Randori design goals and justificationRandori design goals and justification
Randori design goals and justification
michael.labriola
 
L2624 labriola
L2624 labriolaL2624 labriola
L2624 labriola
michael.labriola
 
Talking trash
Talking trashTalking trash
Talking trash
michael.labriola
 
Flex 4 components from the firehose
Flex 4 components from the firehoseFlex 4 components from the firehose
Flex 4 components from the firehose
michael.labriola
 
Developing for a world wide audience
Developing for a world wide audienceDeveloping for a world wide audience
Developing for a world wide audience
michael.labriola
 
Developing for a world wide audience
Developing for a world wide audienceDeveloping for a world wide audience
Developing for a world wide audience
michael.labriola
 
FlexUnit 4 for contributors
FlexUnit 4 for contributorsFlexUnit 4 for contributors
FlexUnit 4 for contributors
michael.labriola
 
Write once... Take Less Time to Deploy
Write once... Take Less Time to Deploy Write once... Take Less Time to Deploy
Write once... Take Less Time to Deploy
michael.labriola
 
Why test with flex unit
Why test with flex unitWhy test with flex unit
Why test with flex unit
michael.labriola
 
Apocalypse Soon
Apocalypse SoonApocalypse Soon
Apocalypse Soon
michael.labriola
 
Flex 4 Component Development
Flex 4 Component DevelopmentFlex 4 Component Development
Flex 4 Component Development
michael.labriola
 
Any Which Array But Loose
Any Which Array But LooseAny Which Array But Loose
Any Which Array But Loose
michael.labriola
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
michael.labriola
 
How To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex InfrastructureHow To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex Infrastructure
michael.labriola
 
Blaze Ds Slides
Blaze Ds SlidesBlaze Ds Slides
Blaze Ds Slides
michael.labriola
 
2007 Max Presentation - Creating Custom Flex Components
2007 Max Presentation - Creating Custom Flex Components2007 Max Presentation - Creating Custom Flex Components
2007 Max Presentation - Creating Custom Flex Components
michael.labriola
 
Dense And Hot 360 Flex
Dense And Hot 360 FlexDense And Hot 360 Flex
Dense And Hot 360 Flex
michael.labriola
 
Dense And Hot Web Du
Dense And Hot  Web DuDense And Hot  Web Du
Dense And Hot Web Du
michael.labriola
 
Optimizing Browser Rendering
Optimizing Browser RenderingOptimizing Browser Rendering
Optimizing Browser Rendering
michael.labriola
 
Randori design goals and justification
Randori design goals and justificationRandori design goals and justification
Randori design goals and justification
michael.labriola
 
Flex 4 components from the firehose
Flex 4 components from the firehoseFlex 4 components from the firehose
Flex 4 components from the firehose
michael.labriola
 
Developing for a world wide audience
Developing for a world wide audienceDeveloping for a world wide audience
Developing for a world wide audience
michael.labriola
 
Developing for a world wide audience
Developing for a world wide audienceDeveloping for a world wide audience
Developing for a world wide audience
michael.labriola
 
FlexUnit 4 for contributors
FlexUnit 4 for contributorsFlexUnit 4 for contributors
FlexUnit 4 for contributors
michael.labriola
 
Write once... Take Less Time to Deploy
Write once... Take Less Time to Deploy Write once... Take Less Time to Deploy
Write once... Take Less Time to Deploy
michael.labriola
 
Flex 4 Component Development
Flex 4 Component DevelopmentFlex 4 Component Development
Flex 4 Component Development
michael.labriola
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
michael.labriola
 
How To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex InfrastructureHow To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex Infrastructure
michael.labriola
 
2007 Max Presentation - Creating Custom Flex Components
2007 Max Presentation - Creating Custom Flex Components2007 Max Presentation - Creating Custom Flex Components
2007 Max Presentation - Creating Custom Flex Components
michael.labriola
 
Ad

Recently uploaded (20)

Alec Lawler - A Passion For Building Brand Awareness
Alec Lawler - A Passion For Building Brand AwarenessAlec Lawler - A Passion For Building Brand Awareness
Alec Lawler - A Passion For Building Brand Awareness
Alec Lawler
 
Smart Home Market Size, Growth and Report (2025-2034)
Smart Home Market Size, Growth and Report (2025-2034)Smart Home Market Size, Growth and Report (2025-2034)
Smart Home Market Size, Growth and Report (2025-2034)
GeorgeButtler
 
Kiran Flemish - A Dynamic Musician
Kiran  Flemish  -  A   Dynamic  MusicianKiran  Flemish  -  A   Dynamic  Musician
Kiran Flemish - A Dynamic Musician
Kiran Flemish
 
Affinity.co Lifecycle Marketing Presentation
Affinity.co Lifecycle Marketing PresentationAffinity.co Lifecycle Marketing Presentation
Affinity.co Lifecycle Marketing Presentation
omiller199514
 
20250428 CDB Investor Deck_Apr25_vFF.pdf
20250428 CDB Investor Deck_Apr25_vFF.pdf20250428 CDB Investor Deck_Apr25_vFF.pdf
20250428 CDB Investor Deck_Apr25_vFF.pdf
yihong30
 
Region Research (Hiring Trends) Vietnam 2025.pdf
Region Research (Hiring Trends) Vietnam 2025.pdfRegion Research (Hiring Trends) Vietnam 2025.pdf
Region Research (Hiring Trends) Vietnam 2025.pdf
Consultonmic
 
Network Detection and Response (NDR): The Future of Intelligent Cybersecurity
Network Detection and Response (NDR): The Future of Intelligent CybersecurityNetwork Detection and Response (NDR): The Future of Intelligent Cybersecurity
Network Detection and Response (NDR): The Future of Intelligent Cybersecurity
GauriKale30
 
AlaskaSilver Corporate Presentation Apr 28 2025.pdf
AlaskaSilver Corporate Presentation Apr 28 2025.pdfAlaskaSilver Corporate Presentation Apr 28 2025.pdf
AlaskaSilver Corporate Presentation Apr 28 2025.pdf
Western Alaska Minerals Corp.
 
From Sunlight to Savings The Rise of Homegrown Solar Power.pdf
From Sunlight to Savings The Rise of Homegrown Solar Power.pdfFrom Sunlight to Savings The Rise of Homegrown Solar Power.pdf
From Sunlight to Savings The Rise of Homegrown Solar Power.pdf
Insolation Energy
 
Disinformation in Society Report 2025 Key Findings
Disinformation in Society Report 2025 Key FindingsDisinformation in Society Report 2025 Key Findings
Disinformation in Society Report 2025 Key Findings
MariumAbdulhussein
 
PREDICTION%20AND%20ANALYSIS%20OF%20ADMET%20PROPERTIES%20OF%20NEW%20MOLECULE%2...
PREDICTION%20AND%20ANALYSIS%20OF%20ADMET%20PROPERTIES%20OF%20NEW%20MOLECULE%2...PREDICTION%20AND%20ANALYSIS%20OF%20ADMET%20PROPERTIES%20OF%20NEW%20MOLECULE%2...
PREDICTION%20AND%20ANALYSIS%20OF%20ADMET%20PROPERTIES%20OF%20NEW%20MOLECULE%2...
AMITKUMARVERMA479091
 
Level Up Your Launch: Utilizing AI for Start-up Success
Level Up Your Launch: Utilizing AI for Start-up SuccessLevel Up Your Launch: Utilizing AI for Start-up Success
Level Up Your Launch: Utilizing AI for Start-up Success
Best Virtual Specialist
 
Accounting_Basics_Complete_Guide_By_CA_Suvidha_Chaplot (1).pdf
Accounting_Basics_Complete_Guide_By_CA_Suvidha_Chaplot (1).pdfAccounting_Basics_Complete_Guide_By_CA_Suvidha_Chaplot (1).pdf
Accounting_Basics_Complete_Guide_By_CA_Suvidha_Chaplot (1).pdf
CA Suvidha Chaplot
 
Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...
Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...
Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...
Lviv Startup Club
 
The Peter Cowley Entrepreneurship Event Master 30th.pdf
The Peter Cowley Entrepreneurship Event Master 30th.pdfThe Peter Cowley Entrepreneurship Event Master 30th.pdf
The Peter Cowley Entrepreneurship Event Master 30th.pdf
Richard Lucas
 
Strategic Enterprise Management - Unit I.pptx
Strategic Enterprise Management - Unit I.pptxStrategic Enterprise Management - Unit I.pptx
Strategic Enterprise Management - Unit I.pptx
PrekshyaRana
 
waterBeta white paper - 250202- two-column.docx
waterBeta white paper - 250202- two-column.docxwaterBeta white paper - 250202- two-column.docx
waterBeta white paper - 250202- two-column.docx
Peter Adriaens
 
NewBase 28 April 2025 Energy News issue - 1783 by Khaled Al Awadi_compressed...
NewBase 28 April 2025  Energy News issue - 1783 by Khaled Al Awadi_compressed...NewBase 28 April 2025  Energy News issue - 1783 by Khaled Al Awadi_compressed...
NewBase 28 April 2025 Energy News issue - 1783 by Khaled Al Awadi_compressed...
Khaled Al Awadi
 
The Fascinating World of Hats: A Brief History of Hats
The Fascinating World of Hats: A Brief History of HatsThe Fascinating World of Hats: A Brief History of Hats
The Fascinating World of Hats: A Brief History of Hats
nimrabilal030
 
Petslify Turns Pet Photos into Hug-Worthy Memories
Petslify Turns Pet Photos into Hug-Worthy MemoriesPetslify Turns Pet Photos into Hug-Worthy Memories
Petslify Turns Pet Photos into Hug-Worthy Memories
Petslify
 
Alec Lawler - A Passion For Building Brand Awareness
Alec Lawler - A Passion For Building Brand AwarenessAlec Lawler - A Passion For Building Brand Awareness
Alec Lawler - A Passion For Building Brand Awareness
Alec Lawler
 
Smart Home Market Size, Growth and Report (2025-2034)
Smart Home Market Size, Growth and Report (2025-2034)Smart Home Market Size, Growth and Report (2025-2034)
Smart Home Market Size, Growth and Report (2025-2034)
GeorgeButtler
 
Kiran Flemish - A Dynamic Musician
Kiran  Flemish  -  A   Dynamic  MusicianKiran  Flemish  -  A   Dynamic  Musician
Kiran Flemish - A Dynamic Musician
Kiran Flemish
 
Affinity.co Lifecycle Marketing Presentation
Affinity.co Lifecycle Marketing PresentationAffinity.co Lifecycle Marketing Presentation
Affinity.co Lifecycle Marketing Presentation
omiller199514
 
20250428 CDB Investor Deck_Apr25_vFF.pdf
20250428 CDB Investor Deck_Apr25_vFF.pdf20250428 CDB Investor Deck_Apr25_vFF.pdf
20250428 CDB Investor Deck_Apr25_vFF.pdf
yihong30
 
Region Research (Hiring Trends) Vietnam 2025.pdf
Region Research (Hiring Trends) Vietnam 2025.pdfRegion Research (Hiring Trends) Vietnam 2025.pdf
Region Research (Hiring Trends) Vietnam 2025.pdf
Consultonmic
 
Network Detection and Response (NDR): The Future of Intelligent Cybersecurity
Network Detection and Response (NDR): The Future of Intelligent CybersecurityNetwork Detection and Response (NDR): The Future of Intelligent Cybersecurity
Network Detection and Response (NDR): The Future of Intelligent Cybersecurity
GauriKale30
 
From Sunlight to Savings The Rise of Homegrown Solar Power.pdf
From Sunlight to Savings The Rise of Homegrown Solar Power.pdfFrom Sunlight to Savings The Rise of Homegrown Solar Power.pdf
From Sunlight to Savings The Rise of Homegrown Solar Power.pdf
Insolation Energy
 
Disinformation in Society Report 2025 Key Findings
Disinformation in Society Report 2025 Key FindingsDisinformation in Society Report 2025 Key Findings
Disinformation in Society Report 2025 Key Findings
MariumAbdulhussein
 
PREDICTION%20AND%20ANALYSIS%20OF%20ADMET%20PROPERTIES%20OF%20NEW%20MOLECULE%2...
PREDICTION%20AND%20ANALYSIS%20OF%20ADMET%20PROPERTIES%20OF%20NEW%20MOLECULE%2...PREDICTION%20AND%20ANALYSIS%20OF%20ADMET%20PROPERTIES%20OF%20NEW%20MOLECULE%2...
PREDICTION%20AND%20ANALYSIS%20OF%20ADMET%20PROPERTIES%20OF%20NEW%20MOLECULE%2...
AMITKUMARVERMA479091
 
Level Up Your Launch: Utilizing AI for Start-up Success
Level Up Your Launch: Utilizing AI for Start-up SuccessLevel Up Your Launch: Utilizing AI for Start-up Success
Level Up Your Launch: Utilizing AI for Start-up Success
Best Virtual Specialist
 
Accounting_Basics_Complete_Guide_By_CA_Suvidha_Chaplot (1).pdf
Accounting_Basics_Complete_Guide_By_CA_Suvidha_Chaplot (1).pdfAccounting_Basics_Complete_Guide_By_CA_Suvidha_Chaplot (1).pdf
Accounting_Basics_Complete_Guide_By_CA_Suvidha_Chaplot (1).pdf
CA Suvidha Chaplot
 
Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...
Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...
Yuriy Chapran: Zero Trust and Beyond: OpenVPN’s Role in Next-Gen Network Secu...
Lviv Startup Club
 
The Peter Cowley Entrepreneurship Event Master 30th.pdf
The Peter Cowley Entrepreneurship Event Master 30th.pdfThe Peter Cowley Entrepreneurship Event Master 30th.pdf
The Peter Cowley Entrepreneurship Event Master 30th.pdf
Richard Lucas
 
Strategic Enterprise Management - Unit I.pptx
Strategic Enterprise Management - Unit I.pptxStrategic Enterprise Management - Unit I.pptx
Strategic Enterprise Management - Unit I.pptx
PrekshyaRana
 
waterBeta white paper - 250202- two-column.docx
waterBeta white paper - 250202- two-column.docxwaterBeta white paper - 250202- two-column.docx
waterBeta white paper - 250202- two-column.docx
Peter Adriaens
 
NewBase 28 April 2025 Energy News issue - 1783 by Khaled Al Awadi_compressed...
NewBase 28 April 2025  Energy News issue - 1783 by Khaled Al Awadi_compressed...NewBase 28 April 2025  Energy News issue - 1783 by Khaled Al Awadi_compressed...
NewBase 28 April 2025 Energy News issue - 1783 by Khaled Al Awadi_compressed...
Khaled Al Awadi
 
The Fascinating World of Hats: A Brief History of Hats
The Fascinating World of Hats: A Brief History of HatsThe Fascinating World of Hats: A Brief History of Hats
The Fascinating World of Hats: A Brief History of Hats
nimrabilal030
 
Petslify Turns Pet Photos into Hug-Worthy Memories
Petslify Turns Pet Photos into Hug-Worthy MemoriesPetslify Turns Pet Photos into Hug-Worthy Memories
Petslify Turns Pet Photos into Hug-Worthy Memories
Petslify
 

Diving in the Flex Data Binding Waters

  • 1. Diving in the Data Binding Waters Michael Labriola Digital Primates
  • 2. Who are you? Michael Labriola Senior Consultant at Digital Primates Flex Geek Component Developer Flex Team Mentor
  • 3. Who were you? Michael Labriola Software Engineer Embedded Systems Developer Reverse Engineer
  • 4. What is this session about? This session is part of my continuing quest to teach Flex from the inside out. Learn what the Flex framework is really doing and you are more likely to use it successfully, respect its boundaries and extend it in useful ways
  • 5. One more reason Let’s call it “Game Theory”. If you know how something works really well, you know which rules you can bend and just how far you can bend them before they break. Sometimes you can even find really creative ways out of difficult situations
  • 6. Standard Disclaimer I am going to lie to you a lot… a whole lot Even at this ridiculous level of detail, there is much more All of this is conditional. So, we are just going to take one route and go with it
  • 7. Data Binding Defined Data Binding is the magical process by which changes in a data model are instantly propagated to views.
  • 8. Now Really Defined Data Binding is not magic It is a relatively complicated combination of generated code, event listeners and handlers, error catching and use of meta data through object introspection
  • 9. Still on the Soap Box Data Binding works because Flex (which I am generically using here to mean precompiler, compiler and framework) generates a lot of code on your behalf.
  • 10. Transformation When you use Data Binding, the Flex compiler generates code for you.. A lot of code So, the following example becomes.. package valueObject { [Bindable] public class Product { public var productName:String; } }
  • 11. Generated Code p ackage valueObject { import flash.events.IEventDispatcher; public class ProductManualBinding implements IEventDispatcher { private var dispatcher:flash.events.EventDispatcher = new flash.events.EventDispatcher(flash.events.IEventDispatcher(this)); [Bindable(event=&quot;propertyChange&quot;)] public function get productName():String { return _productName; } public function set productName(value:String):void { var oldValue:Object = _productName; if (oldValue !== value) { _productName = value; dispatchEvent(mx.events.PropertyChangeEvent.createUpdateEvent(this, &quot;productName&quot;, oldValue, value)); } } public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, weakRef:Boolean = false):void { dispatcher.addEventListener(type, listener, useCapture, priority, weakRef); } public function dispatchEvent(event:flash.events.Event):Boolean { return dispatcher.dispatchEvent(event); } public function hasEventListener(type:String):Boolean { return dispatcher.hasEventListener(type); } public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void { dispatcher.removeEventListener(type, listener, useCapture); } public function willTrigger(type:String):Boolean { return dispatcher.willTrigger(type); } } }
  • 12. Most Importantly public class ProductManualBinding implements IEventDispatcher { private var dispatcher:EventDispatcher = new EventDispatcher(IEventDispatcher(this)); [Bindable(event=&quot;propertyChange&quot;)] public function get productName():String { return _productName; } public function set productName(value:String):void { var oldValue:Object = _productName; if (oldValue !== value) { _productName = value; dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, &quot;productName&quot;, oldValue, value)); } }
  • 13. Only Half of the Equation Data Binding is about changing a model and having the view react So, the generated code for the following view becomes… [Bindable] private var product:Product; <mx:Label id=&quot;myLbl&quot; text=&quot;{product.productName}&quot;/>
  • 14. The Other 7/8 override public function initialize():void { var bindings:Array = []; var binding:Binding; binding = new mx.binding.Binding(this, function():String { var result:* = (product.productName); var stringResult:String = (result == undefined ? null : String(result)); return stringResult; }, function(_sourceFunctionReturnValue:String):void { myLabel.text = _sourceFunctionReturnValue; }, &quot;myLabel.text&quot;); bindings[0] = binding; var watchers:Array = []; watchers[0] = new mx.binding.PropertyWatcher(&quot;product&quot;,{propertyChange: true},[ bindings[0] ], function(propertyName:String):* { return target[propertyName]; } ); watchers[1] = new mx.binding.PropertyWatcher(&quot;productName&quot;,{productNameChanged: true}, [bindings[0]],null); watchers[0].updateParent(target); watchers[0].addChild(watchers[1]); for (var i:uint = 0; i < 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(); }
  • 15. Starting at the Top The generated code overrides the initialization function to add all of the generated code into startup The first relevant thing it does for us it to create an Array of mx.binding.Binding objects. These objects are responsible for executing bindings.. (moving values from the binding source to the destination.)
  • 16. mx.binding.Binding Instances of this class accept a document, srcFunc, destFunc and destString as parameters. The document is the target of the work. The srcFunc returns the value used in the binding. The destFunc assigns it to the destination. The destString is the destination represented as a String… more on that later
  • 17. Binding in our Example var bindings:Array = []; var binding:Binding; binding = new mx.binding.Binding(this, function():String { var result:* = (product.productName); var stringResult:String = (result == undefined ? null : String(result)); return stringResult; }, function(_sourceFunctionReturnValue:String):void { myLabl.text = _sourceFunctionReturnValue; }, “ myLbl.text&quot;); bindings[0] = binding;
  • 18. Watchers Still in the initialize method, the generated code creates an array of mx.binding.PropertyWatcher objects The objects are responsible for noticing a change and, among other things, notifying the binding objects that they should execute
  • 19. mx.binding.PropertyWatcher Instances of this class accept the propertyName, an object that indicates which events are broadcast when the property has changed, an array of listeners and a propertyGetter function The listeners are any Binding instances created for the property. In this case, the property getter is an anonymous function that returns the value of the property binding.
  • 20. Watchers in our Example watchers[0] = new mx.binding.PropertyWatcher(&quot;product&quot;, {propertyChange: true},[ bindings[0] ], propertyGetter ); watchers[1] = new mx.binding.PropertyWatcher(&quot;productName&quot;, {productNameChanged: true}, [bindings[0]],null); watchers[0].updateParent(target); watchers[0].addChild(watchers[1]);
  • 21. Chains Data Binding Expressions are rarely simple names of properties. They are often chains. For example: <mx:Text id=&quot;myText&quot; text=&quot;{user.name.firstName.text}&quot;/>
  • 22. Execution After the watchers are setup, the generated initialize function loops through all of the Binding objects and calls their execute() method. This method cautiously attempts to set the destination value to the source value, first ensuring that we aren’t already in process or an in an infinite loop.
  • 23. Value Changed One important thing to note about this process which often trips up new users to databinding: A value on an object is only set if it is differnet (oldValue !== value) What impact does this have on Objects? Arrays?
  • 24. Ways to Bind This explains how binding is setup if the bindings are declared in MXML. There are ways to handle binding in ActionScript: mx.binding.utils.BindingUtils mx.binding.utils.ChangeWatcher. Manually adding event listeners
  • 25. The differences You cannot: include ActionScript code in a data binding expression defined in ActionScript. include an E4X expression in a data binding expression defined in ActionScript. include functions or array elements in property chains in a data binding expression defined this way
  • 26. Also MXML provides better warning and error detection than any of the runtime methods
  • 27. BindingUtils BindingUtils provides two methods which do this work for you at runtime bindProperty and bindSetter The first one is used with public properties. The second is used with getter/setters.
  • 28. bindProperty Syntax public static function bindProperty(site:Object, prop:String, host:Object, chain:Object, commitOnly:Boolean = false):ChangeWatcher For example: public function setup():void { BindingUtils.bindProperty(someOtherTextFiled, “text”, someTextInput, &quot;text&quot;); }
  • 29. bindSetter Syntax public static function bindSetter(setter:Function, host:Object, chain:Object, commitOnly:Boolean = false):ChangeWatcher For example: public function updateIt(val:String):void { someOtherTextFiled.text = val.toUpperCase(); } public function setup():void { BindingUtils.bindSetter(updateIt, someTextInput, &quot;text&quot;); }
  • 30. The Chain The chain is a rather complex parameter that can take on multiple forms… for instance, it can be a: String containing the name of a public bindable property of the host object. An Object in the form: { name: property name, getter: function(host) { return host[property name] } }. A non-empty Array containing a combination of the first two options that represents a chain of bindable properties accessible from the host. For example, to bind the property host.a.b.c, call the method as: bindProperty(host, [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;], ...).
  • 31. ChangeWatcher public function setup():void { ChangeWatcher.watch(textarea, &quot;text&quot;, watchMeAndReact); } public function watchMeAndReact(event:Event):void{ myTA1.text=&quot;done&quot;; } You can also unwatch() something..
  • 32. Manual Event Listeners You could, but… The data binding code swallows a bunch of errors on your behalf, to handle things like null values, etc… your code will crash if you don’t take the same care
  • 33. What does this mean? Binding is just a contract between two objects. One object explains that it will broadcast an event when it changes and details what event that will be Another object waits for that event to occur and updates the destination when it occurs
  • 34. propertyChange Even though the propertyChange is the default event that Flex uses when you auto-generate binding code, you can change it if you use your own getters and setters. For example:
  • 35. Not propertyChange private var _productName:String; [Bindable(event='myProductNameChanged')] public function get productName():String { return _productName; } public function set productName( value:String ):void { _productName = value; dispatchEvent( new Event('myProductNameChanged') ); }
  • 36. Not getter/Setter You will need to broadcast this event somewhere else. [Bindable(event='myProductNameChanged')] public var productName:String;
  • 37. Double Down private var _productName:String; [Bindable(event='serverDataChanged')] [Bindable(event='myProductNameChanged')] public function get productName():String { return _productName; } public function set productName( value:String ):void { _productName = value; dispatchEvent( new Event('myProductNameChanged') ); }
  • 38. Models, Oh Models The propertyChange event is broadcast by default for every property setter that is auto-generated How do you think that scales in a giant application model? What happens?
  • 39. Binding to Unbindable Putting some of this to use
  • 40. Lazy Load Putting some of this to use
  • 41. Random Closing Tips Any users of describeType out there…. Make sure you use the DescribeTypeCache var info:BindabilityInfo = DescribeTypeCache.describeType(parentObj). bindabilityInfo;
  • 42. Q & A Seriously? You must have some questions by now?
  • 43. Resources Blog Aggregator (All of the Digital Primates) http://blogs.digitalprimates.net/ My Blog Specifically http://blogs.digitalprimates.net/codeSlinger/