• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 438
  • Last Modified:

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,
Todd
0
ToddBPeterson
Asked:
ToddBPeterson
  • 5
  • 5
1 Solution
 
danyul_cCommented:
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
 
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,
Todd
0
 
danyul_cCommented:
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
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

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

Thanks,
Todd
0
 
danyul_cCommented:
Good to hear. I fear its simply because a variable is being called before it is initialised.
0
 
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,
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
 
danyul_cCommented:
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
 
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,
Todd
0
 
danyul_cCommented:
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
 
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!!!

Todd
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

  • 5
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now