Commit c0a3c046 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading
+6 KiB

File added.

No diff preview for this file type.

+903 −0

File added.

Preview size limit exceeded, changes collapsed.

+401 −0
Changes for Flx3 Ckbk Bonus Chaps Code/Bonus_Chap2_Shared_Objects.txt: 401 added lines, 0 removed lines.
Original line number Diff line number Diff line
Bonus Chapter 2: SharedObjects (Was previously chapter 17.)
==================
Recipe 17.2

// retrieve an existing shared object; otherwise create it
public var soInstance : SharedObject = SharedObject.getLocal( "myLso" );
// string storage
public var oString : String = "Adobe Flex 3 Rocks";
soInstance.data.oPhrase = oString;
// array storage
public var oArrayItems : Array = [ 10, 11, 12 ];
soInstance.data.oArrayNumbers = oArrayItems;
// boolean storage
public var oBoolean : Boolean = true;
soInstance.data.oDecision = oBoolean;
    
    
====================================
Recipe 17.3

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
    initialize="onInit()">
    <mx:Script>
        <![CDATA[
            private var lso : SharedObject;

            private function onInit() : void
            {
                lso = SharedObject.getLocal( "mylso" );
            }

            private function saveValue( event : Event ) : void
            {
                var flushStatus : String = null;
                lso.data.myLsoData = textinput.text;

                try{
                    flushStatus = lso.flush( 5000 );
                }
                catch( error : Error ) {
                    status.text = "fault : cannot write shared object to disk";
                }

                if ( flushStatus != null )
                {
                    switch( flushStatus )
                    {
                    case SharedObjectFlushStatus.PENDING:
                       status.text = "requesting permission to save lso";
                       lso.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
                       break;
                    case SharedObjectFlushStatus.FLUSHED:
                       status.text = "value flushed to disk";
                       break;
                    }
                }
            }

            private function onFlushStatus(event:NetStatusEvent):void
            {
                switch (event.info.code)
                {
                    case "SharedObject.Flush.Success":
                        status.text = "permission granted -- value saved.";
                        break;
                    case "SharedObject.Flush.Failed":
                        status.text = "permission denied -- value not saved.";
                        break;
                }
                lso.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
            }

            private function clearValue(event:MouseEvent):void
            {
                status.text = "cleared lso data value";
                delete lso.data.myLsoData;
            }
        ]]>
    </mx:Script>

    <mx:Form>
        <mx:FormItem label="Lso Data Input" width="100%">
            <mx:TextInput id="textinput" width="100%" />
        </mx:FormItem>
        <mx:FormItem direction="horizontal" width="100%">
            <mx:Button label="save value" width="100%" click="{ saveValue( event ) }" />
            <mx:Button label="clear value" width="100%" click="{ clearValue( event ) }" />
        </mx:FormItem>
        <mx:FormItem label="status message" width="100%">
            <mx:Label id="status" width="100%" />
        </mx:FormItem>
    </mx:Form>
</mx:Application>
    
    
====================================
Recipe 17.4

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            private var lso : SharedObject;

            private function readSharedObject() : void
            {
                var sampleData1 : String = "data1";

                lso = SharedObject.getLocal( "mylso" );

                if ( lso.data.someData1 == undefined ) {
                    lso.data.someData1 = sampleData1;
                    lso.flush();
                    status.text += "lso data after assignment: " + lso.data.someData1 + "\n\n";
                } else {
                    status.text += "lso already written to: " + lso.data.someData1 + "\n";
                }
            }
        ]]>
    </mx:Script>

    <mx:VBox width="100%" height="100%">
        <mx:Button label="read a shared object" click="{ readSharedObject() }" />
        <mx:TextArea id="status" width="100%" height="100%" />
    </mx:VBox>
</mx:Application>
    
    
====================================
Recipe 17.5

// create an lso
private var lso : SharedObject = getLocal( "myLso" );
// create some sample data
private var sampleData : String = "data";
//assign some data to the lso
lso.data.sampleData = sampleData;
//flush to the file system
lso.flush();
//check the lso value
trace( lso.data.sampleData );
// delete the lso
lso.clear();
// should be "undefined"
trace( lso.data.sampleData );
    
    
====================================
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            private var lso : SharedObject;

            private function removeSharedObject() : void
            {
               var sampleData1 : String = "data1";
               var sampleData2 : String = "data2";

               //create an lso object and assign some data to it
               lso = SharedObject.getLocal( "mylso" );
               lso.data.someData1 = sampleData1;
               lso.data.someData2 = sampleData2;
               lso.flush();
               status.text = "lso data after assignment" + "\ndata1: " + lso.data.someData1
                              + "\ndata2: " + lso.data.someData2;

               // delete a piece of data from the lso
               delete lso.data.someData1;
               status.text += "\n\nlso after deleting lso.data.someData1" + "\ndata1:"
                              + lso.data.someData1 + "\ndata2: " + lso.data.someData2;

                // remove the lso completely from the filesystem
                lso.clear();
                status.text += "\n\nlso data after calling clear()" + "\ndata1: "
                              + lso.data.someData1 + "\ndata2: " + lso.data.someData2;
            }
        ]]>
    </mx:Script>

    <mx:VBox width="100%" height="100%">
        <mx:Button label="remove a shared object" click="{ removeSharedObject() }" />
        <mx:TextArea id="status" width="100%" height="100%" />
    </mx:VBox>
</mx:Application>
    
    
====================================
Recipe 17.6

// the strongly typed object to use for this example
package oreilly.cookbook
{
    [Bindable]
    public class Automobile
    {
        private var _make : String;
        public function get make() : String { return _make; }
        public function set make( value : String ) : void { _make = value; }

        private var _model : String;
        public function get model() : String { return _model; }
        public function set model( value : String ) : void { _model = value; }

        private var _year : Number;
        public function get year() : Number { return _year; }
        public function set year( value : Number ) : void { _year = value; }

        public function Automobile()
        {
            super();
        }

        public function toString() : String
        {
            return "make: " + _make + "\nmodel: " + _model + "\nyear: " + _year;
        }
    }
}
    
    
====================================
// the main application
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
    initialize="onInit()">
    <mx:Script>
        <![CDATA[
            import mx.utils.ObjectUtil;
            import oreilly.cookbook.Automobile;
            import flash.net.registerClassAlias;

            private var lso : SharedObject;

            private function onInit() : void
            {
                // register the class alias to be able to later correctly
                // deserialize and serialize this class type
                registerClassAlias( "oreilly.cookbook.Automobile", Automobile );
                // initialize the shared object
                lso = SharedObject.getLocal( "automobile" );
            }

            private function save() : void
            {
                var automobile : Automobile = new Automobile();
                automobile.make = make.text;
                automobile.model = model.text;
                automobile.year = parseFloat( year.text );

                lso.data.automobile = automobile;
                lso.flush();
                status.text = "your automobile has been saved";
            }

            private function retrieve() : void
            {
                if ( lso.data.automobile != undefined )
                {
                var objectInfo : String = ObjectUtil.toString( lso.data.automobile);
                    status.text = "retrieving type information about the currently" +
                                    " stored object\n\n";
                    status.text += lso.data.automobile.toString() + "\n\n";
                    status.text += objectInfo;
                }
                else
                {
                    status.text = "nothing has been stored into the shared object";
                }
            }
        ]]>
    </mx:Script>

    <mx:VBox width="100%" height="100%">
       <mx:Form>
          <mx:FormItem label="make" width="100%">
              <mx:TextInput id="make" width="100%"/>
          </mx:FormItem>
          <mx:FormItem label="model" width="100%">
              <mx:TextInput id="model" width="100%"/>
          </mx:FormItem>
          <mx:FormItem label="year" width="100%">
              <mx:TextInput id="year" width="100%"/>
          </mx:FormItem>
          <mx:FormItem direction="horizontal" width="100%">
             <mx:Button label="save lso data" width="100%" click="{ save() }"/>
             <mx:Button label="retrieve lso data" width="100%" click="{ retrieve() }"/>
          </mx:FormItem>
      </mx:Form>
      <mx:TextArea id="status" editable="false" width="100%" height="100%" />
   </mx:VBox>
</mx:Application>
    
    
====================================
Recipe 17.8

package custom
{
    import flash.events.Event;
    import flash.net.SharedObject;
    import mx.controls.TextInput;

    public class PersistentTextInput extends TextInput
    {
        /**
         * The ID this component will use to save and later look up its
         * associated value.
         */
        public var persistenceId:String = null;

        /**
         * The SharedObject name to use for storing values.
         */
        private static const LOCAL_STORAGE_NAME:String = "persistentTextInputStorage";

        /**
         * Clears previously stored values for all PersistentTextInput instances.
         */
        public static function clearStoredValues() :void
        {
            var so:SharedObject = SharedObject.getLocal(LOCAL_STORAGE_NAME);
            so.clear();
        }

        /**
         * Handles initialization of this component.
         */
        override public function initialize() :void
        {
            super.initialize();
            addEventListener(Event.CHANGE, handleChange);
            restoreSavedValue();
        }

        /**
         * Event handler function for CHANGE events from this instance.
         */
        protected function handleChange(event:Event) :void
        {
            saveCurrentValue();
        }

        /**
         * Restores the previously saved value associated with the
         * persistenceID of with this instance.
         */
        protected function restoreSavedValue() :void
        {
            if (persistenceId != null)
            {
                var so:SharedObject = SharedObject.getLocal(LOCAL_STORAGE_NAME);
                var value:String = so.data[persistenceId];
                if (value != null)
                {
                    text = value;
                }
            }
        }

        /**
         * Saves the text value of this instance. Associates the value with
         * the persistenceId of this instance.
         */
        protected function saveCurrentValue() :void
        {
            if (persistenceId != null)
            {
                var so:SharedObject = SharedObject.getLocal(LOCAL_STORAGE_NAME);
                so.data[persistenceId] = text;
                so.flush();
            }
        }
    }
}
    
    
====================================
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:custom="custom.*" layout="vertical">

    <mx:Script>
        <![CDATA[
            import custom.PersistentTextInput;

            public function clearValues() :void
            {
                PersistentTextInput.clearStoredValues();
                message.text = "A page refresh will reveal that the values have not 
persisted.";
            }
        ]]>
    </mx:Script>

    <custom:PersistentTextInput id="firstNameInput"
        persistenceId="firstName" />
    <custom:PersistentTextInput id="lastNameInput" persistenceId="lastName" />
    <mx:Button label="Clear Persistent Values" click="clearValues()" />
    <mx:Label id="message" />

</mx:Application>
    
    
==================
 No newline at end of file
+480 −0

File added.

Preview size limit exceeded, changes collapsed.

+396 −0
Changes for Flx3 Ckbk Bonus Chaps Code/Bonus_Chap4_Dev_Strategies.txt: 396 added lines, 0 removed lines.
Original line number Diff line number Diff line
Bonus Chapter 4: Development Strategies (Was previously chapter 21.)
==================
Recipe 21.1

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local
="*" doubleClickEnabled="true">
    <local:Cloud height="200" width="400"/>
</mx:Application>
    
    
====================================
package{

    import flash.display.MovieClip;
    import mx.flash.UIMovieClip;

    public class Cloud extends UIMovieClip {

        public function growCloud(value:int):void {
            this.scaleX *= value;
            this.scaleY *= value;
        }

        public function darkenCloud(value:int):void {
            trace(' darken ');
            //create custom filters and darken the cloud image
        }

        public function lightenCloud(value:int):void {
            trace(' lighten ');
            //create custom filters and lighten the cloud image
        }

    }
}
    
    
====================================
Recipe 21.2

<local:SmileyContainer id="smiley" y="100" x="100">
    <mx:VBox>
        <mx:Button label="button" width="100%"/>
        <mx:Button label="button"  width="100%"/>
        <mx:Button label="button"  width="100%"/>
        <mx:Button label="button"  width="100%"/>
    </mx:VBox>
</local:SmileyContainer>
    
    
====================================
Recipe 21.5

<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="400" height="300">
    <mx:Script>
        <![CDATA[

            import oreilly.cookbook.cairngorm.events.RecipeEvent;
            import oreilly.cookbook.cairngorm.model.Model;
    
    
====================================
            private function loadRecipes():void {

                var evt:RecipeEvent = new RecipeEvent(RecipeEvent.GET_RECIPE);
                evt.recipeKeywords = recipeKeywords.text.split(",");
                //Note that the CairngormEvent class dispatches itself
                //This notifies the Cairngorm EventBroadcaster that the event
                //is being dispatched. This is used to ensure that the Cairngorm 
architecture
                //handles the event rather than the flash.events.EventDispatcher
                evt.dispatch();

            }

        ]]>
    </mx:Script>
    <mx:VBox>
        <mx:TextInput id="recipeKeywords"/>
        <mx:Button label="Load Recipes" click="loadRecipes()"/>
    
    
====================================
        <mx:DataGrid dataProvider="{Model.getInstance().recipeArray}">
            <mx:columns>
                <mx:DataGridColumn dataField="title"/>
                <mx:DataGridColumn dataField="difficulty"/>
                <mx:DataGridColumn dataField="pictureURL">
                    <mx:itemRenderer>
                        <mx:Component>
                            <mx:Image source="{data}"/>
                        </mx:Component>
                    </mx:itemRenderer>
                </mx:DataGridColumn>
                <mx:DataGridColumn dataField="preparationTime"/>
                <mx:DataGridColumn dataField="ingredients"/>
                <mx:DataGridColumn dataField="instructions"/>
            </mx:columns>
        </mx:DataGrid>
    </mx:VBox>
</mx:Canvas>
    
    
====================================
package oreilly.cookbook.cairngorm.events
{
    import com.adobe.cairngorm.control.CairngormEvent;

    public class RecipeEvent extends CairngormEvent
    {

        public static const GET_RECIPE:String = "getRecipe";

        //this will be all the keywords for our recipe and is stored here so it
        //can be sent to the service for processing
        public var recipeKeywords:Array;

        public function RecipeEvent(type:String, bubbles:Boolean=false, 
cancelable:Boolean=false)
        {
            super(type, bubbles, cancelable);
        }

    }
}
    
    
====================================
package oreilly.cookbook.cairngorm.model
{
    import com.adobe.cairngorm.model.ModelLocator;

    import mx.collections.ArrayCollection;

    public class Model implements ModelLocator
    {
        // A way to get typed arrays
        [Bindable]
        [ArrayElementType("oreilly.cookbook.cairngorm.vo.Recipe")]
        public var recipeArray:ArrayCollection;

        public static function getInstance():Model
        {
            if(inst == null)
            {
                inst = new Model();
            }
            return inst;
        }


        protected static var inst:Model;

    }
}
    
    
====================================
Recipe 21.6

function execute(event:CairngormEvent):void

Here is the RecipeCommand class:

package oreilly.cookbook.cairngorm.commands
{
    import com.adobe.cairngorm.commands.ICommand;
    import com.adobe.cairngorm.control.CairngormEvent;

    import mx.controls.Alert;
    import mx.rpc.IResponder;
    import mx.rpc.events.FaultEvent;

    import oreilly.cookbook.cairngorm.business.BusinessDelegate;
    import oreilly.cookbook.cairngorm.events.RecipeEvent;
    import oreilly.cookbook.cairngorm.model.Model;

    public class RecipeCommand implements ICommand, IResponder
    {
    
    
====================================
        public function execute(event:CairngormEvent):void {
            if(event.type == RecipeEvent.GET_RECIPE) {

                var delegate:BusinessDelegate = new BusinessDelegate(this);
                delegate.getRecipes(event.recipeKeywords);
            }
        }
    
    
====================================
        public function result(arr:ArrayCollection):void {
            Model.getInstance().recipeArray = arr;
        }

        public function fault(event:FaultEvent):void {
            Alert.show(event.message);
        }

    }
}
    
    
====================================
package oreilly.cookbook.cairngorm.business
{

    import mx.rpc.IResponder;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.rpc.remoting.RemoteObject;

    public class BusinessDelegate
    {
        private var responder:IResponder;

        public function BusinessDelegate(responder:IResponder){
            this.responder = responder;
        }
    
    
====================================
        public function getRecipes(params:Array):void {
            // we access the RemoteObject stored in the ServiceLocator by using the 
Cairngorm ServiceLocator singleton
            // and passing a reference to the id of the RemoteObject that we wish 
to call
            var service:RemoteObject = com.adobe.cairngorm.business.ServiceLocator.get
Instance().getRemoteObject("recipeService");
            var token:AsyncToken = service.send(params);
            var responder:mx.rpc.Responder = new mx.rpc.Responder(getRecipeResult, get
RecipeFault);
            token.addResponder(responder);

        }
    
    
====================================
        private function getRecipeResult(event:ResultEvent):void {
            responder.result(event.result as ArrayCollection);
        }

        private function getRecipeFault(event:FaultEvent):void {
            responder.fault(event);
        }

    }
}
    
    
====================================
Recipe 21.7

      public function addCommand( commandName : String, commandRef : Class, 
useWeakReference : Boolean = true ) : void
      {
         if( commands[ commandName ] != null )
            throw new CairngormError( CairngormMessageCodes.COMMAND_ALREADY_REGISTERED, commandName );

         commands[ commandName ] = commandRef;
         CairngormEventDispatcher.getInstance().addEventListener( commandName, execute Command, false, 0, useWeakReference );
      }
    
    
====================================
      protected function executeCommand( event : CairngormEvent ) : void
      {
         var commandToInitialise : Class = getCommand( event.type );
         var commandToExecute : ICommand = new commandToInitialise();

         commandToExecute.execute( event );
      }

      protected function getCommand( commandName : String ) : Class
      {
         var command : Class = commands[ commandName ];

         if ( command == null )
            throw new CairngormError( CairngormMessageCodes.COMMAND_NOT_FOUND, command Name );

         return command;
      }
    
    
====================================
package oreilly.cookbook.cairngorm.controller
{
    import com.adobe.cairngorm.control.FrontController;

    import oreilly.cookbook.cairngorm.commands.RecipeCommand;
    import oreilly.cookbook.cairngorm.events.RecipeEvent;

    public class Controller extends FrontController
    {
        public function Controller()
        {
            super();
    
    
====================================
            // In this simple example there is only one Command that needs to be added
            // to the controller, but usually there are far more Commands to be added
            // when the controller is initialized.addCommand(RecipeEvent.GET_RECIPE, RecipeCommand);
        }

    }
}
    
    
====================================
<cairngorm:ServiceLocator xmlns="*" xmlns:mx="http://www.adobe.com/2006/mxml" 
xmlns:cairngorm="com.adobe.cairngorm.business.*">
    <mx:RemoteObject id="recipeService"
        destination="http://localhost/service_location/"
        showBusyCursor="true"
        source="oreilly.cookbook.service.RecipeService"
        makeObjectsBindable="true">

        <mx:method name="getRecipe"/>

    </mx:RemoteObject>
</cairngorm:ServiceLocator>
    
    
====================================
Recipe 21.10

package oreilly.cookbook
{
    import flash.utils.*;
    public class CustomMetaData
    {
        public function CustomMetaData()
        {
        }

        public function get description():Object {
            return describeType(this);
        }

        [CustomMetaProp(metaPropOne="foo", metaPropTwo="bar")]
        public function get propertyThatContainsMetaData():Object {
            return null;
        }
        public function set propertyThatContainsMetaData(value:Object):void {

        }
    }
}
    
    
====================================
<?xml version="1.0"?>
<flex-config xmlns="http://www.adobe.com/2006/flex-config">
    <compiler>
        <keep-as3-metadata>
            <name>CustomMetaProp</name>
        </keep-as3-metadata>
        <keep-generated-actionscript>true</keep-generated-actionscript>
        <source-path>
                <path-element>.</path-element>
            </source-path>
    </compiler>
</flex-config>
    
    
====================================
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
    <mx:Script>
        <![CDATA[
          import oreilly.cookbook.CustomMetaData;
          private var metaData:CustomMetaData = new CustomMetaData();

          private function displayDescription():void
          {
            var xmlData:XML = metaData.description;
            trace(String(xmlData.accessor.(@name == "propertyThatContainsMetaData")));
          }
       ]]>
    </mx:Script>
    <mx:Button label="Describe" click="displayDescription()"/>
</mx:Application>
    
    
====================================
<accessor name="propertyThatContainsMetaData" access="readwrite" type="Object" declared
By="oreilly.cookbook::CustomMetaData">
  <metadata name="CustomMetaProp">
    <arg key="metaPropOne" value="foo"/>
    <arg key="metaPropTwo" value="bar"/>
  </metadata>
</accessor>
    
    
==================
 No newline at end of file
Loading