Go Premium for a chance to win a PS4. Enter to Win


Flex - Accessing App Properties From Included AS File

Posted on 2009-07-15
Medium Priority
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,
Question by:ToddBPeterson
  • 5
  • 5

Expert Comment

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;

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.

Author Comment

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,

Expert Comment

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.
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.


Author Comment

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...


Expert Comment

ID: 24871894
Good to hear. I fear its simply because a variable is being called before it is initialised.

Author Comment

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,
<?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


Expert Comment

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?

Author Comment

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,

Accepted Solution

danyul_c earned 2000 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.

Author Closing Comment

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!!!


Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

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

This is intended to introduce all collision detection principles in flash, their strengths, weaknesses and workarounds. The main method for Collision Detection in flash is using hitTestObject. But unless you'll be pushing rectangular shapes without …
Recently, I was asked to recommend a tracking system to be implemented on a clients website. As the entire site was built on flash, my first thought was to suggest custom built tracking system. However, our company at that point of time didn't h…
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.
The goal of the tutorial is to teach the user how to use the auto adjust feature and what the different options do. When your video is not working right you can choose the auto adjust feature to help choose your settings.
Suggested Courses

782 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