We help IT Professionals succeed at work.

how to reload a flex module within the flex application?

CCBRONET
CCBRONET asked
on
1,522 Views
Last Modified: 2013-11-11
Was trying to do some data entry through my application the data gets loaded into the database the first time properly but not the second time....there seems to be some problem with a few variables set....would like to know if there is a way to reload the module upon reset or when data entered properly.....


Thanks In Advance....
Comment
Watch Question

Well we will gladly help you, but you have to give us some more detais for this.
You have a Flex application and that posts data to a server and that saves it in the database .... the fist time you do this, it works, the second fails? Is that correct. If yes, the error messages would be very interesting. If you haven't allreads done so, install the debug-flash-player ... it should be a little more verbouse.

Author

Commented:
Hey Christofer,
                        My MXML modules have alot of variables in them which do not get set back to its original state st the time of loading.....trying to find code to reload the module to its original.....usually the error i get in the debugger is the index out of bounds in the one of the functions....
Tried using the function below it does not reload the module but takes you to the main application page....

Thanks....
public function unloadModule():void 
{
var ref:URLRequest=new
URLRequest("javascript:location.reload(true)");
navigateToURL(ref,"_self"); 
}

Open in new window

ok ... so you are not talking abut unloading Modules (as this is possible too), what you are trying to do is to reload the entire application by simulating the user hitting F5. Am I correct? Well usually the Flash variables should be reset, but Flash has something similar to Cookies. They are called Local Shared Objects (http://en.wikipedia.org/wiki/Local_Shared_Object). If your application makes use of these, then this yould certainly be responsible for the effect you are experiancing.

Author

Commented:
Yes but we need the reload on the module not the application.....is there a way to do this....
thanks....

Author

Commented:
how can i find out if my app is using Local Shared Object (LSO)....
Well if you load a module (swf that is not runnable on its own), then flex loads it into its memory and after loading it can be instantiated. If you use the ModuleLoader (the simple mxml tag) that does both for you. I think you have no way to explicitly unload the module using that technique. If you want to have full control over yor modules, you have to utilize the ModuleManager class in ActionScript. Here you are provided with a ModuleInfo object that you can (and should) save and use to explicitly unload the module (Keep in mind that all existing instances of the module have to be removed from the stage/application first).

Have a look at this page ... it describes the loading/unloading of modules very well:
http://livedocs.adobe.com/flex/3/html/help.html?content=modular_5.html
Well If you are the Author ... look in your code ;-)
If you are using third-party stuff, Right-Click on the Application and select "settings" and the dialog should ask you how much data may be stored on the lokal system ... if you set that to "never" and refresh the page, you can be certain that it doesnt do local saving (Default is 100kb, I think)

Author

Commented:
Tried finding out if a LSO is generated using Better Privacy FireFox Plugin there is no cookie created.....
The LSO has nothing to do with Firefox and Cookies ... ist's completely dealt with by the Flash Player.

Author

Commented:
where do i write the code for module manager in the flex modules or application.....???
You have to put the code in the application ... as the code loads the module.

Author

Commented:
Here is the code in the application/stage.mxml do i need to remove the existing module loader that is there....

So onclick of a button that is present in one of my module i will need to call the module loader function in the stage.mxml is that right.....

Author

Commented:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application tabEnabled="false" tabChildren="true" xmlns:mx="http://www.adobe.com/2006/mxml" initialize="init()"  
	applicationComplete="registerGlobalKeyHandler()"  layout="absolute" width="100%" height="100%" 
	xmlns:model="com.citizen.cbs.model.*" xmlns:utils="flexed.utils.timeout.*">

<mx:RemoteObject id="initInfoUCFlexRO" destination="initInfoUCFlexRO">
	<mx:method name="getInitInfo" result="handleGetInitInfoResult(event)" fault="handleGetInitInfoFault(event)" />
</mx:RemoteObject>
<mx:RemoteObject id="mainMenuUCFlexRO" destination="mainMenuUCFlexRO">
	<mx:method name="getXMLDocument" result="handlegetXMLDocumentResult(event)" fault="handlegetXMLDocumentFault(event)"/>
</mx:RemoteObject>
<mx:RemoteObject id="branchDetailsUCFlexRO" destination="branchDetailsUCFlexRO">
	<mx:method name="read" result="handleReadResult(event)" fault="handleReadFault(event)"/>
</mx:RemoteObject>

<mx:Script>
	<![CDATA[
		import mx.controls.RadioButton;
		import mx.events.CloseEvent;
		
		import flexed.utils.timeout.*;
		import mx.core.EdgeMetrics;
		import mx.core.Container;
		import com.citizen.cbs.vo.ApplicationInitInfo;
		import com.citizen.cbs.CitizenApplication;
		import mx.rpc.events.FaultEvent;
		import mx.rpc.events.ResultEvent;
		import mx.modules.IModuleInfo;
		import mx.modules.ModuleManager;
		import mx.events.ModuleEvent;
		import mx.controls.Alert;
		import mx.managers.CursorManager;
		import mx.events.DynamicEvent;
		
		private var info:IModuleInfo = null;
		
		[Bindable]
		private var XMLDocument:XML; 
		[Bindable]
		private var branchCode:int;
		
		//passed to the component as value of onTimeOut attribute
			private function onTimeOutHandler(e:Event=null):void
			{
				Alert.show("The Client has been timed out due to inactivity","Timeout Message by Method call",(Alert.OK),this,autoLogout);
			}
			
			private function autoLogout(event:CloseEvent):void{
				if(event.detail==Alert.OK){
					
				}
				var str:String="/citizenProject/LogoutServlet";
				//var jscommand:String = "window.open('"+str+"','win','toolbar=no,scrollbars=yes,resizable=1');";
				var url:URLRequest = new URLRequest(str);
				navigateToURL(url, "_self");
			}
			
			
			//Fired when the appTimedOut event occurs in the component
			private function appTimedOutHandler(devent:DynamicEvent):void{
				var expiryTime:String = devent.expiryTime.toString();
				//Alert.show("The Client has been timed out at "+expiryTime,"Timeout Message by Event trigger");
			}
			
			
				
		private function init():void {
			//initInfoUCFlexRO.getInitInfo();
			branchDetailsUCFlexRO.read();
			
			
			
		}
		
		public function unloadModule():void {
			var ref:URLRequest=new URLRequest("javascript:location.reload(true)");
			navigateToURL(ref,"_self");  
			treeBox.percentWidth = 25;
			treeBox.enabled = true;
			treeBox.visible = true;
			formLoader.unloadModule();
			
		}
		private function handleGetInitInfoResult(event:ResultEvent):void {
	
			CitizenApplication.initInfo = ApplicationInitInfo(event.result);
			var user:String = CitizenApplication.initInfo.registeredUser.uamCode;
			mainMenuUCFlexRO.getXMLDocument(branchCode, user);
		}
		
		private function handleGetInitInfoFault(event:FaultEvent):void {
			Alert.show("Error in Getting Init Info : " + event.fault.faultString);
		}
		
		private function handlegetXMLDocumentResult(event:ResultEvent):void
		{
			XMLDocument = event.result as XML;
		}
		
		private function handlegetXMLDocumentFault(event:FaultEvent):void
		{
			Alert.show("Error In Getting XML Document: "+event.fault.faultString,"ERROR!!!!");
		}
		
		private function handleReadResult(event:ResultEvent):void
		{
			branchDetailsVO = BranchDetails(event.result);
			branchCode = branchDetailsVO.bdBranchNo;
			initInfoUCFlexRO.getInitInfo();
		
		}
		private function handleReadFault(event:FaultEvent):void{
			Alert.show(event.fault.faultString);
		}
		
		private function loadModule(selectedItem:Object):void 
		{
			var moduleToOpen:String = selectedItem.@data;            /* ******* */
			if (moduleToOpen.length == 0) {
				return;
			}
			
			var parameters:String = selectedItem.@parameters;
			var allParameters:Array = parameters.split(",");
			CitizenApplication.menuParameters  = new Object();
			for (var i:int = 0; i < allParameters.length; i++) {
				var parameter:String = allParameters[i];
				CitizenApplication.menuParameters[parameter.split("=")[0]] = parameter.split("=")[1];
			}
			var moduleurl:String = moduleToOpen+'?'+Math.random();
			formLoader.url = moduleurl;
			//Alert.show("URL: "+moduleurl,"Message!!!!");
			formLoader.loadModule();
			treeBox.enabled = false;
			treeBox.visible = false;
			treeBox.percentWidth = 0;
		}
		
		private function moduleEventHandler(event:ModuleEvent):void {
			moduleCanvas.addChild(info.factory.create() as DisplayObject);
		}
		
		private function handleModuleLoaderError(event:ModuleEvent):void {
			trace(event.errorText  + " - " + event.bytesLoaded + " -- " + event.bytesTotal + " -- " + event.module);
			
		}
		private function reloadpage(event:ModuleEvent):void
		{
			var ref:URLRequest=new URLRequest("javascript:location.reload(true)");
			navigateToURL(ref,"_self");
		}
			public var rBtn:RadioButton;
			public function registerGlobalKeyHandler() :void
			{
				stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
				stage.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, makeFocusedItemVisible);
				stage.addEventListener("appTimedOut",appTimedOutHandler);
			}
			
	
			
			public function handleKeyDown(event:KeyboardEvent) :void
			{
				/* display.text = "Key was pressed: " + event.keyCode;
				display1.text = "CtrlKey was pressed: " + event.ctrlKey;
				display2.text = "AltKey was pressed: " + event.altKey;
				display3.text = "Key Location: " + event.keyLocation;
				er.text="Key Location: " + event.target.toString(); */
				if ((event.ctrlKey && (event.keyCode == 65 || event.keyCode == 67 || event.keyCode == 86 || event.keyCode == 88))
				|| event.keyCode == 116 || event.keyCode == 18 || event.keyCode == 115)
				{
					Alert.show("Not Allowed","Warning")
					return void(0);
				}
				/* else if (event.keyCode == 113)
				{
					Alert.show("Report","Enjoy ShortCut Keys v0.0");
					formLoader.url = "data=com/citizen/cbs/modules/parameters/UserAccessMain.swf";
					formLoader.loadModule();
				} */
			
			}
			
			
			public function makeFocusedItemVisible(event:FocusEvent):void {
            // Target is the actual object that has focus.
            var target:InteractiveObject = InteractiveObject(event.target);
            
            // OriginalTarget is the component that has focus as some
            // component actually delegate true focus to an internal object.
            var originalTarget:InteractiveObject = 
        InteractiveObject(focusManager.findFocusManagerComponent(target));
    
            // The viewable portion of a container
            var viewport:Rectangle = new Rectangle();
            do {
                // Cycle through all parents looking for containers.
                if (target.parent is Container) {
                    var viewportChanged:Boolean = false;
                    var c:Container = target.parent as Container;

                    // Get the viewable area in the container.
                    var vm:EdgeMetrics = c.viewMetrics;
                    viewport.x = vm.left;
                    viewport.y = vm.top;
                    viewport.width = 
                        c.width / c.scaleX - vm.left - vm.right;
                    viewport.height = 
                        c.height / c.scaleY - vm.top - vm.bottom;
                    
                    // Calculate the position of the target in the container.
                    var topLeft:Point = new Point(0, 0);
                    var bottomRight:Point = 
                new Point(originalTarget.width, originalTarget.height);
                    topLeft = originalTarget.localToGlobal(topLeft);
                    topLeft = c.globalToLocal(topLeft);
                    bottomRight = originalTarget.localToGlobal(bottomRight);
                    bottomRight = c.globalToLocal(bottomRight);
    
                    // Figure out if we have to move the scroll bars.
                    // If the scroll bar moves, the position of the component
                    // moves as well. This algorithm makes sure the top
                    // left of the component is visible if the component is
                    // bigger than the viewport.
                    var delta:Number;

                    if (bottomRight.x > viewport.right) {
                        delta = bottomRight.x - viewport.right;
                        c.horizontalScrollPosition += delta;
                        topLeft.x -= delta;
                        viewportChanged = true;
                    }

                    if (topLeft.x < viewport.left) {
                        // leave it a few pixels in from the left
                        c.horizontalScrollPosition -= 
                            viewport.left - topLeft.x + 2;
                        viewportChanged = true;
                    }
                    
                    if (bottomRight.y > viewport.bottom) {
                        delta = bottomRight.y - viewport.bottom;
                        c.verticalScrollPosition += delta;
                        topLeft.y -= delta;
                        viewportChanged = true;
                    }
                    
                    if (topLeft.y < viewport.top) {
                        // leave it a few pixels down from the top
                        c.verticalScrollPosition -= 
                            viewport.top - topLeft.y + 2;
                        viewportChanged = true;
                    }
                    
                    // You must the validateNow() method to get the 
                    // container to move the component before working 
                    // on the next parent.
                    // Otherwise, your calculations will be incorrect.
                    if (viewportChanged) {
                        c.validateNow();
                    }
                }
                
                target = target.parent;
            }
            
            while (target != mx.core.Application.application && target.parent);
        }

		
	]]>
</mx:Script>
<utils:ClientIdleTimeOut id="myTimeOut" onTimeOut="onTimeOutHandler" listenKeyStroke="true" listenMouseMove="true" 
	timeOutInterval="5" confirmInterval="5"/>
<model:BranchDetails id="branchDetailsVO"/>
<mx:XML id="mainMenu" source="/assets/xml/mainmenu.xml" format="xml"/> 
	<mx:DateFormatter id="df" formatString="DD-MM-YYYY" />
	<mx:ApplicationControlBar horizontalAlign="center" width="90%" x="60" y="0">
		<!--<mx:MenuBar   dataProvider="{mainMenu}" labelField="@label" showRoot="false"  itemClick="loadModule(event.item)" />-->
		<mx:Label text="Ver No.:0.1" fontWeight="bold" fontSize="10" color="#FF0000"/>
		<!--<mx:MenuBar     dataProvider="{mainMenu}" labelField="@label" showRoot="false"  itemClick="loadModule(event.item)" />-->
		<mx:Spacer width="100%" />
		<mx:Text fontWeight="bold" text="{CitizenApplication.initInfo.registeredUser.branchDetails.bdBankName}"  styleName="appctrl"/>
		<mx:Text fontWeight="bold" text="-"  styleName="appctrl"/>
		<mx:Text fontWeight="bold" text="{CitizenApplication.initInfo.registeredUser.branchDetails.bdBranchName.toUpperCase()}"  styleName="appctrl"/>
		<mx:Text fontWeight="bold" text="BRANCH"  styleName="appctrl"/>
		<mx:Spacer width="100%" />
		<mx:Text fontWeight="bold" text="{CitizenApplication.initInfo.registeredUser.uamName}"  styleName="appctrl"/>
		<mx:Text fontWeight="bold" text="|"  styleName="appctrl"/>
		<mx:Text fontWeight="bold" text="{df.format(CitizenApplication.initInfo.registeredUser.branchDetails.bdCurrentWorkingDt)}"  styleName="appctrl"/>
	</mx:ApplicationControlBar>
	<mx:HDividedBox id="divBox" width="100%" height="100%" shadowDirection="center" resizeToContent="true" liveDragging="true" horizontalGap="10" x="0" y="34">
	    <mx:VBox width="274" id="treeBox" borderStyle="solid" borderColor="#6699CC"><mx:Tree backgroundColor="#000000" color="#FFFFFF" width="100%" height="100%" id="treeMenu" dataProvider="{mainMenu}" labelField="@label" showRoot="false" 
	    		itemClick="loadModule(treeMenu.selectedItem)"/>
	    	<!--<mx:Tree backgroundColor="#000000" color="#FFFFFF" width="100%" height="100%" id="treeMenu" dataProvider="{XMLDocument}" labelField="@label" showRoot="false" 
	    		itemClick="loadModule(treeMenu.selectedItem)"/>-->
	    </mx:VBox>
	  	<mx:Canvas id="moduleCanvas" width="100%" height="100%" styleName="mmc"> 
		 <mx:ModuleLoader backgroundColor="#000000" color="#FFFFFF" error="handleModuleLoaderError(event)" 
		 	updateComplete="treeMenu.height = moduleCanvas.height-2" loading="CursorManager.setBusyCursor()"  
		 	useHandCursor="true"   ready="CursorManager.removeBusyCursor()" autoLayout="true"   
		 	verticalAlign="middle" horizontalAlign="center" id="formLoader" width="100%" height="100%" />
  		</mx:Canvas>
	</mx:HDividedBox>
	<mx:Style source="CbsDesignFinal.css"/>
</mx:Application>

Open in new window

This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
That's great man will look into it and let you know how it goes.....


Thanks....

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.