After learning how to create a custom Event, I decided to try to make a DataBinding Model. Finally I did it.

Again, I decided to create the same application but with a Model as in my previous post.

This time I needed to show/hide a button in the main application when the user clicked on a button in the component. I extended the code, by trying to manipulate a second component.

This is the final file:

1. Step

First you have to create a Actioncript Class. In my case I created it in a Model Folder. I used a Singleton Template I found on the web. It basically creates an instance and checks that the instance is not repeated. First the template:

package model
{

  public class ButtonModel
  {
     
     // HERE YOU SHOULD CREATE THE GLOBAL VARIABLES

     
     private static var instance:ButtonModel;
 
     public function ButtonModel()
     {
 if( instance != null )
 {
    throw( new Error( "there can be only one instance of ChatModel" ) );
 }  
     }

     public static function getInstance():ButtonModel
     {
 if( instance == null )
 {
    instance = new ButtonModel();
 }
     return instance;
     }
  }
}

Now you can define new Variables. In this case I needed a Boolean, which I call ButtonVisible

[Bindable]
public var ButtonVisible:Boolean = true;

2. Step

Now that I defined a new Bindable Variable, I can access it everywhere I want, lets say the main application:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" xmlns:components="components.*" viewSourceURL="srcview/index.html">
 
 <mx:Script>
  <![CDATA[
  <b>import model.ButtonModel;</b>
 ]]>
 </mx:Script>
 
 <mx:VBox>
 
  <components:Component1 />
  <mx:Button id="AppButton" label="AppButton"
  visible="<b>{model.ButtonModel.getInstance().ButtonVisible}</b>" />
  <components:component2 />
 
 </mx:VBox>
 
 
</mx:Application>

3. Step

Lastly I can manipulate it in a component.

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" >
 <mx:Script>
  <![CDATA[
 
   import model.ButtonModel;
     
   public function clickHandler(e:MouseEvent):void {
    if(model.ButtonModel.getInstance().ButtonVisible == true) {
     model.ButtonModel.getInstance().ButtonVisible = false;
    } else {
     model.ButtonModel.getInstance().ButtonVisible = true;
    }
   }
  ]]>
 </mx:Script>
 
 <mx:Button id="compButton" label="ComponentButton" visible="true"
  click="clickHandler(event)"/>

</mx:Canvas>

Hope it helps.

ChristianDataBindingExample