Solved

Flex - Accessing App Properties From Included AS File

Posted on 2009-07-15
10
428 Views
Last Modified: 2013-11-11
In my recent efforts to clean-up some prototype code, I have introduced an error that I can't seem to figure my way around...

In my main Flex application, I refer to other MXML objects via <local:MyMXMLObject id="myObj"...>

The "MyMXMLObject.mxml" was created to keep the code cleaner, and consisted of other basic <mx:...> components.

I also had a huge <mx:Script CDATA...> block in my application code, which had functions that manipulated behaviors in the MyMXMLObject (myObj).

This all worked wonderfully, until I decided to do some further cleanup, and create some ActionScript files, which I would include in the beginning of my application using <mx:script source="myInclude.as">.  So now, my ActionScript files have functions that have references to components that used to be in the same scope, when resided in the application object.  I even had "this." refrerences in the function code, which I've recently removed.

I'm getting errors when the functions get called: "TypeError: Error #1009: Cannot access a property or method of a null object reference.".  I completely understand why I'm getting the errors, I just don't understand enough about application, component, and variable scope to figure out how to resolve this.  I tried importing mx.core.Application.application, to see if I could access application.myComponent, but that didn't seem to work.  Probably because an application variable was never set to the parent application...  I just don't understand enough about Flex yet to work through the particulars of how that all might work???

So my basic question is...  How do I access a component of my main application (really properties or methods), from ActionScript files, which I've included in my application through <mx:script source...> includes?

Please let me know if I can provide any additional information of use.

Thanks and best regards,
Todd
0
Comment
Question by:ToddBPeterson
  • 5
  • 5
10 Comments
 
LVL 9

Expert Comment

by:danyul_c
ID: 24864877
In a good OOP design each file will encapsulate its own methods within the one file.

Then, if you wish to perform operations on another component you would either, from the parent, use the reference to the child and call it's public method.

Or, from the child you call the method of the parent  either by pre-defined reference or a temporary assignment to a variable such as:

var myMxmlDoc:MyMXMLObject = parent as MyMXMLObject;
myMxmlDoc.method();

If you are working with separate files for the one object you are going to have to create references for the MXML side in the AS side.
0
 

Author Comment

by:ToddBPeterson
ID: 24871000
Thanks for the response danyul_c!

I agree that what I've put together probably doesn't follow best OOD/OOP practices...  I was merely trying to cleanup what I created as a prototype to make it easier to maintain, for demo purposes.  The real-world application will certainly go through much more rigor...  I just wanted to present some capabilities.

In order to get past this, I have reverted back, by putting all of the included ActionScript back into the main MXML file, with a <mx:script ...  CDATA...> block.  However, I'm still getting the same error.  I'm completely stumped!

I'll need some time to get my prototype functional again, before I can dig in and use the methodologies you've suggested.  Thanks so much for the feedback though!

Best Regards,
Todd
0
 
LVL 9

Expert Comment

by:danyul_c
ID: 24871038
Can you show me the mxml with the code and the call you are trying to make and maybe I can figure it our for you.
0
 

Author Comment

by:ToddBPeterson
ID: 24871866
Attempted to slim down the code to be able to share with you, and am not getting the error...  I'm going to build it back up, a little bit at a time and see what happens...

I'll respond when I have more...

Thanks,
Todd
0
 
LVL 9

Expert Comment

by:danyul_c
ID: 24871894
Good to hear. I fear its simply because a variable is being called before it is initialised.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:ToddBPeterson
ID: 24873128
Ok...  I have been able to get a trimmed down version of code, reproducing the behavior...

Below is the source from the primary objects that seem to be giving me grief...  Any thoughts you have are greatly appreciated!

The error, again is:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
      at SiteMockupShared/goToBook()[C:\FlexSDK\samples\SiteMockup\src\SiteMockupShared.mxml:87]
      at SiteMockupShared/setCurrentDoc()[C:\FlexSDK\samples\SiteMockup\src\SiteMockupShared.mxml:45]
      at SiteMockupShared/headerClicked()[C:\FlexSDK\samples\SiteMockup\src\SiteMockupShared.mxml:93]
      at SiteMockupShared/__accordion_change()[C:\FlexSDK\samples\SiteMockup\src\SiteMockupShared.mxml:110]
      at flash.events::EventDispatcher/dispatchEventFunction()
      at flash.events::EventDispatcher/dispatchEvent()
      at mx.core::UIComponent/dispatchEvent()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\core\UIComponent.as:9298]
      at mx.containers::Accordion/dispatchChangeEvent()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\containers\Accordion.as:1841]
      at mx.containers::Accordion/headerClickHandler()[C:\autobuild\3.2.0\frameworks\projects\framework\src\mx\containers\Accordion.as:1690]


It occurs when I click on the "ABC Book" accordion item

Best Regards,
Todd
<!-- FIRST THE APPLICATION CODE -->

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 

	xmlns:filters="flash.filters.*" 

	xmlns:rs="com.rubenswieringa.book.*"

	xmlns:local="*"

	layout="absolute" 

	backgroundColor="#FFFFFF" 

	creationComplete="onCreationComplete()" 

	xmlns:flexlib="http://code.google.com/p/flexlib/"

	xmlns="*">    
 

	<mx:Style source="SiteMockup.css"/>
 

	<mx:Script>

        <![CDATA[

            // Import the PopUpManager.

            import mx.core.IFlexDisplayObject;

			import mx.collections.ArrayCollection;

			import mx.utils.ArrayUtil;

			import mx.controls.Alert;

            import flash.geom.Point;

            import mx.events.MenuEvent;

            import mx.controls.menuClasses.MenuBarItem;

	        import mx.controls.Image;

	        import mx.utils.ObjectUtil;

	        import mx.events.ValidationResultEvent;

	        import mx.utils.StringUtil;

        

	        [Bindable]

	        private var curDoc:String; 

	        private var pages:Array;

            private var point1:Point = new Point();
 

	        [Bindable]

			public var navData:ArrayCollection;

			public var index:int=-1;

			public var description:String;

			public var image:*;

			public var title:String;

			

			private function setCurrentDoc(document:String, page:int):void {

				curDoc = document;

				hSlider.value = 0;
 

				this.goToBook(document, page);

			}
 

			private function getCurrentDoc():String {

				return curDoc;

			}

      

			private function menuChange(event:MenuEvent):void {

				var strData:String = event.item.@data;

				

				this.setCurrentDoc(strData, 0);

            }

            

           private function onCreationComplete():void {

           		this.setCurrentDoc("def", 0);

           }

           

           private function turnPage(pageNumber:int):void {

           		var book:String = this.getCurrentDoc();

           		

				if (book == "abc")

					myabcBook.gotoPage(pageNumber - 1, false);
 

           }

           

            public function menuClick(doc:String, page:int):void {

				this.setCurrentDoc(doc, page);

            }           

            

            public function bookPageTurned(book:String):void {

				if (this.getCurrentDoc() != book)

					this.setCurrentDoc(book, 0);

					

				if (book == "def")

                	hSlider.value = mydefBook.currentPage;

										

            }

            

            private function goToBook(book:String, page:int):void {

            	

				if (book == "abc") {

	               	myViewStack.selectedIndex = 1;

	         		myabcBook.gotoPage(page, false);

	   			}	

            }

	

			private function headerClicked(item:int):void {

				if (item == 1)

					this.setCurrentDoc("abc", 0);

			}

            

        ]]>

    </mx:Script>
 

	<mx:VBox backgroundColor="#FFFFFF" verticalGap="0">

		<mx:Canvas backgroundColor="#FFFFFF">

			<mx:HBox horizontalGap="0"> 

				<mx:Image source="resources/GlobalPrime/SiteHeader2.JPG" width="870" height="120"/>

			</mx:HBox> 

		</mx:Canvas>

		<mx:Spacer height="10"/>

		<mx:VBox>

			<mx:HBox width="100%" backgroundColor="#FFFFFF">

				<mx:VBox>

					<mx:Panel title="Document List" width="203" height="592">

				        <mx:Accordion id="accordion" width="199" change="headerClicked(accordion.selectedIndex);">

				            <mx:VBox label="First Book">

				                <mx:Label text="First Link" selectable="true" click="menuClick('def', 4);" color="#0000FF" useHandCursor="true" mouseChildren="false" buttonMode="true" mouseEnabled="true"/>

				                <mx:Label text="Second Link" selectable="true" click="menuClick('def', 4);" color="#0000FF" useHandCursor="true" mouseChildren="false" buttonMode="true" mouseEnabled="true"/>

				            </mx:VBox>

				            <mx:VBox label="ABC Book">

				                <mx:Label text="Link One" selectable="true" click="menuClick('abc', 0);" color="#0000FF" useHandCursor="true" mouseChildren="false" buttonMode="true" mouseEnabled="true"/>

				                <mx:Label text="Link Two" selectable="true" click="menuClick('abc', 0);" color="#0000FF" useHandCursor="true" mouseChildren="false" buttonMode="true" mouseEnabled="true"/>

				            </mx:VBox>

				        </mx:Accordion>	

				    	<mx:Spacer height="20"/>

					</mx:Panel>

				</mx:VBox>

				<mx:Panel width="660" title="My Document">

					<mx:VBox>

						<mx:ViewStack id="myViewStack">

				            <mx:Canvas id="defCanvas">

								<local:defBook id="mydefBook" width="600" height="469" pageTurned="bookPageTurned('def');"/>

		        		    </mx:Canvas>

				            <mx:Canvas id="abcCanvas">

								<local:abcBook id="myabcBook" width="600" height="469" pageTurned="bookPageTurned('abc');"/>

		        		    </mx:Canvas>

						</mx:ViewStack>

						<mx:HSlider id="hSlider" minimum="0" maximum="10" value="0" dataTipPlacement="top" tickColor="black" snapInterval="2" tickInterval="2" labels="['Cover','Last Page']" allowTrackClick="true" liveDragging="true" change="turnPage(hSlider.value);" width="100%"/>

						<mx:Text text="Turn page by grabbing page with mouse, or sliding the slider to the desired page." width="100%" textAlign="center"/>

				  		<mx:Spacer height="20"/>

					</mx:VBox>

				</mx:Panel>

			</mx:HBox>

		</mx:VBox>

	</mx:VBox>

	

</mx:Application>
 
 
 
 

<!-- NEXT, THE TWO INCLUDE MXML FILES abcBook.MXML and defBook.MXML -->

<!-- abcBook.MXML -->

<?xml version="1.0" encoding="utf-8"?>
 

<rs:Book x="10" y="10" openAt="0" autoFlipDuration="600" easing="0.7" regionSize="150" 

	sideFlip="true" hardCover="false" hover="true" snap="false" 

	flipOnClick="true" xmlns:mx="http://www.adobe.com/2006/mxml" 

	xmlns:rs="com.rubenswieringa.book.*" > 

	

	<rs:Page><mx:Image source="@Embed('resources/bk_Page_01.png')"/></rs:Page>

	<rs:Page><mx:Image source="@Embed('resources/bk_Page_02.png')"/></rs:Page>

	<rs:Page><mx:Image source="@Embed('resources/bk_Page_03.png')"/></rs:Page>

	<rs:Page><mx:Image source="@Embed('resources/bk_Page_04.png')"/></rs:Page>

</rs:Book>
 
 

<!-- defBook.MXML -->

<?xml version="1.0" encoding="utf-8"?>
 

<rs:Book x="10" y="10" width="551" height="461" openAt="0" autoFlipDuration="600" easing="0.7" regionSize="150"

	sideFlip="true" hardCover="false" hover="true" snap="false" flipOnClick="true" xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:rs="com.rubenswieringa.book.*" >

	

	<rs:Page><mx:Image source="@Embed('resources/bk_Page_1.png')"/></rs:Page>

	<rs:Page><mx:Image source="@Embed('resources/bk_Page_2.png')"/></rs:Page>

	<rs:Page><mx:Image source="@Embed('resources/bk_Page_3.png')"/></rs:Page>

</rs:Book>

Open in new window

0
 
LVL 9

Expert Comment

by:danyul_c
ID: 24873385
The problem I see is in the Book component that there is no gotoPage function. Make sure the case is correct in the Book component (like goToPage) or something like that. Are you able to post the code for that?
0
 

Author Comment

by:ToddBPeterson
ID: 24873531
I'm using rubenswieringa's FlexBook component...  You'll see a namespace definition for it in the application tag "xmlns:rs="com.rubenswieringa.book.*""

The source is available at: http://www.rubenswieringa.com/code/as3/flex/Book/source/

It was working at one point...  I just don't know what I did to break it???  ;-)

Thanks for looking into this!

Best Regards,
Todd
0
 
LVL 9

Accepted Solution

by:
danyul_c earned 500 total points
ID: 24873671
ok I see that's all there and ok. So the only other thing I can think of would to be to set your viewstack creation policy to all.

<mx:ViewStack id="myViewStack" creationPolicy="all">

Maybe even the Canvas containers in there need it too.

Unfortunately this is all I can think of.
0
 

Author Closing Comment

by:ToddBPeterson
ID: 31604018
Nice going!!!  I had set the ViewStack creationPolicy to "all", based on what I read from another thread, but that didn't seem to work...  Your recommendation on setting it at the Canvas level seems to have worked!

Much appreciated!!!

Todd
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Video sharing with user login 3 198
Accessing Live Dynamic Stream 6 190
Adobe Presenter not Publishing Slide Theme 17 120
Flash Player Action Script Error 1090 5 197
I come across a lot of question about how to access things in the document class from a movieclip, or accessing something from a movieclip in the document class. It took me a while to figure this out but once I did it makes life so much easier. …
This article describes a solution to a problem of subloading one movie into another when they have different SWF versions. Sometime back, I was working on an ActionScript project while I came across an interesting fact which I would like to share…
The goal of the tutorial is to teach the user how to select the video input device. Make sure you have an input device that in connected and work and recognized by Adobe Flash Media Live Encoder and select it in the “video input” menu.
This Micro Tutorial will teach to how to utilize bit rate in Adobe Flash Media Live Encoder.

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now