Solved

Flex - Accessing App Properties From Included AS File

Posted on 2009-07-15
10
426 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Good to hear. I fear its simply because a variable is being called before it is initialised.
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:ToddBPeterson
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This is a very simple example to help those of you who are still migrating from AS2 to AS3 understand the redesigned event model in AS3. In AS2.0, event functions (that is, the function to be performed when an event is fired) were stored as a pro…
I know the transition can be hard. We got used to the ease of use ActionScript 2 had, but honestly, it became problematic later on, especially if designers were involved in the project and found it easy to add code as they saw fit. So, this artic…
In this tutorial viewers will learn how to create a basic motion tween animation in Flash Open a new document in Flash: Draw/import an image: Press CTRL + F8 to convert it into a graphic symbol: Select a frame (how long you want the tween to last): …
The goal of the tutorial is to teach the user how to live broadcast using Flash Media Live Encoder and connecting it to YouTube to broadcast. Log into your Youtube account, choose live stream settings, start live stream from Flash Media Live Enc…

744 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

13 Experts available now in Live!

Get 1:1 Help Now