[카테고리:] AS3

  • URLNavigator class.

    /**
     * URLNavigator
     *
     * The URLNavigator class extends the Flash built-in method, navigateToURL.
     * This class copies the Firefox browser's link-click action.
     * If you click on a link with the "Ctrl" key held down, the link will be opened in a new window or a new tab, depend on the browser's settings.
     * Or Flash Player tries to download the url, if the "Alt" key is held down.
     *
     * @author: Han Sanghun (http://hangunsworld.com, hanguns@gmail.com)
     * @created: 2008 04 04
     * @last modified: 2008 04 04
     *
     * Modify Histories
    */
    
    
    package com.hangunsworld.net{
    	
    	import	flash.net.navigateToURL;
    	import	flash.net.URLRequest;
    	
    	import	com.hangunsworld.net.Downloader;
    	
    	
    	public class URLNavigator{
    		
    		// Downloader object.
    		var dloader:Downloader;
    		
    		/**
    		 * Constructor function.
    		 */
    		public function URLNavigator(){
    			dloader = new Downloader();
    		}// end constructor
    		
    		/**
    		 * Handles the URL depending on the properties provided.
    		 *
    		 * @param ur An URLRequest object.
    		 * @param target A String value specifies the target window. [OPTIONAL]
    		 * @param ctrlkey A Boolean value indicates whether the "Ctrl" key is held down. [OPTIONAL]
    		 * @param altkey A Boolean value indicates where the "Alt" key is held down. [OPTIONAL]
    		 */
    		public function navigateToURL(ur:URLRequest, target:String="_self", ctrlkey:Boolean=false, altkey:Boolean=false):void{
    			
    			if(ctrlkey){
    				
    				// If "Ctrl" key is held down,
    				// opens the URL in a new window or a new tab, depend on the browser's settings.
    				flash.net.navigateToURL(ur, "_blank");
    				
    			}else if(altkey){
    				
    				// If "Alt" key is held down,
    				// downlaods the URL via a Downloader object.
    				dloader.downloadURL(ur);
    				
    			}else{
    				
    				// Otherwise, opens the URL in the window specified by the "target" parameter.
    				flash.net.navigateToURL(ur, target);
    				
    			}
    			
    		}// end navigateToURL
    		
    	}// end class
    	
    }// end package

    Usage sample code.

    import	com.hangunsworld.net.URLNavigator;
    
    stage.addEventListener(MouseEvent.CLICK, clickListener);
    
    
    var un:URLNavigator = new URLNavigator();
    
    function clickListener(e:MouseEvent):void{
    	
    	var url:String = "http://hangunsworld.com/blog";
    	var ur:URLRequest = new URLRequest(url);
    	
    	un.navigateToURL(ur, "_self", e.ctrlKey, e.altKey);
    	
    }

    You can download the class file here.

  • Downloader class was modified.

    Downloader 클래스의 패키지를 com.hangunsworld.util 에서 com.hangunsworld.net 으로 변경하였습니다. 아무래도 util 보다는 net 패키지에 있는 것이 더 적당한 것 같아서요.

    그리고 addEventListener, removeEventListener 메소드를 추가하여, 다운로드 프로그래스, 완료, 취소 등 이벤트들을 사용할 수 있습니다.

    Downloader class has been moved from com.hangunsworld.util to com.hangunsworld.net. I think the net is the appropriate package rather than the util.

    And I added addEventListener and removeEventListener methods. Now you can monitor the download progress or get comepete event, and so on.

    Downloadクラスを com.hangunsworld.util から com.hangunsworld.net に移動しました。なぜならuitlよりnetクラスの方が相応しそう。

    また、addEventListenerとremoveEventListenerメソッドを追加しました。ダウンロードプログレス、完了、キャンセルイベントを含め、色んなイベントを使えます。

  • The XMLLoader class has been revised.

    기존에 try…catch 구문을 이용해서 만들었던 XMLLoader(XMLLoaderOld로 변경)는 몇 가지 문제점들을 포함하고 있었습니다. Wooyaggo님이 URLStream 객체를 사용하여 만든 XMLLoader 클래스를 보고서 저도 URLStream 객체를 사용하도록 수정해 보았습니다.

    XMLLoader 파일 다운로드

    그런데 이벤트 관련해서 이런식으로 사용하는 것이 옳은 것인지 모르겠네요. 많은 지적 부탁드립니다.

    /**
     * XMLLoader
     * XMLLoader class loads an external text file and decodes the data with the provided character set.
     * If you loads a text file encoded in the euc-kr encoding via an URLLoader, frequently, the source data is currupted.
     * To avoid this problem, uses URLStream instead of URLLoader.
     *
     * XMLLoader is the modified version of the XMLLoaderOld class.
     * This code is inspired by Wooyaggo's article(http://wooyaggo.tistory.com/116).
     * 
     *
     * @author: Han Sanghun (http://hangunsworld.com, hanguns@gmail.com)
     * @created: 2008 03 28
     * @last modified: 2008 06 06
     */
     
     /*
    Licensed under the MIT License
    
    Copyright (c) 2008 Han Sanghun
    
    Permission is hereby granted, free of charge, to any person obtaining a copy of
    this software and associated documentation files (the "Software"), to deal in
    the Software without restriction, including without limitation the rights to
    use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
    the Software, and to permit persons to whom the Software is furnished to do so,
    subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
    FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
    COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
    IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
    CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    
    http://hangunsworld.com/classes/com/hangunsworld/net/
    */
    
    package com.hangunsworld.net{
    	
    	import	flash.events.*;
    	import	flash.net.URLLoader;
    	import	flash.net.URLRequest;
    	import	flash.net.URLStream;
    	
    	
    	public class XMLLoader{
    		
    		private var us:URLStream;
    		private var ul:URLLoader;
    		private var ur:URLRequest;
    		
    		private var encode:String;
    		
    		public var data:String = "";
    		
    		
    		/**
    		 * XMLLoader constructor
    		 */
    		public function XMLLoader(){
    			
    			us = new URLStream();
    			ul = new URLLoader();
    			
    		}// end constructor
    		
    		
    		/**
    		 * Adds event listeners to the URLLoader object and the URLStream object.
    		 */
    		public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void{
    			ul.addEventListener(type, listener, useCapture, priority, useWeakReference);
    			us.addEventListener(type, agentListener, useCapture, priority, useWeakReference);
    		}// end addEventListener
    		
    		/**
    		 * Removes event listeners from the URLLoader object and the URLStream object.
    		 */
    		public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void{
    			ul.removeEventListener(type, listener, useCapture);
    			us.removeEventListener(type, agentListener, useCapture);
    		}// end removeEventListener
    		
    		
    		/**
    		 * Loads external data via the URLStream object,
    		 * and sets the character set with the provied string.
    		 *
    		 * @param pUr The URLRequest object.
    		 * @param pEncode The string denoting the character set to use to interpret the bytes. [OPTIONAL]
    		 */
    		public function load(pUr:URLRequest, pEncode:String="utf-8"):void{
    			
    			encode = pEncode;
    			
    			ur = pUr;
    			us.load(ur);
    			
    		}// end load
    		
    		
    		/**
    		 * Dispatches events through the URLLoader object.
    		 */
    		private function agentListener(e):void{
    			
    			if(e.type == Event.COMPLETE){
    				// If the event's type is Event.COMPLETE, decodes the loaded data using the provided character set.
    				var str:String = us.readMultiByte(us.bytesAvailable, encode);
    				// Puts the decoded data into the URLLoader object.
    				data = str;
    				ul.data = str;
    			}
    			
    			ul.dispatchEvent(e.clone());
    			
    		}// end agentListener
    		
    		
    	}// end class
    }// end package

    Usage example.

    import	com.hangunsworld.net.XMLLoader;
    
    var xloader:XMLLoader = new XMLLoader();
    
    xloader.addEventListener(Event.COMPLETE, loaded);
    xloader.addEventListener(IOErrorEvent.IO_ERROR, errored);
    xloader.addEventListener(ProgressEvent.PROGRESS, progressed);
    
    xloader.load(new URLRequest(path), "euc-kr");
    
    
    function loaded(e:Event):void{
    	trace("COMPLETE");
    	var xml:XML = new XML(xloader.data);
    	trace(xml);
    }
    
    function errored(e:IOErrorEvent):void{
    	trace("IOERROR");
    }
    
    function progressed(e:ProgressEvent):void{
    	trace("PROGRESS - " + e.bytesTotal + " : " + e.bytesLoaded);
    }
  • XMLLoader, a custom class.

    I devised the XMLLoader class to avoid the URLLoader bug that I posted on FlaLab.com.
    Related links
    예전에 FlaLab에 올렸던 URLLoader의 버그를 회피하기 위해서 만든 XMLLoader 클래스 입니다.
    참고 링크
    私がFlaLab.comに書いたURLLoaderのバーグを回避するためにXMLLoaderクラスを作りました。
    参考リンク

    http://www.flalab.com/phpBB2/viewtopic.php?t=1791
    http://www.flalab.com/phpBB2/viewtopic.php?t=2228

    /**
     * XMLLoader
     *
     * XMLLoader class loads and validates an XML file.
     * If you loads a text file encoded in the euc-kr encoding via an URLLoader, frequently, the source data is currupted.
     * To avoid this problem, parses the loaded data into an XMLDocument,
     * then, parses the first node of the XMLDocument into an XML.
     * If an error has been occured, reloads the XML data.
     * 
     *
     * @author: Han Sanghun (http://hangunsworld.com, hanguns@gmail.com)
     * @created: 2008 02 28
     * @last modified: 2008 02 29
     */
    
    
    package com.hangunsworld.as3.net{
    	
    	import	flash.events.*;
    	import	flash.net.*;
    	import	flash.utils.Timer;
    	import	flash.xml.*;
    	
    	
    	public class XMLLoader{
    		
    		
    		private var path:String;
    		private var returnFunction:Function;
    		private var errorFunction:Function;
    		
    		private var timer:Timer;
    		private var xml:XML;
    		
    		private var xml_ul:URLLoader;
    		private var xml_ur:URLRequest;
    		private var xml_uv:URLVariables;
    		
    		/**
    		 * XMLLoader constructor
    		 *
    		 * @param pPath A path of an XML file
    		 * @param okFunc A function to call when the XML is loaded successfully
    		 * @param errorFunc A function to call when an IOError has occured
    		 */
    		public function XMLLoader(pPath:String, okFunc:Function=null, errorFunc:Function=null){
    			
    			path = pPath;
    			returnFunction = okFunc;
    			errorFunction = errorFunc
    			
    			XML.ignoreWhitespace = true;
    			XML.ignoreComments = true;
    			
    			
    			// Initializes NET objects
    			xml_ul = new URLLoader();
    			xml_ul.addEventListener (Event.COMPLETE, xmlCompleteListener);
    			xml_ul.addEventListener (IOErrorEvent.IO_ERROR, errorListener);
    			
    			xml_ur = new URLRequest();
    			xml_ur.url = path;
    			
    			xml_uv = new URLVariables();
    			
    			
    			// Initializes Timer object
    			timer = new Timer(50, 1);
    			timer.addEventListener(TimerEvent.TIMER, timerListener);
    			
    			timer.start();
    
    			
    		}// end constructor
    		
    		
    		/**
    		 * Timer EventListener
    		 * Loads an XML file after some time
    		 */
    		private function timerListener(evt:TimerEvent):void{
    			loadXML();
    		}// end timerListener
    		
    		
    		/**
    		 * Loads an XML file
    		 */
    		private function loadXML():void{
    			
    			if(path.indexOf("?") >= 0){
    				// If the url already contains parameters, attaches the random seed to the end of the url
    				xml_ur.url = path + "&randomSeed=" + Math.floor(Math.random() * 1000000);
    			}else{
    				// If the url does not contain parameters, uses an URLVariable object
    				xml_uv.randomSeed = Math.floor(Math.random() * 1000000);
    				xml_ur.data = xml_uv;
    			}
    			
    			xml_ul.load (xml_ur);
    			
    		}// end loadXML
    		
    		
    		/**
    		 * XML Complete EventListener
    		 */
    		private function xmlCompleteListener(evt:Event):void{
    			
    			// Sets the defualt parse state to false
    			var parsed:Boolean = false;
    			
    			var str:String = evt.target.data;
    			
    			var xmldoc:XMLDocument = new XMLDocument();
    			xmldoc.ignoreWhite = true;
    			
    			try{
    				
    				// Parses the loaded data into an XMLDocument
    				xmldoc.parseXML(str);
    				
    				// Gets a string from the first node of the XMLDocument
    				str = xmldoc.firstChild.toString();
    				
    				// Parses the string into an XML
    				xml = new XML(str);
    				
    				// If no error has occured, sets the parse stae to true
    				parsed = true;
    				
    			}catch(e){
    				
    				// If an error occured, loads the XML again
    				timer.start();
    				
    			}// end try catch
    			
    			
    			// If the parse process done without errors and the returnFunction is NOT null, returns the XML data
    			if(parsed){
    				if(returnFunction != null){
    					returnFunction(xml);
    				}
    			}
    			
    			
    		}// end xmlCompleteListener
    		
    		/**
    		 * XML IOError EventListener
    		 */
    		private function errorListener(evt:IOErrorEvent):void{
    			
    			if(errorFunction != null){
    				errorFunction(evt);
    			}
    			
    		}// end xmlErrorListener
    		
    		
    	}// end class
    	
    }// end package
    import	com.hangunsworld.as3.net.XMLLoader;
    
    var xloader:XMLLoader;
    xloader = new XMLLoader(xmlPath, xmlLoaded, xmlErrorListener);
    
    function xmlLoaded(xx:XML):void{
    	// xml loaded
    }
    
    function xmlErrorListener(evt:IOErrorEvent):void{
    	trace("xml load error");
    }