Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    Flash




Web Service Question With Custom Event



Ok,I have two files I am working with.(My Custom AS Class,and the core flash movie that will use this file).I am connecting to a webservice using my AS Class known as MyWebUtility .In the MyWeb Utility class I have a custom event known as DataFilled.THis is used when the service is returned so I can retrieve data back to the core application.I have debugged this with a trace statement and the event is fired from the core but I do not get data returned from my custom event property called XMLData...Is there a better way to do this or what can I do to create this to work.My problem is that the function result is an asyn function that fires and the core code needs the return value...... That is why I wrote a custom event to caputre when the result function(CUstom Class) is fired.As I metioned it fires and the results are available when I use trace but they do not get populated to my custom property of my event .Attach Code/**Web Utilties Classauthor: Allen Lewisversion 1.0This code defines a custom web utilities class that allows you to easy return values from a web service*/import mx.data.components.WebServiceConnector;import mx.events.EventDispatcher;class MyWebUtility{//private instance variablesprivate var __serviceURL:String;private var __method:String;private var __xmlResult:String;//declare the dispatchEvent, addEventListener and removeEventListener methods that EventDispatcher uses (Step2) function dispatchEvent() {}; function addEventListener() {}; function removeEventListener() {};//constructorpublic function MyWebUtility(p_url:String,p_serviceMethod:String){this.__serviceURL=p_url;this.__method=p_serviceMethod;// send instance of self to the Event Dispatcher mx.events.EventDispatcher.initialize(this);}public function get ServiceURL():String{return this.__serviceURL;}public function set ServiceURL(value:String):Void{this.__serviceURL=value;}public function get XMLResults():String{return this.__xmlResult;}public function CreateService():Void{var stat:Function = function (error:Object) {switch (error.code) {case 'InvalidParams' :trace("Unable to connect to remote Web Service: "+error.code);break;case 'StatusChange' :break;default :trace("Error: "+error.code);break;}};var wsConn:WebServiceConnector = new WebServiceConnector();wsConn.addEventListener("result",result);wsConn.addEventListener("status", stat);wsConn.WSDLURL = this.__serviceURL;wsConn.operation = this.__method;wsConn.params = ["Flash"];wsConn.trigger();}function result (evt:Object){var eventObject:Object = {target:this, type:'DataFilled'}; // any optional properties eventObject.XMLData = evt.target.results;trace(eventObject.XMLData);//dispatch the event dispatchEvent(eventObject)}}//end class/**************************************CORE FLASH MOVIE CODE***********************************************************import MyWebUtility;var ws:MyWebUtility=new MyWebUtility("http://www.flash-mx.com/mm/tips/tips.cfc?wsdl","getTipByProduct");// new object we can use for a listenervar myListnerObj:Object = new Object; // method definition for the DataFilled eventmyListnerObj.DataFilled = function(evtObj) {//trace("This is the XML prop: "+ evtObj.XMLData);trace("This is the event type: "+ evtObj.type);trace("This is the event target: "+ evtObj.target);}function showIT(evtObj:Object){trace("This is the event type: "+ evtObj.type);trace("This is the event target: "+ evtObj.target);}// subscribe myListnerObj to resultsObjectws.addEventListener("DataFilled",showIT);//myListnerObj);//Create Service and Fire Eventws.CreateService();



Adobe > ActionScript 1 and 2
Posted on: 11/10/2006 05:43:36 AM


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread

Including Web Service Classes In A Custom Class?
Hi all,

does anyone know how I'd add the Web Services classes to a custom class I'm creating myself?

I've created my class, and basically I have a method that I want to go away and do web service calls; but in order to do this I need the classes normally included with:

mx.services.*

Any idea how I can add all these and make use of them in my method? I can't extend my class to include all of them, as you can only extend one class. I also can't do a "import mx.services.*;" in the method as Flash won't permit it.

Please help!

Custom Event Handlers - Triggering Event Listeners On Other Objects
I'm trying to update an object whenever something happens in another object. At the moment, I have the second object explicitly calling an update function on the first object, but this seems a little sloppy and it strikes me that this is the sort of scenario where I should be using custom event handlers.

I'm not quite sure how they work though. My first assumption is that if I built two objects, one like this which fires off an event:


Code:
public class eventFirer extends Sprite
{

public function eventFirer():void
{
dispatchEvent(new Event("customEvent"));
}
}
...and one like this which updates whenever the custom event happens:


Code:
public class eventListener extends Sprite
{

public function eventListener():void
{
trace ("main");
addEventListener("customEvent", eventFired);
}

private function eventFired(e:Event):void
{
trace ("ok");
}
}
...then eventListener.eventFired would automatically be set off whenever a new eventFirer is created. This seems not to be the case though.

Can anybody enlighten me as to how custom events bubble between otherwise unrelated objects?

Custom Tabbed Menu Needing Custom Event?
Hi everyone,

I managed to solve my flash asset problem I was having last week and successfully created a for loop to loop through an array and make me my animated tabbed menu.

A brief explanation of what's happening... I have built an animated tab (animated with AS3 tweening) so when a user rolls mouse over it makes the tab image pop up from below the text then on roll out it makes the tab image drop back down again.

What I'm trying to achieve is when user clicks on tab it will keep the tab image behind it, but when the user clicks another tab it runs the animation that drops the currently selected and maintains the one just clicked.

current creation code is below.


Code:
// create main menu tab components
for (var i:int = 0; i < menuArray.length; i++)
{
var menuTab:MainMenuTab = new MainMenuTab();

tabContainer.addChild(menuTab);
menuTab.x = i * 106;
menuTab.setLabelText(menuArray[i]);

// event listeners
menuTab.addEventListener(MouseEvent.CLICK, tabClickHandler);
What is happening is I make an instance of menuTab then add it to the 'tabContainer' which is a standard flex canvas on the stage, it then obviously assigns the spacing, sets the label (public function inside flash swc). The click handler is then added which runs a public function inside the flash symbol to get the tab to stick to the top and not drop down.

Now I really can't get my head around how to get the tabs I'm not clicking on to respond to the click. I can obviously get the one I am clicking on to repond no problem by going through 'event.currentTarget' but I need to also tell the rest of them to check to see if they are currently selected, if they are then to drop down so I don't have more than one tab selected at a time.

I have tried having a public var that acts as the selectedIndex and sending that to the flash component, but again the problem is getting the other tabs that aren't being clicked the data and to do something and I have no idea how to reference them?!

Anyone please help? Is there some way I can loop through the children of the flex canvas or something?

Custom Event Handler For A Timer Event?
I understand how to create custom events in order to pass parameters to a function being called by an event listener. I can get this to work fine if the event is being dispatched within my own code. However, I don't get how to do this if the event is a built-in event being dispatched by a Flash object.

Specifically, I need to call a function and pass it parameters when a timer ends. I don't know how to change the information being sent by the Timer because it is a native Flash class rather than something I'm writing. Can someone please clarify how to do this?

Help With Custom Event
I'm trying to create a custom event for my game.

here is the code for the event:

Code:
package com.scargames
{
/**
* @author:Kyle McKnight
* @date:28-JAN-08
* @purpose:
*/

import flash.events.Event;

public class WorldEvent extends Event
{
public static const ON_REGION_LOAD_ERROR:String = "onRegionLoadError";
public var _params:Object;

public function WorldEvent(type:String, params:Object = null, bubbles:Boolean = false, cancelable = false)
{
super(type, bubbles, cancelable);
_params = params;
}

public function get params():Object { return _params; }

public override function clone():Event
{
return new WorldEvent(type, this.params, bubbles, cancelable);
}

public override function toString():String
{
return formatToString("WorldEvent", "params", "type", "bubbles", "cancelable");
}
}
}


and the code for the object that dispatches it:

Code:
package com.scargames
{
/**
* @author:Kyle McKnight
* @date:28-JAN-08
* @purpose:
*/

import flash.events.EventDispatcher;
import com.scargames.WorldEvent;

public class World extends EventDispatcher
{
private var _regionNames:Array;
private var _zoneNames:Array;

public function World(config:XML)
{
buildRegionZoneNames(config);
}

private function buildRegionZoneNames(config:XML):void
{
var regionList:XMLList = config.region;
_regionNames = new Array();
_zoneNames = new Array();

for each(var regionElement:XML in regionList)
{
_regionNames.push(regionElement.attribute("name"));
var zoneList:XMLList = regionElement.zones.zone;

var tmpArr:Array = new Array();

for each(var zoneElement:XML in zoneList)
tmpArr.push(zoneElement.attribute("name"));

_zoneNames.push(tmpArr);
}
}

public function loadRegion(regionToLoad:String):void
{
for (var i:int = 0; i < _regionNames.length; i++)
{
if (regionToLoad == _regionNames[i])
return;
}

var event:WorldEvent = new WorldEvent(WorldEvent.ON_REGION_LOAD_ERROR, { errorText:regionToLoad + " is not in the list of regions." } );
dispatchEvent(event);
}
}
}


and the class that listens for it:

Code:
package com.scargames
{
/**
* @author:Kyle McKnight
* @date:28-JAN-08
* @purpose:This is the main entry point for the game
*/

import flash.display.Sprite;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.xml.*;

import com.scargames.World;
import com.scargames.WorldEvent;

public class Main extends Sprite
{
private var _world:World;
private var _config:XML;

public function Main()
{
XML.ignoreWhitespace = true;
var urlLoader:URLLoader = new URLLoader();
var urlRequest:URLRequest = new URLRequest("configuration.xml");
urlLoader.addEventListener(Event.COMPLETE, onConfigLoadComplete);
urlLoader.load(urlRequest);
}

public function onConfigLoadComplete(e:Event):void
{
trace("Configuration file loaded
");
_config = XML(e.target.data);
_world = new World(_config);
_world.loadRegion("RaccoonLan");
_world.addEventListener(WorldEvent.ON_REGION_LOAD_ERROR, onRegionLoadError);
}

public function onRegionLoadError(e:WorldEvent):void
{
trace("region error");
}
}
}


it's getting to the point where it shoudl create it, and it does create it, but then i dispatch it and the listener function in main is never called

Help With Custom Event
I'm trying to create a custom event for my game. The problem is the actual dispatching of the event. The class it is being dispatched FROM doesnt need to extend anything because it isn't displayed on screen but since it isnt extending anything it doesnt have the dispatchEvent function defined. So do i HAVE to extend the EventDispatcher class? I just wanted to keep it as lean as possible so didnt want to extend anything if I didnt have to.

Thanks!
Kyle

p.s. the code just for info

this is the class that creates the object that will dispatch the event... the _ws object is where it will originate from.


Code:
package com.scargames
{
/**
* @author:Kyle McKnight
* @date:28-JAN-08
* @purpose:This is the main entry point for the game
*/

import flash.display.Sprite;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.xml.*;

import com.scargames.World;

public class Main extends Sprite
{
private var _ws:World;
private var _config:XML;

public function Main()
{
XML.ignoreWhitespace = true;
var urlLoader:URLLoader = new URLLoader();
var urlRequest:URLRequest = new URLRequest("configuration.xml");
urlLoader.addEventListener(Event.COMPLETE, onConfigLoadComplete);
urlLoader.load(urlRequest);
}

public function onConfigLoadComplete(e:Event):void
{
trace("Configuration file loaded
");
_config = XML(e.target.data);
_ws = new World(_config);
_ws.loadRegion("RaccoonLan");
_ws.addEventListener(WorldEvent.ON_REGION_LOAD_ERROR, onRegionLoadError);
}

public function onRegionLoadError(e:WorldEvent):void
{
trace("region error");
}
}
}
and the class that will dispatch the event

Code:
package com.scargames
{
/**
* @author:Kyle McKnight
* @date:28-JAN-08
* @purpose:
*/

import flash.events.EventDispatcher;
import com.scargames.WorldEvent;

public class World
{
private var _regionNames:Array;
private var _zoneNames:Array;

public function World(config:XML)
{
buildRegionZoneNames(config);
}

private function buildRegionZoneNames(config:XML):void
{
var regionList:XMLList = config.region;
_regionNames = new Array();
_zoneNames = new Array();

for each(var regionElement:XML in regionList)
{
_regionNames.push(regionElement.attribute("name"));
var zoneList:XMLList = regionElement.zones.zone;

var tmpArr:Array = new Array();

for each(var zoneElement:XML in zoneList)
tmpArr.push(zoneElement.attribute("name"));

_zoneNames.push(tmpArr);
}
}

public function loadRegion(regionToLoad:String):void
{
for (var i:int = 0; i < _regionNames.length; i++)
{
if (regionToLoad == _regionNames[i])
return;
}

dispatchEvent(new WorldEvent(WorldEvent.ON_REGION_LOAD_ERROR, { errorText:regionToLoad + " is not in the list of regions." } ));
}
}
}

Custom Event
I'm new to AS3 and am trying to get the hang of events and custom events. In AS2 I used a callBack class to connect to other classes for information. From what I gather you no longer use that route and events are the way to go.

I have created a customEvent class.

ActionScript Code:
package com{
   
    import flash.events.Event;
   
    public class CustomEvent extends Event {
       
        public static const CUSTOM:String = "custom";
        public var arg:*;
       
        public function CustomEvent(type:String, customArg:*=null, bubbles:Boolean=false, cancelable:Boolean=false) {
            super(type, bubbles,cancelable)
            this.arg = customArg;
    }
   
    public override function clone():Event {
        return new CustomEvent(type, arg,bubbles,cancelable);
    }
   

    public override function toString():String {
         return formatToString("CustomEvent", "type", "arg");
      }
   
}
   
}

I created a test class to listen for an event that is been dispatched.


ActionScript Code:
package com {
   
    public class TestClass{
       
        import com.CustomEvent;
        import flash.events.*;
       
        public function TestClass(){
            this.addEventListener(CustomEvent.CUSTOM, onCustom, false, 0, true);
            //trace("TEST WORKNG = "+this);
        }
   
   
        private function onCustom(evt:CustomEvent):void {
       // trace(evt);
        trace(evt.arg);
        }
    }
}

To save time I just used the main timeline instead of another class to dispatch the event.


ActionScript Code:
import com.CustomEvent;
import com.TestClass;

var test:TestClass = new TestClass();

btn.addEventListener(MouseEvent.MOUSE_UP, onClick, false, 0, true);
btn.buttonMode = true;

function onClick(evt:MouseEvent) : void {
    var ctm_evt:CustomEvent = new CustomEvent(CustomEvent.CUSTOM, "Timeline Button has been clicked");
    dispatchEvent(ctm_evt);

}

btn is a movieClip that is on the stage and has an instance called btn
What I'm trying to do is tell the test class that btn has been clicked.
When I test this I get an error
[quote]1061: Call to a possibly undefined method addEventListener through a reference with static type com:TestClass.

Help With Custom Event
I know this is probably answered somewhere on here already and probably a basic question but I have searched and have not been able to solve my problem. I think I probably have some fundamental misunderstanding about how this works.

I am trying to write a single function that can control many buttons so I need the buttons when clicked to send a number to my function.

I first tried to do

Code:
btn1.addEventListener(MouseEvent.CLICK, dostuff(#));
I understand now why this did not work and think that I need a custom event handler so I have written this


Code:
package {
import flash.events.Event;
public class loadpage extends Event {
public static const type:String = "loadpage";
public var frame:int;
public function loadpage( frame:int ) {
super(type);
this.frame = frame
}
}
}
the above code might not be exactly right but even when it is I realized that as I understand it I still have to trigger this event with a dispatchEvent( and I don't get how I do that without writing another function for each button that triggers on click anyways

so if anyone can lay this out for me as simply as possible I think it will go a long way towards my understanding of how this stuff works

Custom Event In As3
Custom event example in as3
Hi,

Event listener model in cs3 looks nice it is not same as we were heaving earlier in as2 or till flash 8.

Here is an example of using and making your own custom event in as3.
This example allow user to load n number of XML file when XML file is loaded then dispatch an event "XMLLoaded" which can be listen by any other class any where.

There are two class
1. CustEvent
2. DEvt

Here are the definition of both class

CustEvent.as

/************************************************** *************************************
* Author - Sanjeev Rajput
* Date - 16-July-07
* class is used to load any XML file and dispatch an event when XML is loaded
************************************************** ***************************************/
package eventDispatch{
import flash.events.Event;
public class CustEvent extends Event {
public static const XMLLoaded:String = "XMLLoaded";// Event Name
public var XMLData:XML // loaded XML data
public var XMLRef:String // XML file name
public function CustEvent(type:String, param:String,param1:XML) {
this.XMLData= param1;
this.XMLRef=param;
super(type);
}
}
}
DEvt.as

/************************************************** *************************************
* Author - Sanjeev Rajput
* Date - 16-July-07
* class is used to load any XML file and dispatch an event when XML is loaded
************************************************** ***************************************/
package eventDispatch{
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.events.Event;
import flash.net.URLRequest;
public class DEvt extends EventDispatcher {
private var xmlLdr:URLLoader;
private var urlr:URLRequest;
private var xmlpath_str:String;
public var XMLData:XML;
private var counter:int=0;
private var xmlRequestArr:Array
public function DEvt():void {
this.xmlRequestArr=new Array()
}
public function loadXML(fileRef:String,xmlRef:String):void {
this.xmlpath_str=fileRef;
this.xmlRequestArr.push(xmlRef)
this.xmlLdr = new URLLoader();
this.urlr=new URLRequest(this.xmlpath_str);
this.xmlLdr.addEventListener(Event.COMPLETE, completeHandler);
this.xmlLdr.load(this.urlr);
}
private function completeHandler(evt:Event) {
this.XMLData=new XML(evt.target.data);
this.dispatchEvent(new CustEvent(CustEvent.XMLLoaded,this.xmlRequestArr[this.counter],this.XMLData));
this.counter++
}
}
}

evtDispatchExample.fla

Inside this fla on very first frame I have following code

import eventDispatch.*;
var DEvt_obj:Evt=new DEvt();
DEvt_obj.loadXML("xml.xml",'xml0 File');
DEvt_obj.loadXML("xml1.xml",'xml1 File');
DEvt_obj.loadXML("xml2.xml",'xml2 File');//----and so on---
DEvt_obj.addEventListener(CustEvent.XMLLoaded,XMLL oaded);
function XMLLoaded(evt:CustEvent) {
//--- here we can check which XML file is loaded----
if(evt.XMLRef=='xml0'){
//--- do necessary task when this file loaded
//---XML data can be found in evt.XMLData
trace(evt.XMLData) //-- property of CustEvent class
}
if(evt.XMLRef=='xml1'){
//--- do necessary task when this file loaded
//---XML data can be found in evt.XMLData
trace(evt.XMLData) //-- property of CustEvent class
}
//---- and so on for n number of XML file----
}

Custom Event Please Help
Hi all

I have a container sprite on stage. Then I have another sprite containing 5 buttons. I want to display the contents of buttons when they are clicked in the container sprite.

I am using CustomEvent class to dispatch Display obejct i.e is a dynamic textfield containing the contents of the clicked button.

I have a class called GetDisplayObejct() when a button is clicked I am creating an object of GetDisplayObject by passing the contents of the display button as constructor argument.

Inside GetDisplay Object constructor I am running a switch statment to check which button was clicked so if the clicked button was home then what I am doing is creating a home moviclip which is just a dynamice text field and filling this text field with the contents of home. now I am dispatching this DisplayObejct i.e home textfield how can I notify the container on the main time line about this dispatched event so that it can receive the display object and dispaly it on stage using addChild

I hope I am making sense here
If you want I can send u the code for GetDisplayObject class as well.

Thank you for helping

Help With Custom Event
I am trying to create a custom event for my game.

Here is the event code:

Code:
package com.scargames
{
/**
* @author: Kyle McKnight
* @date: 28-JAN-08
* @purpose:
*/

import flash.events.Event;

public class WorldEvent extends Event
{
public static const ON_REGION_LOAD_ERROR:String = "onRegionLoadError";
public var _params:Object;

public function WorldEvent(type:String, params:Object = null, bubbles:Boolean = false, cancelable = false)
{
super(type, bubbles, cancelable);
_params = params;
}

public function get params():Object { return _params; }

public override function clone():Event
{
return new WorldEvent(type, this.params, bubbles, cancelable);
}

public override function toString():String
{
return formatToString("WorldEvent", "params", "type", "bubbles", "cancelable");
}
}
}
here is the class that dispatches it:

Code:
package com.scargames
{
/**
* @author: Kyle McKnight
* @date: 28-JAN-08
* @purpose:
*/

import flash.events.EventDispatcher;
import com.scargames.WorldEvent;

public class World extends EventDispatcher
{
private var _regionNames:Array;
private var _zoneNames:Array;

public function World(config:XML)
{
buildRegionZoneNames(config);
}

private function buildRegionZoneNames(config:XML):void
{
var regionList:XMLList = config.region;
_regionNames = new Array();
_zoneNames = new Array();

for each(var regionElement:XML in regionList)
{
_regionNames.push(regionElement.attribute("name"));
var zoneList:XMLList = regionElement.zones.zone;

var tmpArr:Array = new Array();

for each(var zoneElement:XML in zoneList)
tmpArr.push(zoneElement.attribute("name"));

_zoneNames.push(tmpArr);
}
}

public function loadRegion(regionToLoad:String):void
{
for (var i:int = 0; i < _regionNames.length; i++)
{
if (regionToLoad == _regionNames[i])
return;
}

var event:WorldEvent = new WorldEvent(WorldEvent.ON_REGION_LOAD_ERROR, { errorText:regionToLoad + " is not in the list of regions." } );
dispatchEvent(event);
}
}
}
and the class that listens for it:

Code:
package com.scargames
{
/**
* @author: Kyle McKnight
* @date: 28-JAN-08
* @purpose: This is the main entry point for the game
*/

import flash.display.Sprite;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.events.Event;
import flash.xml.*;

import com.scargames.World;
import com.scargames.WorldEvent;

public class Main extends Sprite
{
private var _world:World;
private var _config:XML;

public function Main()
{
XML.ignoreWhitespace = true;
var urlLoader:URLLoader = new URLLoader();
var urlRequest:URLRequest = new URLRequest("configuration.xml");
urlLoader.addEventListener(Event.COMPLETE, onConfigLoadComplete);
urlLoader.load(urlRequest);
}

public function onConfigLoadComplete(e:Event):void
{
trace("Configuration file loaded
");
_config = XML(e.target.data);
_world = new World(_config);
_world.loadRegion("RaccoonLan");
_world.addEventListener(WorldEvent.ON_REGION_LOAD_ERROR, onRegionLoadError);
}

public function onRegionLoadError(e:WorldEvent):void
{
trace("region error");
}
}
}
it's getting to the point where it shoudl create it, and it does create it, but then i dispatch it and the listener function in main is never called

AS3 - [AS3] Custom Event Tip
On a few occasions while using custom events I have encountered runtime errors when the name of one event conflicts with another, this seems to happen more with bubbling events than non-bubbling events. For example, a custom ButtonEvent.CLICK event could conflict with the MouseEvent.CLICK event. To remedy this problem I decided to change the way I name events in order to avoid these conflicts.


Code:
package
{
import flash.events.Event;

public class ButtonEvent extends Event
{
public static const CLICK:String = "ButtonEvent:click";
public static const DOUBLE_CLICK:String = "ButtonEvent:doubleClick";

public function ButtonEvent( type:String )
{
super( type, true );
}
}
}
As you can see I decided to prefix the event names (the string value) with the name of the class. A simple but effective change.

Custom Event Please Help
Hi all

I have a container sprite on stage. Then I have another sprite containing 5 buttons. I want to display the contents of buttons when they are clicked in the container sprite.

I am using CustomEvent class to dispatch Display obejct i.e is a dynamic textfield containing the contents of the clicked button.

I have a class called GetDisplayObejct() when a button is clicked I am creating an object of GetDisplayObject by passing the contents of the display button as constructor argument.

Inside GetDisplay Object constructor I am running a switch statment to check which button was clicked so if the clicked button was home then what I am doing is creating a home moviclip which is just a dynamice text field and filling this text field with the contents of home. now I am dispatching this DisplayObejct i.e home textfield how can I notify the container on the main time line about this dispatched event so that it can receive the display object and dispaly it on stage using addChild

I hope I am making sense here
If you want I can send u the code for GetDisplayObject class as well.

Thank you for helping

[mx]add Event For Custom Button
You know how you can add an event to trigger a function on the mx push button component ?

I had my component do something "onSubmit" (onSumbit was the event name in the property inspector.)

now, I want to do the same thing, only I have a custom button I made and I want to attach the function to it..on Press..

I'm sure you all know the answer, will be waiting for enlightment
thanks

Custom Event Handler
hi:

i was wondering if it was posible to make a custom event handler, i have a scene and i duplicate a MC a lot of times and each duplicated MC has its own code, so the scene is getting a little slow, so i was wondering instead of using the enterFrame event handler i could use something like this

onClipEvent(this._x<100){
do this
}
or instead of the this._x<100 some other condition
thanks i have flash 8 and i am using actionscript 2

No Response From Custom Event
hi guys...what am i missing here:

Code:
package {
import flash.display.Sprite;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.text.StyleSheet;
import flash.events.Event;
import com.em.CSSEvent;
import com.em.Response;

public class LC extends Sprite{
private var urlr:URLRequest;
private var urll:URLLoader;
public var css:StyleSheet;
public var mainURL:String;
public function LC(){
init();
}
private function init():void{
var re:Response= new Response();
re.addEventListener(CSSEvent.LOADED,tellme)
mainURL="http://localhost/LC/";
urlr= new URLRequest();
urlr.url=mainURL+"styles/styles.css";
urll=new URLLoader();
urll.addEventListener(Event.COMPLETE,doCSS);
urll.load(urlr)
}
private function doCSS(ev:Event):void{
var cssev:CSSEvent= new CSSEvent("loaded","yep, it's good");
this.dispatchEvent(cssev);
}
private function tellme(ce:CSSEvent){
trace(ce.result);
}
}
}


the custom event code is:


Code:
package com.em
{
import flash.events.Event;
public class CSSEvent extends Event{
public static const LOADED:String="loaded";
public var result:String;
public function CSSEvent(type:String,x:String){
super(type,true);
result=x;
}
public override function clone():Event{
//return the event, it's type, and it's result props
return new CSSEvent(type,result);
}
}
}


the Response class, you don't need to see...i don't think. Just know that it extends Sprite. I am expecting to see the trace from the eventListener....but apparently, i am not dispatching or listening correctly....ideas?

Dispatching Custom Event
Hello everybody,

Task: I want to enter a message in input text field and write it in the dynamic using a custom event dispatching.

Solution:
I have 2 textfields on the stage.
One textfield is an input text field the other is a dynamic text field which will server just to display text.
on the flash in the first frame I made this code:

Code:
var messageBoard:MsgBoard = new MsgBoard(mb); // mb is the instance name of the dynamic text field already placed on the stage
var user1:UserInput = new UserInput(u1); // u1 is the input text field placed on the stage


Also I wrote 3 very simple classes.

1. UserInput.as

Code:
package {

import flash.text.TextField;
import flash.ui.Keyboard;
import flash.events.*;

public class UserInput extends EventDispatcher{

private var textInput:TextField;

public function UserInput(ti:TextField){
textInput = ti;
//listening user input in the input text
textInput.addEventListener(KeyboardEvent.KEY_UP, send_event);
}

private function send_event(evnt:KeyboardEvent):void{
//once enter pressed dispatching our custom event
if(evnt.keyCode == Keyboard.ENTER){
var msg:MsgEvent = new MsgEvent(textInput.text);
this.dispatchEvent(msg);
textInput.text = '';
}
}

}
}


2. MsgEvent.as

Code:
package {
import flash.events.Event;

public class MsgEvent extends Event{

public static const NEW:String = "new_message";

public var msg:String;

public function MsgEvent(str:String){
super(NEW);
msg = str;
}

public override function clone():Event
{
return new MsgEvent(msg);
}

}
}


3. MsgBoard.as

Code:
package {

import flash.text.TextField;
import flash.display.Sprite;

public class MsgBoard extends Sprite{

private var displayTextArea:TextField;

public function MsgBoard(mb:TextField){
displayTextArea = mb;
displayTextArea.text = 'listening to the user input';
// as displayTextArea is a reference to the object that is located on the Stage
// it should have an ability to listen to the events as it's a part of event flow
displayTextArea.addEventListener(MsgEvent.NEW, refreshTextArea);
}

private function refreshTextArea(evnt:MsgEvent):void{
displayTextArea.appendText(evnt.msg);
}

}
}


Problem: Somehow it doesn't work. I actually made it work by making a listener the same object that dispatches the event.
But I want to understand why it doesn't works the way I showed above. I browsed a lot of forums and found that all the
people use to listen by the same object that is dispatching. I think it's like talking with yourself isn't it?

Help With Custom Class Event
Hya,

This is really annoying me, I've gone round and round trying to find a solution, but the event is never fired or listened to!....

Basically i want to load an XML file when this has been parsed raise an event.

this is the class:


Code:
import mx.events.EventDispatcher;
import mx.utils.Delegate;

class NewsArticlesCommunicator {

public function dispatchEvent() {};
public function addEventListener() {};
public function removeEventListener() {};

var strXMLPath = "data/NewsArticles.xml";
var xmlDoc:XML;
var arrReturn:Array;
public function NewsArticlesArray()
{
mx.events.EventDispatcher.initialize(this);
}
public function LoadAll():Void{
xmlDoc = new XML();
xmlDoc.ignoreWhite = true;
xmlDoc.onLoad = Delegate.create(this, ParseXML);
xmlDoc.load(strXMLPath);
}
public function ParseXML(success){

arrReturn = new Array();
var eventObject:Object = {type:'onLoadData'};
if(success){
for (var current_node:XMLNode = xmlDoc.firstChild.firstChild; current_node != null; current_node = current_node.nextSibling) {
if (current_node.nodeName == "Article") {
arrReturn.push(
{articleid: String(current_node.attributes.ID),
title: String(current_node.childNodes[0].firstChild.nodeValue),
summary: String(current_node.childNodes[1].firstChild.nodeValue),
content: String(current_node.childNodes[2].firstChild.nodeValue)}
);
}
}
eventObject.success = true;
eventObject.resultsArray = arrReturn;
}else{
eventObject.success = false;
}
this.dispatchEvent(eventObject);
}
}
and

Code:
var newsArticles:NewsArticlesCommunicator = new NewsArticlesCommunicator();

var myListnerObj:Object = new Object;
myListnerObj.onLoadData = function(evtObj) {
trace("This is the suceess: "+ evtObj.success);
trace("This is the event type: "+ evtObj.type);
}

newsArticles.addEventListener("onLoadData", myListnerObj);
newsArticles.LoadAll();
Please help, it all seems ok to me, maybe it's something i'm missing or not doing properly!... I've changes the event type as i though it might have been a reserved word but it's not, i've added a trace in the ParseXML and it's fine...

Thanks for your help..

Regards,

Custom Event Dispatching
Hi

I need a little help....i have created a custom event, and would like to dispacth this to the stage in frame 1 of my .fla.

However, im a bit confused how to do this.

I have read a couple of tutorials, but nothing actually works.

Thanks

Custom Event Dispatching
I'm trying to dispatch and catch events along the display path, and I'm running into a small problem - it doesn't work. I assume I'm implementing something incorrectly, but from what I've read I assumed I was doing this correctly. I'm trying to catch an event in the bubbling phase, though either would work in this test case. Also, I recognize that using a static constant is much better than using a literal string, but this isn't live code, just code tests..

In my FLA..

ActionScript Code:
import GameManager;

var myGameManager = new GameManager();
addChild(myGameManager);

GameManager.as

ActionScript Code:
package {
    import flash.display.MovieClip;
    import flash.events.*;
    import EventTest;
   
    public class GameManager extends MovieClip {
        private var myTestObject:EventTest;
       
        public function GameManager():void {
            this.addEventListener("Test", doSomething);
            myTestObject = new EventTest();
            addChild(myTestObject);
            myTestObject.testDispatch();
        }
       
        private function doSomething(whichEvent:Event):void {
            trace("doSomething function");
        }
    }
}

EventTest.as

ActionScript Code:
package {
   
    import flash.display.MovieClip;
    import flash.events.*;
   
    public class EventTest extends MovieClip {
       
        private var localDispatcher:EventDispatcher;
       
        public function EventTest():void {
            localDispatcher = new EventDispatcher();
        }
       
        public function testDispatch():void {
            trace("dispatching event..");
            localDispatcher.dispatchEvent(new Event("Test", true));
        }
    }
}

Dispatch Custom Event
Hi,

Is there way to dispatch events if any movieClip change its position..

Custom Event Not Received
I'm new to Flash and AS3 and I've been struggling with this one for the whole day. I'm trying to implement custom events in AS but somehow after dispatching the event it doesn't seem to get handled.

Here's my custom event class:


Code:
package
{
import flash.events.Event;

public class UpdateMsgEvent extends Event
{
public static const UPDATEMSG:String = 'updatemsg';
public var msg:String;

public function UpdateMsgEvent(msg:String, bubbles:Boolean = false, cancelable:Boolean = false)
{
super(UPDATEMSG, bubbles, cancelable);
this.msg = msg;
}

public override function clone():Event
{
return new UpdateMsgEvent(this.msg, this.bubbles, this.cancelable);
}
}
}
And here's my main script:


Code:
package
{
import UpdateMsgEvent;
import flash.display.MovieClip;

public class CustomEventTest extends MovieClip
{
public function CustomEventTest()
{
var dis:MyDispatcher = new MyDispatcher();
this.addEventListener(UpdateMsgEvent.UPDATEMSG, handle);
dis.dispatch();
}

public function handle(e:UpdateMsgEvent):void
{
trace("Event detected");
}
}
}

import flash.events.EventDispatcher;
import UpdateMsgEvent;

class MyDispatcher extends EventDispatcher
{
public function dispatch():void
{
trace('Dispatching...');
this.dispatchEvent(new UpdateMsgEvent('Message'));
}
}
The only output from the program is "Dispatching..." which seems to indicate that handle() is never called. I would really like to get over this problem, so any help is appreciated

Custom Event Handling
This is probably really basic, but I'm trying to use a custom event class because, as I understand it, this is the only way to pass a parameter/variable through an event handler. Here is my class code:


Code:
package
{

import flash.events.Event;

class CustomEvent extends Event
{

public var myString:String;

public function CustomEvent( type:String, str:String )
{
myString = str;
super( type );
}
And here is how I'm calling it:


Code:
dispatchEvent(new CustomEvent("imageLoaded", "hello"));
and then, after the event is dispatched and received, I am trying to trace it out like so:


Code:
private function configText(e:Event):void {
trace(e.myString);
}
But I get the following error:
[b]1119: Access of possibly undefined property myString through a reference with static type flash.events:Event.

Custom Event Dispatching
Hello everybody,

Task: I want to enter a message in input text field and write it in the dynamic using a custom event dispatching.

Solution:
I have 2 textfields on the stage.
One textfield is an input text field the other is a dynamic text field which will server just to display text.
on the flash in the first frame I made this code:

Code:
var messageBoard:MsgBoard = new MsgBoard(mb); // mb is the instance name of the dynamic text field already placed on the stage
var user1:UserInput = new UserInput(u1); // u1 is the input text field placed on the stage
Also I wrote 3 very simple classes.

1. UserInput.as

Code:
package {

import flash.text.TextField;
import flash.ui.Keyboard;
import flash.events.*;

public class UserInput extends EventDispatcher{

private var textInput:TextField;

public function UserInput(ti:TextField){
textInput = ti;
//listening user input in the input text
textInput.addEventListener(KeyboardEvent.KEY_UP, send_event);
}

private function send_event(evnt:KeyboardEvent):void{
//once enter pressed dispatching our custom event
if(evnt.keyCode == Keyboard.ENTER){
var msg:MsgEvent = new MsgEvent(textInput.text);
this.dispatchEvent(msg);
textInput.text = '';
}
}

}
}
2. MsgEvent.as

Code:
package {
import flash.events.Event;

public class MsgEvent extends Event{

public static const NEW:String = "new_message";

public var msg:String;

public function MsgEvent(str:String){
super(NEW);
msg = str;
}

public override function clone():Event
{
return new MsgEvent(msg);
}

}
}
3. MsgBoard.as

Code:
package {

import flash.text.TextField;
import flash.display.Sprite;

public class MsgBoard extends Sprite{

private var displayTextArea:TextField;

public function MsgBoard(mb:TextField){
displayTextArea = mb;
displayTextArea.text = 'listening to the user input';
// as displayTextArea is a reference to the object that is located on the Stage
// it should have an ability to listen to the events as it's a part of event flow
displayTextArea.addEventListener(MsgEvent.NEW, refreshTextArea);
}

private function refreshTextArea(evnt:MsgEvent):void{
displayTextArea.appendText(evnt.msg);
}

}
}
Problem: Somehow it doesn't work. I actually made it work by making a listener the same object that dispatches the event.
But I want to understand why it doesn't work the way I showed above. I browsed a lot of forums and found that all the
people use to listen by the same object that is dispatching. I think it's like talking with yourself isn't it?

Help With Custom Event Listener
I'm having some trouble with a custom event listener.
The listener fires as far as I'm aware of. The problem is that I have my main document registered to listen for the event and It dosn't seem to be catching it?

On my main document as soon as it starts I make a instance of a loader class. This class dosnt do anything yet except dispatch my custom Event
Audio Loader Class

ActionScript Code:
package {
    import flash.errors.*;
    import flash.net.*;
    import flash.events.*;
    import flash.display.*;
    public class audioLoader extends MovieClip {


        public var workpath:String="loopMaster";
        public var mc:MovieClip=new MovieClip  ;

        public function audioLoader() {
            onComplete()
        }
        public function onComplete() {
            dispatchEvent(new loadEvent(loadEvent.LOAD_COMPLETE));
        }
    }
}

Here is the code for my event


ActionScript Code:
package {
    import flash.events.*;

    public class loadEvent extends Event {

        public static  const LOAD_COMPLETE:String="complete";

        public function loadEvent(type:String,bubbles:Boolean=true,cancelable:Boolean=false) {
            super(type,bubbles,cancelable);
            trace("event test :" + type);
        }
        public override  function clone():Event {
            return new loadEvent(type);
        }
    }
}

now here is my main document



ActionScript Code:
public function Main() {
           
            this.addEventListener(loadEvent.LOAD_COMPLETE,loadHandler)
var audioLoad:audioLoader=new audioLoader();
   

        }
        function loadHandler(e:loadEvent):void {
            trace("about to init"+e)
            init();
           
        }

It seems that the loadHandler from my main document never gets called because neither the trace traces or the init function executes?

Why might my main documnet class not be able to listen for the event I dispatch?

I tried changing bubbles for true to false but it didnt do anything. I get the feeling Im missing something very fundamental?

AS3 Custom Event Problem
Hi,
I've encountered a problem when trying to dispatch a custom event between two brothers in the hirrarchy tree.
When dispatched from one of the children, the parent can listen to this event, but other children can not.
Anybody knows why ???

Thanks,
EZ42

Custom Event Handler
I am trying to make a custom event handler to check to see when the XML data is loaded into an object in my class so it can be accessed by the instance in an FLA. I made the class below to extend Events. I am planning on using a timer to keep checking to see when it is loaded. I can't put the checking logic into the base class because when the class runs, the XML object is there. It is a question of when it is available to the instance of the class. So, do I have to put the timer code in the FLA? Can I somehow put the timing logic into the handler as? Any help on the best way to do it....I've gotten it to work in the FLA but I hate having that code out there in the FLA if I can do it elsewhere in a class...

Thanks in advance!








Attach Code

// Can I put handler logic - timer checking logic - in here somehow and have it check for the instance?

package handlers{

import flash.events.Event;

public class xmlObjectEvent extends Event{

public static const XMLOBJECTLOAD:String = "XML Object Load";

public function xmlObjectEvent(type:String):void{
super(type);
}

public override function clone():Event{
return new xmlObjectEvent(type);
}
}
}

Custom Event Handler
Just curious. I made a custom event handler that is dispatched from within a class when an XML document is loaded. The listener is attached to the instance of that class in the FLA. The attached code to this thread is what is for the class instance. Does that have to be out there? Is there a cleaner way to do it so that the code would be away in a class? Just wondering....

Thanks!







Attach Code

import mps.uiprototype.main.xmlLoader;
import mps.uiprototype.events.xmlObjectEvent;

var myXML:XML = new XML();

var appMenubar:xmlLoader = new xmlLoader("xml/menubar.xml");
appMenubar.addEventListener(xmlObjectEvent.XMLOBJECTLOAD, handleXMLObject);

function handleXMLObject(e:xmlObjectEvent):void{

// Load the XML Object passed from the load event into the local Object
myXML = e.xmlData;
trace("Here: " + myXML.mainitem[0].@name);

// Remove the listener as it is no longer required
appMenubar.removeEventListener(xmlObjectEvent.XMLOBJECTLOAD, handleXMLObject);

}

Dispatching Custom Event
Hello everybody,

Task: I want to enter a message in input text field and write it in the dynamic using a custom event dispatching.

Solution: I have 2 textfields on the stage.
One textfield is an input text field the other is a dynamic text field which will server just to display text.
on the flash in the first frame I made this code:
// mb is the instance name of the dynamic text field already placed on the stage
var messageBoard:MsgBoard = new MsgBoard(mb);
// u1 is the input text field placed on the stage
var user1:UserInput = new UserInput(u1);

Also I wrote 3 very simple classes.
1. UserInput.as // input textfield class that listens to input and dispatches a custom event
2. MsgEvnt.as // custom event class the instance of which is dispatched
3. MsgBoard.as // class that listens to the new event and once it occurs adding event message to the textfield

Problem: Somehow it doesn't work. I actually made it work by making a listener the same object that dispatches the event. But I want to understand why it doesn't works the way I showed above. I browsed a lot of forums and found that all the people use to listen by the same object that is dispatching. I think it's like talking with yourself isn't it?

Thanks everybody who will reply and I hope it will help someone who will read!







Attach Code

//UserInput.as
package {

import flash.text.TextField;
import flash.ui.Keyboard;
import flash.events.*;

public class UserInput extends EventDispatcher{

private var textInput:TextField;

public function UserInput(ti:TextField){
textInput = ti;
//listening user input in the input text
textInput.addEventListener(KeyboardEvent.KEY_UP, send_event);
}

private function send_event(evnt:KeyboardEvent):void{
//once enter pressed dispatching our custom event
if(evnt.keyCode == Keyboard.ENTER){
var msg:MsgEvent = new MsgEvent(textInput.text);
this.dispatchEvent(msg);
textInput.text = '';
}
}

}
}

// MsgEvent.as
package {
import flash.events.Event;

public class MsgEvent extends Event{

public static const NEW:String = "new_message";

public var msg:String;

public function MsgEvent(str:String){
super(NEW);
msg = str;
}

public override function clone():Event
{
return new MsgEvent(msg);
}

}
}

// MsgBoard.as
package {

import flash.text.TextField;
import flash.display.Sprite;

public class MsgBoard extends Sprite{

private var displayTextArea:TextField;

public function MsgBoard(mb:TextField){
displayTextArea = mb;
displayTextArea.text = 'listening to the user input';
// as displayTextArea is a reference to the object that is located on the Stage
// it should have an ability to listen to the events as it's a part of event flow
displayTextArea.addEventListener(MsgEvent.NEW, refreshTextArea);
}

private function refreshTextArea(evnt:MsgEvent):void{
displayTextArea.appendText(evnt.msg);
}

}
}

Custom Event Class
I am trying to create my own custom event class. Following a couple of tutes and trying to make sense of it all. I have an FLA with absolutely nothing but a shape in the library exported for AS. I then have two classes (code below), one to display the object, and another for custom events. I am lost as to how to make my custom event actually do something. As you can see, I want it to call the second function, but I get nothing, not even an error. A little direction would be greatly appreciated! I think it will obvious that I don't know where to put the "dispatchEvent" or the "newShape.addEventListener" or even if they both go in the same AS file!







Attach Code

// control.as

package
{
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import eventManager;

public class control extends MovieClip
{
var newShape:Shape;

public function control()
{
newShape = new Shape();
newShape.y = newShape.x = 100;
addChild(newShape);
functionOne();
}
private function functionOne():void
{
trace("Function One");
dispatchEvent(new eventManager("EventManagerFired"));
newShape.addEventListener(eventManager.ANIM_COMPLETE, functionTwo);
}
private function functionTwo():void
{
trace("Function Two");
}

public function functionThree():void
{
trace("Function Three");
}
}
}

// === eventManager.as

package
{
import flash.events.*;

public class eventManager extends Event
{
public static const ANIM_COMPLETE:String = "CustomEventCalled";
private var theMessage:String;

public function eventManager(tm:String):void
{
super(ANIM_COMPLETE);
this.theMessage = tm;
}
}
}

Custom Event Problem
am making custom click event in which I'm not getting any output and also not getting any errors in it.. following is the code : please tell me what am I doing wrong in it?







Attach Code

//Rec.as
package{
import flash.display.MovieClip;
import flash.text.TextField;
import flash.events.Event;
import flash.events.MouseEvent;
public class Rec extends MovieClip{

//public static var ClickedMe:String = "clicked";
static public var ClickedMe:String = "clicked";
public function Rec(mc:MovieClip):void
{
trace("this "+this.name)
mc.addEventListener(MouseEvent.CLICK, mouseClicked);
}

public function mouseClicked(e:MouseEvent):void {
dispatchEvent(new Clicked(ClickedMe));
}


}
}



//Clicked.as

package {
import flash.display.MovieClip;
import flash.text.TextField;
import flash.events.Event;
import flash.events.MouseEvent;

public class Clicked extends Event {
public function Clicked(type:String) {
super(type);
}
}
}


//.fla
//rec_mc is the movieclip on stage.

var d:Rec=new Rec(rec_mc);
rec_mc.addEventListener(Rec.ClickedMe,clickedRec);

function clickedRec(e:Clicked) {
trace("entered clicking event : "+e.target);
}

Custom Event Problem
Hi, i have a class which extends the EventDispatcher class and fires a custom event when it completes. I'm trying to add an event listener to it in the document class but it gives me this error:

ReferenceError: Error #1065: Variable config::addEventListener is not defined.
at Reader/init()
at Reader()

the code is this:

public var config:Config;// Main configuration class

config = new Config();
config.addEventListener(Config.FINISHED, loadComponents, false,0,true);

Any ideas please, thanks

[AS3] Custom Event Subclass
I'm having a problem with a custom subclassed Event class. Or I should say, I'm having trouble receiving events from this custom event class. I'm pretty sure I have everything wired correctly, the event is dispatched properly and my trace shows the Event instance being spawned. However, my eventListener, which is in another class, never fires its handler function.

Have any of you run across instances where custom event classes fail to fire? I'm about at my wit's end.

[AS3] Custom Event Problems
Hi!

I'm trying to make a custom event that bubbles up from the Items object in this code to the Main object, and start
the changeInfoHandler there.

For some reason, it works when I put the dispatchEvent in the Items object inside a handler for a mouse click,
but when I try to bypass that and call the function directly, it seems to only work in the scope of the Items object.


Main.as:


Code:
package
{
import flash.display.*;
import flash.events.*;
import ChangeEvent;

[SWF(backgroundColor="0xefefef", frameRate='60', width='640', height='480')]

/**
* @mxmlc -use-network=false -library-path+=./ -source-path+=./ -locale=en_US
*/

public class Main extends Sprite
{
public function Main()
{
addEventListener(ChangeEvent.INFO, changeInfoHandler);

// this is for senocular's Output.as trace Class
stage.addChild(new Output(stage));
initItems();
}

private function initItems():void
{
var items: Items = new Items();
addChild(items);
}

public function changeInfoHandler(evt: ChangeEvent):void
{
Output.trace("we're in the changeInfoHandler of " + this + "(" + evt.target + evt.currentTarget + evt + ")");
}
}
}
Here's the ChangeEvent.as


Code:
package
{
import flash.events.*;

public class ChangeEvent extends Event
{
public static const INFO:String = "info";

public function ChangeEvent(type: String, bubbles: Boolean, cancelable: Boolean)
{
Output.trace("we're in the ChangeEvent.");
super(type, bubbles, cancelable);
}
public override function clone():Event {
return new ChangeEvent(type, true, false);
}
}
}

The follow Items.as works:


Code:
package
{
import flash.display.*;
import flash.events.*;
import ChangeEvent;
import flash.text.TextField;

public class Items extends Sprite
{
public function Items()
{
addEventListener(ChangeEvent.INFO, changeInfoHandler);
addEventListener(MouseEvent.CLICK, mediate);

makeItems();
}
private function makeItems():void
{
var dummyField: TextField = new TextField();
dummyField.text = "here's something to click";
addChild(dummyField);
// mediate();
}

// private function mediate():void
private function mediate(evt: MouseEvent):void
{
var changeEvent:ChangeEvent = new ChangeEvent(ChangeEvent.INFO, true, false);
dispatchEvent(changeEvent);
}

public function changeInfoHandler(evt: ChangeEvent):void
{
Output.trace("we're in the changeInfoHandler of " + this + "(" + evt.target + evt.currentTarget + evt + ")");
}
}
}
traces:


Quote:




we're in the ChangeEvent.
we're in the changeInfoHandler of [object Items]([object Items][object Items][Event type="info" bubbles=true cancelable=false eventPhase=2])
we're in the changeInfoHandler of [object Main]([object Items][object Main][Event type="info" bubbles=true cancelable=false eventPhase=3])




The following Items.as doesn't work:


Code:
package
{
import flash.display.*;
import flash.events.*;
import ChangeEvent;
import flash.text.TextField;

public class Items extends Sprite
{
public function Items()
{
addEventListener(ChangeEvent.INFO, changeInfoHandler);

makeItems();
}
private function makeItems():void
{
var dummyField: TextField = new TextField();
dummyField.text = "here's something to click";
addChild(dummyField);
mediate();
}

private function mediate():void
{
var changeEvent:ChangeEvent = new ChangeEvent(ChangeEvent.INFO, true, false);
dispatchEvent(changeEvent);
}

public function changeInfoHandler(evt: ChangeEvent):void
{
Output.trace("we're in the changeInfoHandler of " + this + "(" + evt.target + evt.currentTarget + evt + ")");
}
}
}
traces:


Quote:




we're in the ChangeEvent.
we're in the changeInfoHandler of [object Items]([object Items][object Items][Event type="info" bubbles=true cancelable=false eventPhase=2])





Any ideas why?

Custom Event Handler
hi, I want to create some custom event handler, so here is my code at stage

ActionScript Code:
import getInfo;var hhh:getInfo = new getInfo();



my class getInfo;

ActionScript Code:
package {    import flash.display.MovieClip;    import flash.events.Event;    import phpInfo;    import getInfoEvent;    public class getInfo extends MovieClip {        public function getInfo() {            var url:String = "http://localhost:81/www.theflashblog-bg.com/fcp_v2/bin/php/showPosts.php";            var php:phpInfo = new phpInfo();            php.getAllPosts(url);            addEventListener(getInfoEvent.getXML, heh);        }        public function heh(info:getInfoEvent):void {            trace(">> "+info.xmlArrayData);        }    }}


get form php ifrmation class: class phpInfo

ActionScript Code:
package {    import flash.events.Event;    import flash.net.URLLoader;    import flash.net.URLLoaderDataFormat;    import flash.net.URLRequest;    import flash.net.URLRequestMethod;    import flash.net.URLVariables    import flash.xml.XMLDocument;    import flash.display.Stage;    import flash.display.MovieClip;        import getInfoEvent;    import getInfo;    public class phpInfo extends MovieClip{        public static const readyXML:String = "readyXML";        public var query:String;        public var id:String;        public var ArrayOfInfo:Array = new Array();        private var phpLoader:URLLoader = new URLLoader();        private var request_:URLRequest = new URLRequest();        private var varsToSend:URLVariables = new URLVariables();                                public function phpInfo():void {            request_.method = URLRequestMethod.POST;            phpLoader.dataFormat = URLLoaderDataFormat.TEXT;        }        public function getAllPosts(url:String):void {            request_.url = url;            //set needed info            varsToSend.hostnam = "localhost";            varsToSend.database = "theblog";            varsToSend.username = "tAdmin";            varsToSend.password = "tpass";            //            request_.data = varsToSend;            phpLoader.addEventListener(Event.COMPLETE, getAllPosts_COMPLETED);            phpLoader.load(request_);        }        private function getAllPosts_COMPLETED(info:Event):void {            var gallery_xml:XMLDocument = new XMLDocument();            gallery_xml.ignoreWhite = true;            gallery_xml.parseXML(phpLoader.data);            var i:uint;            var al:Number = gallery_xml.firstChild.childNodes.length;            for (i=0;i<al;i++) {                ArrayOfInfo.push(new Array(gallery_xml.firstChild.childNodes[i].attributes["id"], gallery_xml.firstChild.childNodes[i].attributes["date"], gallery_xml.firstChild.childNodes[i].attributes["title"], gallery_xml.firstChild.childNodes[i].attributes["author"], gallery_xml.firstChild.childNodes[i].attributes["view"], gallery_xml.firstChild.childNodes[i].attributes["categry"], gallery_xml.firstChild.childNodes[i].attributes["attach"], gallery_xml.firstChild.childNodes[i].attributes["image"], gallery_xml.firstChild.childNodes[i].attributes["comments"]));            }            this.dispatchEvent(new getInfoEvent(getInfoEvent.getXML, ArrayOfInfo));                    }    }}



event class:class getInfoEvent

ActionScript Code:
package {    import flash.events.Event;        public class getInfoEvent extends Event{        public static const getXML:String = "getXML";        public var xmlArray:Array = new Array();                public function get xmlArrayData():Array {            return xmlArray;        }        public function getInfoEvent(type:String, gotData:Array):void {            xmlArray = gotData;            super(type, true);            trace(xmlArray);        }        public override function clone():Event {            trace("<<>>");            return new getInfoEvent(type, xmlArray);                    }    }    }



So, what is the problem. The problem is that in function getInfoEvent(), it trace me the array correctly, but this clone(), don't trace "<<>>", and I don't have function heh() trace too. What is wrong?

Custom Event Problem
So I have a group of MenuItems (Extends sprite) that are dynamically created from the coding in my as frame in my timeline.


ActionScript Code:
for(var i:int=0;i<menuArray;i++){    var tmp:MenuItem = new MenuItem(menuArray[i]);    tmp.id=i;}


in the coding for these menuitems is a line that dispatches a custom event when one of them is selected. I would like all of the menuItems to react when one is pressed. Leaving out the extraneous stuff my coding is:

ActionScript Code:
public static const MENU_SELECTED:String="MENU_SELECTED";addEventListener(MenuItem.MENU_SELECTED, menuReset);function menuDownListener(e:MouseEvent):void{     dispatchEvent(new Event(MenuItem.MENU_SELECTED));}


in my menuReset function I have a trace command that displays the id variable I set up for each menu item.
trace(e.currentTarget.id);

The problem is that it only ever runs the menuReset function for the menu item that gets pressed. None of the other items react to the listener?

What am I missing here?

Thanks guys!

Custom Event Dispatcher
in MyClass i have event listener, it never will be called although i dispatch my event from my custom eventdispatcher...can anyone tell me what is wrong with this code?

Custom Event Propogation
I'm currently calling a custom event from one class and adding another class as the listener.
Previously the stage was the listener which worked perfectly but it seems when another class is listening there needs to be something more in order for anything to happen.

Any help is greatly appreciated.

Creating A Custom Event
Hi guys,

I'm currently building a flex media player for a client and I am looking to have the controls fade out when the user has been inactive for 3 seconds. I have found an actionscript class that prints a message in a text box after a set period.

However, I need to convert this class into an extension of the effect class. This is where I become stuck.

Can you please help?

The class I currently have is:

package utils{
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.utils.clearInterval;
import flash.utils.setInterval;

import mx.core.Application;

public class IdleUserWatcher{
// is the user active?
private var __isActive : Boolean = false;
// the id for the interval
private var intervalID : Number;
// how long to wait before calling is idle... default is 1 second
private var idleTime : Number = 1000;
// a list of all objects listening
private var listeners : Array;
// readonly property for isActive

public function get isActive () : Boolean{
return this.__isActive;
}

public function IdleUserWatcher(idleTime:Number = 1000){
Application.application.addEventListener(MouseEven t.MOUSE_MOVE, this.onMouseMove);
Application.application.addEventListener(KeyboardE vent.KEY_DOWN, this.onKeyDown);
listeners = new Array();
}

/* Adds a listener to the listeners list */
public function addListener(listener:Object):Boolean{
for (var i:Number=0; i<listeners.length; i++){
if (this.listeners == listener) return false;
}
this.listeners.push(listener);
return true;
}

/* Removes a listener from the listener list */
public function removeListener(listener:Object):Boolean{
for (var i:Number=0; i<this.listeners.length; i++){
if (this.listeners == listener){
this.listeners.splice(i, 1);
return true;
}
}
return false;
}

/* Events */
private function onKeyDown(event:KeyboardEvent):void{
this.setIdleInterval();
}

private function onMouseMove (event:MouseEvent):void{
this.setIdleInterval();
}

/* Private Methods */
private function setIdleInterval():void {
this.__isActive = true;
clearInterval(this.intervalID);
this.intervalID = setInterval(this.broadcastIdle, this.idleTime);
}

private function broadcastIdle():void{
this.__isActive = false;
for (var i:Number=0; i<this.listeners.length; i++) {
this.listeners.onUserIdle();
}
clearInterval(this.intervalID);
}

}
}


How do i then make it so when the user is idle I can then call an mx:fade effect?

Thanks

Custom Event In Another Class
hi,

i have a simple class that extends MovieClip, and I need to issue a custom event to all instances of this class as well as to any other listeners.

most of the stuff in the file below is not relevant, really just the portion that deals with the custom event. i include the other stuff for reference. i've included comments on the lines with event statements.

i'm not sure if i have the structure correct. i've implemented IEventDispatcher and added a listener withing the class constructor. however, I'm not getting any events firing (which it should do upon a mouse click).

what am I doing wrong here, and will any non class objects be able to listen to this event though it's defined within the class? everything compiles and runs, but the event is not being dispatched.


thanks! -- lou

Code:

package {

   import flash.display.MovieClip;
   import flash.events.MouseEvent;
   import flash.display.Sprite;
   import flash.events.Event;
   import flash.events.IEventDispatcher;
   import flash.events.EventDispatcher;

   public class NumberButton extends MovieClip implements IEventDispatcher {
      var id:Number;
      var whichPic:String;
      var highlightBox:Sprite;
      var selectedBox:Sprite;
      var isSelected:Boolean;
      private var dispacher:EventDispatcher;
      public static  const DESELECT_OTHERS:String = "DeselectOthers";   //define custom event string

      public function NumberButton() {
         //trace("new NumberButton");
         this.addEventListener(MouseEvent.CLICK, onClick);
         this.addEventListener(MouseEvent.MOUSE_OVER, showBox);
         this.addEventListener(MouseEvent.MOUSE_OUT, hideBox);
         this.addEventListener(DESELECT_OTHERS, deselectBox);     //let all instances of this class listen for custom event
                                                                                           //call deselectBox when dispatched
         dispacher = new EventDispatcher();      // initialize custom event dispatcher

         isSelected=false;
         highlightBox= new Sprite();
         highlightBox.graphics.lineStyle(2, 0xFF9900);
         highlightBox.graphics.beginFill(0x0000ff,0);
         highlightBox.graphics.drawRect(1,-1,28,10);
         highlightBox.graphics.endFill();
         this.addChild(highlightBox);
         highlightBox.visible = false;

         selectedBox= new Sprite();
         selectedBox.graphics.lineStyle(1, 0x000000);
         selectedBox.graphics.beginFill(0x000000,.18);
         selectedBox.graphics.drawRect(1,-1,28,10);
         selectedBox.graphics.endFill();
         this.addChild(selectedBox);
         selectedBox.visible = false;
      }
      
      public function setID(idNum:Number):void {
         id=idNum;
      }

      public function setPic(whichPicArg:String):void {
         whichPic=whichPicArg;
         trace("Creating NumberButton:   id = " + id + ",    whichPic = " + whichPic);
      }
      
      private function onClick(evt:MouseEvent):void {
         isSelected = true;
         selectedBox.visible = true;
         trace(" * * * * * * clicked button " + id);
         dispacher.dispatchEvent(new Event(DESELECT_OTHERS));
      }

      private function showBox(evt:MouseEvent):void {
         highlightBox.visible = true;
      }
      
      private function hideBox(evt:MouseEvent):void {
         highlightBox.visible = false;
      }
      
      private function deselectBox(evt:Event):void {    //custom event handler
         selectedBox.visible = false;
         trace(" ################    HIDING button " + id);
         trace("                        Selected box = " + evt.target);
      }
      ///////////////////////////////////////////////////////////////////////
      
   }
}

Custom Event Performance Implications...
Am working on a site, was wondering what the effect might be on memory/performance were I to implement the following:

MovieClip's inherit a registerEvent and handleEvent function

registerEvent syntax:
this.registerEvent(eventName,eventFunction);

where eventName can be anything and eventFunction follows this format:

fobj=function(param){actions}

handleEvent follows this syntax:
this.handleEvent(eventType);

here's what it does:

*attempt to call event handler from internal events array, ie: this.events[eventType]();
*iterate through children movies
*if child movie has event handlers, and is set to receive custom events, it calls the handleEvent(eventType) on the child


recursive functions in the past seem to have been the bane of performance in flash apps.....anyone got any ideas what kind of considerations would i need to make?

.ns.

AS 2.0 Making A Custom Event Handler
hi, i am trying to make a custom event handler.

basically, here is an example.. i have 3 buttons...

so i want to make an event handler so i only have to write :

obj.onCustomHandler = function () {

}

and it detects a click to any of the buttons....

instead of having to this individually ..

button1.onPress = button2.onPress= button3.onPress = function () {

}


any help would be greatly appreciated. is this event possible? i am using it to make a component-like class .

Custom Cursor And Mouse Event
Hi,

In this code I've swapped the handcursor with a custom cursor from the library. When I move the cursor moves. That's fine. But the onClick event for the but_mc isn't working anymore. The code works fine when I don't use a custom cursor.

Code:
// when this invisible button is clicked, a new webcam image is loaded
but_mc.addEventListener(MouseEvent.CLICK, click_cam);
// load and scale the img from webcam
function load_cam():void{
var cam_request:URLRequest = new URLRequest("http://webcam");
var cam_loader:Loader = new Loader();
cam_loader.load(cam_request);
// load server img in holder
but_mc.holder_mc.addChild(cam_loader);
// loadlistener
cam_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, scale_cam);
// if loaded
function scale_cam(event:Event):void{
trace("cam loaded");
// scale img
var w_fact:Number = 1010/event.target.content.width;
var h_fact:Number = 550/event.target.content.height;
event.target.content.width *= w_fact;//6.4
event.target.content.height *= h_fact;//4.6;
trace(event.target.content.width);
trace(event.target.content.height);
}
}
// is called when but_mc is clicked
function click_cam(event:MouseEvent):void{
trace("click");
load_cam();
}
//
// my cursor // this code stops the but_mc event from working
stage.addEventListener(MouseEvent.MOUSE_MOVE,redrawCursor);
Mouse.hide();
var my_cursor:cursor = new cursor();
addChild(my_cursor);
// position cursor
function redrawCursor(event:MouseEvent):void
{
my_cursor.x = event.stageX;
my_cursor.y = event.stageY;
}
but_mc.buttonMode = true;
//
// load webcam img first time
load_cam();


So the question is why the but_mc.addEventListener(MouseEvent.CLICK, click_cam); stops working I add another eventlistener and the custom cursor. Hope someone can help. TIA for your time and help.

[F8] Problems Defining A Custom Event
Hi can someone tell me were I am going wrong here I can not seem to register a custom event. I am trying to raise an flash event when an external container accesses an function.

import flash.external.*;

var pushSuccess:Boolean = ExternalInterface.addCallback("button_pushed", null, pushed);
var releaseSuccess:Boolean = ExternalInterface.addCallback("button_released", null, released);
var externalAvala:Boolean = ExternalInterface.available;
trace(externalAvala)

var externalevent:Object = new Object();

AsBroadcaster.initialize(externalevent);

function pushed(Num) {
externalevent.broadcastMessage("button_pushed", Num)
//_root.application.DVD["B" + Num].gotoAndPlay(2);
trace("Buttton" + Num )
}

function released(Num) {
//externalevent.broadcastMessage("button_released", Num)
//trace(getObjectid(Num))
}

ExternalInterface.addCallback("button_released", null, released);
ExternalInterface.addCallback("button_pushed", null, pushed);

function ProcessEvent(){

trace("external event processed")
}
externalevent.addEventListener("button_pushed",Pro cessEvent)
var Binitialised:Boolean = externalevent.addEventListener("button_pushed",Pro cessEvent)
trace("Binitialised " + Binitialise)

Custom Class Event Listener
Hi all, Im very new to AS3, can someone please help. I have written my first class, call it CustomClass

Have called it from the main timeline first frame with:

var myCustomClass:CustomClass = new CustomClass(somedata);

In the main timeline, how do I get a second class or function to run once this is complete? Can I add something to my class to say when it is complete? I would like to be able to then have something like

myCustomClass.addEventListener(Event.COMPLETE, DoSomthingElse);

Please someone help, have been at this 9 hours straight and my eyes are popping out! !

Custom Component/Event Focus
I'm currently having issues with handling mouse events.
I've created a custom component that extends from UIComponent. I have 3 components of the same type being instantiated within this component. They are all made to be draggable. The issue occurs when you're dragging one over another the mouse will grab and drag both of these.

Is there a way to set focus to a component so that only it receives mouseEvents or some other way to avoid the mouse events going to the other components and just the one that was initially selected?

Sorry if I'm not clear enough if so just ask what you'd like me to specify.
Thanks guys

Custom Event Handler Easy
Hi all:

I was wondering if you guys could help, i need the code to create a custom event handler. The reason I need it is becausse i have a scene where a MC is duplicated 20 times, and each duplicate has its own code to bounce off walls, so on the screen there are 20 balls with different speeds and directions, bouncing off the walls, I am using the enterFrame method to check if the ball has touched a wall, so each of the 20 balls its cheking the same and each of them with the enterFrame method so my game is very slow. I was thinking of instead of using the enterFrame method using a custom one something like this

onClipEvent(this._x>300){
(bounce off code)
}

I did a little research and found something about dispatchevent and classes I really dont know about that stuff i was wondering if you guys could give me a n easier answer. thanks

Custom Event When Method's Tweens End
Hello.

For now I merely want to know if what I need is possible to accomplish in AS3. I think so, but not sure how.

I have several class methods that each perform several tweens and I need to know when those tweens end so I can act on that information. The tweens are class variables, so they'll be used by several methods. Because of this, I cannot - ok, I can, but it's inellegant at the very least - respond solely to the TweenEvent.FINISH and other tween events.

So what I need is for the methods to fire custom events when all the tweens they're performing finish. That way, I can create nice event handlers that deal with whatever I need to happen afterwards.

Is this possible? I'm not sure what sort of parameters would be involved in a solution.

Thanks in advance.

Custom Event Quick Question
I am trying to sort out a seemily wierd issue. My main Document Class has
the following self-descriptive line


Code:
addEventListener(GameEvent.STATUS,GameEventOccurred );
I am able to dispatch, listen for and successfully aces the custom GameEvent without any problem on the first dispatch...then I no longer seem to be able to listen for the GameEvent...even though i do not remove the listener that I quoted above.

My main question is..is there any way for me to know if something is still listening for an event....ie is there anything like "hasEventListener" that I could use from the document class in order to tell whether or not i'm still listening for a custom event?

Copyright © 2005-08 www.BigResource.com, All rights reserved