0 Replies Latest reply on Feb 4, 2011 10:01 PM by cmittle

    Help with event listener

    cmittle

      I'm having some trouble trying to figure out how this event listener will work.

       

      The main application is building an arrayCollection of a calendarDay custom components which is displayed by a DataGroup.

      Within each calendarDay custom component i may create an arrayList of a DriverDetailComponent custom components displayed within the calendarDay by a DataGroup.

       

      If a user double clicks on the DriverDetailComponent that is two layers in I would like to change states of the main application.  I'm having trouble figuring out what item in the main application to set the listener on.  Please help.

       

       

      I can't figure out how to post the below as scrollable code snips so this is very long.

       

      Main application code:

      <code><?xml version="1.0" encoding="utf-8"?>
      <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                     xmlns:s="library://ns.adobe.com/flex/spark"
                     xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:components="components.*"
                     preinitialize="readDataFile()"
                     creationComplete="buildRowTitles()"
                     width="1024" height="512"  backgroundColor="#A4BDD8">
          <s:states>
              <s:State name="State1"/>
              <s:State name="driverDetailState"/>
          </s:states>
          <!--
          <fx:Style source="EventCalendar.css"/>
          creationComplete="readDataFile()"    creationComplete="driversList.send()"-->
         
          <fx:Declarations>
              <!-- Place non-visual elements (e.g., services, value objects) here -->       
              <mx:DateFormatter id="myDateFormatter"
                                formatString="EEE, MMM D, YYYY"/>
             
              <!--<s:HTTPService id="driversList"
                             url="files/drivers.xml"
                             result="driversList_resultHandler(event)"
                             fault="driversList_faultHandler(event)"/>
              <s:HTTPService id="postDriversList"
                             url="files/drivers.xml"
                             method="POST"
                             result="postDriversList_resultHandler(event)"
                  />-->
              <!--<s:Move id="expandTab"
                      target="{labelTab}"
                      xBy="250"/>-->
             
          </fx:Declarations>
          <fx:Script>
              <![CDATA[
                  import components.CalendarDay;
                  import components.TruckDriver;
                  import components.calendarDay;
                 
                  import events.CancelChangeDriversEvent;
                  import events.ChangeDriversEvent;
                  import events.EditDriverEvent;
                 
                  import mx.collections.ArrayCollection;
                  import mx.collections.ArrayList;
                  import mx.containers.Form;
                  import mx.controls.Alert;
                  import mx.controls.CalendarLayout;
                  import mx.core.FlexGlobals;
                  import mx.core.IVisualElement;
                  import mx.core.WindowedApplication;
                  import mx.printing.FlexPrintJob;
                  import mx.rpc.events.FaultEvent;
                  import mx.rpc.events.ResultEvent;
                  import mx.rpc.xml.SimpleXMLEncoder;
                 
                  import spark.components.Application;
                 
                  import utilities.FormatUtil;
                  import utilities.ObjectToXML;
                 
                  /* public var prefsFile:File; */ // The preferences prefsFile
                  [Bindable] public var driversXML:XML; // The XML data
                  public var stream:FileStream; // The FileStream object used to read and write prefsFile data.
                  public var fileName:String="driversArrayCollection";
                  public var directory:String = "AceTrackerData";
                  public var dataFile:File = File.documentsDirectory.resolvePath(directory + "\\" + fileName);
                  [Bindable]
                  public var drivers:ArrayCollection=new ArrayCollection();
                  private var fileStream:FileStream;
                  [Bindable]
                  public var calendarDayArray:ArrayCollection = new ArrayCollection;
                  public var i:int;
                  [Bindable]
                  public var weekOneTitle:String;
                  [Bindable]
                  public var weekTwoTitle:String;
                  [Bindable]
                  public var weekThreeTitle:String;
                  [Bindable]
                  public var weekFourTitle:String;
                  public var day:Object;

       

                  protected function readDataFile():void
                  {
                      if(dataFile.exists)
                      {
                          fileStream = new FileStream();
                          fileStream.open(dataFile, FileMode.READ);
                          drivers = fileStream.readObject() as ArrayCollection;
                          fileStream.close();
                      }
                      else
                      {
                          drivers = new ArrayCollection();
                          var driver:TruckDriver = new TruckDriver("New", "Driver", 000);
                          drivers.addItem(driver);
                          saveData(drivers);
                      }
                      buildCalendarArray();
                  }
                  protected function buildCalendarArray():void
                  {
                      calendarDayArray.removeAll();
                      for (i=0; i<28; i++)
                      {
                          var cd:calendarDay = new calendarDay;
                         
                          cd.dateOffset= i-7
                          cd.drivers=drivers;
                           cd.addEventListener("editDriverEvent",editDriverEvent_Handler);
                          calendarDayArray.addItem(cd);
                         
                      }
                     
                  }

                private function saveData(obj:Object):void//this is called on the postDriversList result handler to create and write XML data to the file
                  {
                      var fs:FileStream = new FileStream();
                      fs.open(dataFile, FileMode.WRITE);
                      /* fs.writeUTFBytes(myXML); */
                      fs.writeObject(drivers);
                      fs.close();
                  }

       


                  protected function driverschedule1_changeDriversHandler(event:ChangeDriversEvent):void
                  {
                      saveData(drivers); 
                     
                      readDataFile();//i read the drivers file again, this refreshes my data, and removes any temporary data that may have been stored in the drivers array
                     
                      buildCalendarArray();
                      currentState = 'State1';//this hides the driversdetail window after we've clicked save
                      /* postDriversList.send(event.driverInfo); */  //this needs to be different
                      /* Alert.show("TEST"); */
                     
                  }
                  protected function driverschedule1_cancelChangeDriversHandler(event:CancelChangeDriversEvent):void
                  {
                      /* Alert.show("Changes have been canceled."); */
                      readDataFile();//this re-reads the saved data file so that the changes that were made in the pop up window
                      // are no longer reflected if you reopen the window
                      buildCalendarArray();
                      currentState = 'State1';  //this hides the driversdetail window after we've clicked cancel
                  }
             
                  protected function buildRowTitles():void
                  {
                      var calendarDay0:Object;
                      var calendarDay6:Object;
                      calendarDay0=calendarDayArray.getItemAt(0);
                      calendarDay6=calendarDayArray.getItemAt(6);
                      weekOneTitle = calendarDay0.getDayString() + " - " + calendarDay6.getDayString();
                      weekTwoTitle=calendarDayArray.getItemAt(7).getDayString()+ " - " + calendarDayArray.getItemAt(13).getDayString();
                      weekThreeTitle=calendarDayArray.getItemAt(14).getDayString()+ " - " + calendarDayArray.getItemAt(20).getDayString();
                      weekFourTitle=calendarDayArray.getItemAt(21).getDayString()+ " - " + calendarDayArray.getItemAt(27).getDayString();
                  }

       

       

       

              ]]>
          </fx:Script>

         
          <s:Group height="100%" width="100%">
              <s:layout>
                  <s:BasicLayout/>  <!--This is the outermost layout for the main application MXML-->
              </s:layout>

       

                 
          <s:Scroller width="95%" height="100%"  >
          <s:Group height="100%" width="100%"  ><!--this groups the vertically laid out row titles hoizontally with the large group of calendar days and day titles-->
              <s:layout>
                  <s:HorizontalLayout/>
              </s:layout>
             
             
          <s:Group height="95%" width="50" ><!--this is the group of row titles layed out vertically-->
              <s:layout>
                  <s:VerticalLayout paddingLeft="40" paddingTop="35"/>
              </s:layout>
              <s:Label text="{weekOneTitle}"
                       rotation="-90"
                       backgroundColor="#989393"
                       height="25%" width="115"
                       fontWeight="normal" fontSize="15"
                       paddingTop="4" textAlign="center"  />
              <s:Label text="{weekTwoTitle}"
                       rotation="-90"
                       backgroundColor="#989393"
                       height="25%" width="115"
                       fontWeight="normal" fontSize="15"
                       paddingTop="4" textAlign="center" />
              <s:Label text="{weekThreeTitle}"
                       rotation="-90"
                       backgroundColor="#989393"
                       height="25%" width="115"
                       fontWeight="normal" fontSize="15"
                       paddingTop="4" textAlign="center"  />
              <s:Label text="{weekFourTitle}"
                       rotation="-90"
                       backgroundColor="#989393"
                       height="25%" width="115"
                       fontWeight="normal" fontSize="15"
                       paddingTop="4" textAlign="center"  />
          </s:Group>
         
             
         
         
         
             
          <s:Group height="100%" width="100%" >
              <!--this vertically groups together the horizontal day names group and the tile layout datagroup of calendar days-->
              <s:layout>
                  <s:VerticalLayout paddingLeft="5"/>
              </s:layout>
          <s:Group width="100%" >
              <s:layout><!--this group horizontal layout is for the Day names at the top-->
                  <s:HorizontalLayout paddingTop="10"/>
              </s:layout>
             
              <s:Label id="dayNames" text="Sunday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
              <s:Label text="Monday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
              <s:Label text="Tuesday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
              <s:Label text="Wednesday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
              <s:Label text="Thursday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
              <s:Label text="Friday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
              <s:Label text="Saturday" width="16%" fontWeight="bold" fontSize="18" textAlign="center"/>
          </s:Group>
         
         
                 
             
              <!--<s:SkinnableContainer width="16%">-->
                  <s:DataGroup id="calendarDataGroup"
                               dataProvider="{calendarDayArray}"
                               itemRenderer="{null}"  resizeMode="scale"
                                height="100%" width="100%"
                                >  <!--  I had to use a null renderer because otherwise each instance is added in a group container renderers.DriverScheduleRenderer-->
                      <s:layout >
                          <s:TileLayout requestedColumnCount="7" />
                      </s:layout>

       

                     
                  </s:DataGroup>
             
         
              <!--</s:SkinnableContainer>-->

       

         
          <!--<mx:FormItem label="Today's Date:">
              <s:TextInput id="dateToday"
                           text="{myDateFormatter.format(testDate)}"/>
          </mx:FormItem>-->
         
          <!--<components:DriverSchedule drivers="{drivers}"
                                     changeDriversEvent="driverschedule1_changeDriversHandler(event)"/>-->
              <s:HGroup>  <!--this groups together my drivers button and my print button at the bottom of the calendar-->
                 
              <s:Button id="showDriverDetailButton"
                        label="Driver List"
                        click="currentState = 'driverDetailState'">
                 
                  <!--</s:Button>
                  <s:Button id="printButton"
                      label="Print"
                      >  click="printButton_clickHandler(event)"-->
                     
                  </s:Button>
              </s:HGroup>    <!--this is the end of the small hgroup which pairs my drivers button with the print button-->                  
          </s:Group><!--this ends the vertical grouping of the day names and the tile layout calendar-->   
             
      </s:Group>        <!--this ends the horizontal grouping of the calendar (names and days) with the week labels at the left-->
          </s:Scroller>
              <s:SkinnableContainer includeIn="driverDetailState"
                                    width="95%" height="95%"  horizontalCenter="0" verticalCenter="0"
                                    backgroundColor="#989898" backgroundAlpha="0.51">
                  <s:BorderContainer horizontalCenter="0" verticalCenter="0">
                     
                  <components:DriverSchedule id="driverSchedule"
                                              drivers="{drivers}"
                                             changeDriversEvent="driverschedule1_changeDriversHandler(event)"
                                             cancelChangeDriversEvent="driverschedule1_cancelChangeDriversHandler(event)"
                                             />
                  </s:BorderContainer>
              </s:SkinnableContainer>
          </s:Group>  <!--end of basic layout group-->
      </s:WindowedApplication>

      </code>

      calendarDay.mxml code:

      <code>

      <?xml version="1.0" encoding="utf-8"?>
      <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               creationComplete="initDay()"
                width="100%">  <!--width="16%" height="25%"  width="160" height="112"-->
          <fx:Declarations>
              <!-- Place non-visual elements (e.g., services, value objects) here -->
              <mx:DateFormatter id="myDateFormatter"
                                formatString="MMM D"/>
          </fx:Declarations>
          <fx:Metadata>
              [Event(name = "editDriverEvent", type="events.EditDriverEvent")]
             
          </fx:Metadata>
          <fx:Script>
              <![CDATA[
                  import components.CalendarDay;
                  import components.DriverDetailComponent;
                 
                  import events.EditDriverEvent;
                 
                  import mx.collections.ArrayCollection;
                  import mx.collections.ArrayList;
                  import mx.controls.CalendarLayout;
                  import mx.controls.DateField;
                 
                  [Bindable]
                  public var todayCollection:ArrayCollection = new ArrayCollection;
                  [Bindable]
                  public var todayList:ArrayList=new ArrayList; //arraylist created as data provider for dataGroup, this is where all drivers with an arrival date of today are added
                  [Bindable]
                  public var currDate:Date =new Date; //this will be used to contain the current real world date
                  [Bindable]
                  public var calDate:Date = new Date; //this is used below to determine the date of the calender day that is being created
                  [Bindable] 
                  public var todaysDate:CalendarDay;
                  [Bindable]
                  public var currDay:int;
                  [Bindable]
                  public var dateOffset:int;
                  public var drivers:ArrayCollection= new ArrayCollection();
                     public var driver:Object;  
                  public var rowLabel:String;
                 
                 
                  public function initDay():void
                  {
                      todaysDate  = new CalendarDay(currDate, currDate.day, dateOffset)//currDate represents the day the operating system says today is
                          currDay=todaysDate.returnDate().getDate();//currDay is an int representing the day of the month
                          calDate=todaysDate.returnDate();//calDate represents the actual date on the calendar (MM-DD-YYY) that is currently being evaluated
                          /* if (currDay ==currDate.getDate()) //i want to highlight the day if it is in fact today
                          {
                              cont.styleName="Today";
                          } */
                         
                              if (calDate.getDate() == currDate.getDate())
                          {
                              calDayBorder.setStyle("backgroundColor", "#FFFF00");
                          }
                          else
                          {
                              calDayBorder.setStyle("backgroundColor", "#EEEEEE");
                          }  
                           addDrivers(); 
                      return;
                  }
                    public function addDrivers():void
                  {
                         var count:int = 0;
                        /*var driverDetail:DriverDetailComponent;
                        var driver =  */
                      for each (driver in drivers)
                      {//i check the date value based on data entry of mm-dd-yy format against the calculated date for the day
                          //the calender is building and if it is equal the drivers information is added to this day of the calendar
                          if (DateField.stringToDate(driver.arrivalDate,"MM/DD/YYYY").getDate() == calDate.getDate())
                              {
                                  var driverDetail:DriverDetailComponent = new DriverDetailComponent; //i create a new visual component that adds the id and destination to the calendar day
                                  driverDetail.driverid = drivers[count].id; //i feed the id property which is the truck# - firstName
                                  driverDetail.driverToLoc=drivers[count].toLoc; //i feed the toLoc which is the current destination of the driver
                                  driverDetail.driverArrayLocation=count;   //here i feed the location of this driver in the "drivers" array so i know where it's at for the click listener
                                  todayList.addItem(driverDetail);
                              //this concatenates the drivers truck number first name and destination to display in the calendar day
                                  /* todayList.addItem(driver.truckNumber + " - " + driver.firstName + " - " + driver.toLoc); */
                                 
                              }
                      count ++;
                      }
                  } 
                  public function getDayString():String
                  {
                      rowLabel =myDateFormatter.format(calDate);
                      return rowLabel;
                  }

       

              ]]>
          </fx:Script>
          <s:BorderContainer id="calDayBorder" width="160" styleName="Today" cornerRadius="2" dropShadowVisible="true" height="100%">
              <s:layout>
                  <s:BasicLayout/>   
              </s:layout>
             
              <!--I need to make a custom item renderer for my calendar days that limits the height and width of the day, and also puts the items
              closer together so i can fit maybe 5 drivers on a single day-->
              <s:DataGroup dataProvider="{todayList}"
                           itemRenderer="spark.skins.spark.DefaultComplexItemRenderer"
                           bottom="-2"
                           width="115" left="2">  <!--width="94%"  width="100"  width="16%"-->
                  <s:layout >
                      <s:VerticalLayout gap="-4"/> <!--The reduced gap pushes the drivers together if there are serveral on one day. This helps cleanly show several drivers on one day-->
                  </s:layout>
              </s:DataGroup >
              <s:Label  text="{currDay}" right="3" top="2" fontSize="14" fontWeight="bold"/>
          </s:BorderContainer>
         
         
      </s:Group>

      </code>

      DriverDetailComponent code:

      <code><?xml version="1.0" encoding="utf-8"?>
      <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx">
          <fx:Declarations>
              <!-- Place non-visual elements (e.g., services, value objects) here -->
             
          </fx:Declarations>
          <fx:Metadata>
              [Event(name = "editDriverEvent", type="events.EditDriverEvent")]
          </fx:Metadata>
          <fx:Script>
              <![CDATA[
                  import events.EditDriverEvent;
                 
                  import mx.controls.Alert;
                  [Bindable]
                  public var driverid:String;
                  [Bindable]
                  public var driverArrayLocation:int;
                  [Bindable]
                  public var driverToLoc:String;

       


                  protected function label1_doubleClickHandler(event:MouseEvent):void
                  {
                      Alert.show("You have selected " +driverid +" at location "  + driverArrayLocation.toString() +" in the drivers ArrayCollection.");
                      var eventObject:EditDriverEvent = new EditDriverEvent("editDriverEvent",driverArrayLocation);
                      dispatchEvent(eventObject);

       

                  }

       

              ]]>
          </fx:Script>
         
          <s:Label id="driverDetailLabel" text="{driverid} - {driverToLoc}"  doubleClick="label1_doubleClickHandler(event)" doubleClickEnabled="true"/>
         
      </s:Group>
      </code>