Flex - Accessing App Properties From Included AS File

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,
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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;

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.
ToddBPetersonAuthor Commented:
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,
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.
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

ToddBPetersonAuthor Commented:
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...

Good to hear. I fear its simply because a variable is being called before it is initialised.
ToddBPetersonAuthor Commented:
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,
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
	<mx:Style source="SiteMockup.css"/>
            // 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;
	        private var curDoc:String; 
	        private var pages:Array;
            private var point1:Point = new Point();
			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: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:Spacer height="10"/>
			<mx:HBox width="100%" backgroundColor="#FFFFFF">
					<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 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:Spacer height="20"/>
				<mx:Panel width="660" title="My Document">
						<mx:ViewStack id="myViewStack">
				            <mx:Canvas id="defCanvas">
								<local:defBook id="mydefBook" width="600" height="469" pageTurned="bookPageTurned('def');"/>
				            <mx:Canvas id="abcCanvas">
								<local:abcBook id="myabcBook" width="600" height="469" pageTurned="bookPageTurned('abc');"/>
						<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"/>
<!-- 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>
<!-- 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>

Open in new window

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?
ToddBPetersonAuthor Commented:
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,
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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ToddBPetersonAuthor Commented:
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!!!

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Adobe Flash

From novice to tech pro — start learning today.