AIR-Mobile Tip #1 Passing key-value pairs between views



This blog will start featuring tips and tricks for AIR-based application development on mobile devices. The tips are primarily for AIR and ActionScript developers who want to learn some tricks for quickly and effectively building applications for the mobile devices.

Tip: You can easily pass a key-value pair from one view to another view.

Here is a simple example:

MyView 1

<?xml version="1.0" encoding="utf-8"?>
    <s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" title="Home">

        <fx:Script>

          <![CDATA[
          protected function button1_clickHandler(event:MouseEvent):void
          {
              navigator.pushView(views.MyView2,{userKey:"someValue"});
          }
          ]]>

        </fx:Script>
      <s:Button x="178" y="196" label="Button" click="button1_clickHandler(event)"/>
   </s:View>

In MyView1, we are passing a key-vale pair to MyView2 using the navigator.pushView method.

MyView 2

<?xml version="1.0" encoding="utf-8"?>
    <s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" title="MyView" 
       viewActivate="view1_viewActivateHandler(event)" >

       <fx:Script>
          <![CDATA[
            import mx.events.FlexEvent;

            private var userValue:String;

            protected function view1_viewActivateHandler(event:FlexEvent):void
            {
                userValue = data.userKey;
                trace(userValue);
            }
          ]]>
      </fx:Script>
   </s:View>

In MyView2, we are receiving the key-value pair when the view gets activated.

Why would you need to pass key-value pairs between views? You can use this technique:

  • when you want to pass form values from one view to another.
  • when you want to pass user preferences.
  • when you want to route the view based on a key.
  • when you want to change the behavior of the view based on some keys. For instance, in a game, a view can read from the application storage directory and load the saved game or just start with a new game based on the values passed.

Apart from a key-value pair, you can also pass any untyped object from one view to another.