How To Get Event In Component Class?
Hello,
I want to make ActionScript 2 component. I have one movie clip (my component). Inside it I have ComboBox with instance name myMovieClip. The class associated with component is
Code: class mypackage.MyComponent extends Object{
static var symbolName:String = "parser.Deroulateur"; static var symbolOwner:Object = parser.Deroulateur;
private var myMovieClip:MovieClip;
function MyComponent(){
}
function change():Void{ trace("change"); }
} I want to work with event change of the ComboBox. If I put it on the ComboBOx instance like this:
Code: on(change){ trace("change"); } it works OK but how to get it in my class? I tried with method
Code: function change():Void{ trace("change"); } but it just doesn't work
Please help.
Thank you
FlashKit > Flash Help > Flash ActionScript
Posted on: 12-22-2003, 10:16 AM
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
How To Get Event In Component Class?
Hello,
I want to make ActionScript 2 component. I have one movie clip (my component). Inside it I have ComboBox with instance name myMovieClip. The class associated with component is
class mypackage.MyComponent extends Object{
static var symbolName:String = "parser.Deroulateur";
static var symbolOwner:Object = parser.Deroulateur;
private var myMovieClip:MovieClip;
function MyComponent(){
}
function change():Void{
trace("change");
}
}
I want to work with event change of the ComboBox. If I put it on the ComboBOx instance like this:
on(change){
trace("change");
}
it works OK but how to get it in my class? I tried with method
function change():Void{
trace("change");
}
but it just doesn't work
Please help.
Thank you
MovieClipLoader OnLoadInit Event AND Loader Component Complete Event
What´s the difference beetwen the Loader complete event and MovieClipLoader onLoadInit. The manual says onLoadInit is called after the code on the first frame of the loaded clip gets executed, so, it´s better to use onLoadInit if you want to manipulate the loaded asset via code.
So, if anyone could clarify the following points to me, I would be grateful!
- Does the complete event of the Loader component have the same behaviour?
- How does MovieClipLoader knows that the code on the first frame of the loaded assets got executed?
Thanks,
Marcelo.
Child Class Trigger Event For Parent Class
is there a way for a parent class to listen to a variable in a subclass, and when it changes, run a function?
This seems like a pretty simple thing to do. I'm trying to keep my subclass independent of my main class, so i just have a variable that is set to false, and when its finished, it sets the variable to true.
The only thing i can think of is having an onEnterFrame that keeps checking the variable...but it seems like an event would be more efficient.
thanks!
Why Is An Event On One Class Object Being Broadcast For All Instances Of That Class?
I have a custom class called McText which extends MovieClip, and includes an input text field. That class has a function to register itself as a listener to Key - Key.addListener(this). It does not register by default.
There are multiple instances of McText. But even though I only call the function to register on one of those instances, ALL of them fire an onKeyDown function when i type into their text field, regardless of whether i've registered that particular object to Key or not. I register one, I register them all.
This is a little annoying because I use this class everywhere, and I want to be able to assign an onKeyDown function for only one of them. At first i tried writing that function outside of the class itself, as in:
classObject.onKeyDown = function()
But that, perhaps unsurprisingly, created an onKeyDown function for every instance again.
I thought to myself "I know, I'll register McText with Key by default (in the constructor), write an McText.onKeyDown function in the class itself, and then get that function to use a broadcaster". The idea being that onKeyDown will fire on all of them, but the broadcaster will be registered to a specific listener on an object by object basis.
So I did that, and created a function to register a broadcaster listener. I then created a broadcaster listener in a seperate, different, class, throw it to the McText function so it registers with its broadcaster and guess what? Now that listener receives an event from every instance of that class.
There's no explicit use of static vars or functions anywhere.
Sorry for the long question, but can anyone enlighten me as to what's going on? You get virtual chocolate if you do
How Do You Listen In One Class For A Custom Event Dispatched From Another Class?
I am not sure how to word this, so here is what I would like to happen:
MyDocumentClass contains an instance of MyItem and MyItemManager. MyItem will fire an ItemEvent.ITEM_CHANGED event. I want MyItemManager to listen and react to that event. Possible? Here's my code:
ItemEvent.as:
ActionScript Code:
package
{
import flash.events.Event;
public class ItemEvent extends Event
{
public static const ITEM_EVENT:String = "itemEvent";
public function ItemEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false)
{
super(type, true);
}
public override function clone():Event
{
return new ItemEvent(type);
}
public override function toString():String
{
return formatToString("ItemEvent", "type", "bubbles", "cancelable");
}
}
}
MyDocumentClass.as:
ActionScript Code:
package {
import flash.display.Sprite;
import MyItem;
import MyItemManager;
public class MyDocumentClass extends Sprite
{
public var item:MyItem;
public var manager:MyItemManager;
public function MyDocumentClass()
{
item = new MyItem();
manager = new MyItemManager();
item.dispatchCustomEvent();
}
}
}
MyItem.as:
ActionScript Code:
package
{
import flash.display.Sprite;
import flash.events.EventDispatcher;
import ItemEvent;
public class MyItem extends Sprite
{
public function MyItem()
{
}
public function dispatchCustomEvent():void
{
dispatchEvent(new ItemEvent(ItemEvent.ITEM_EVENT));
}
}
}
MyItemManager.as:
ActionScript Code:
package
{
import flash.display.Sprite;
import ItemEvent;
import flash.events.EventDispatcher;
public class MyItemManager extends Sprite
{
public function MyItemManager()
{
addEventListener(ItemEvent.ITEM_EVENT, handleItemEvent);
}
public function handleItemEvent(e:ItemEvent):void
{
// do something here
}
}
}
Event From Class
Hi!..
before asking question i would tell the people that i am new to OOPS.... so i want to make a custom class and dispatch some events from that class....
this is custom class
Quote:
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class SomeThing extends Sprite
{
public function SomeThing ():void
{
init ();
}
private function init ():void
{
stage.addEventListener (MouseEvent.MOUSE_DOWN, doSome);
stage.addEventListener (MouseEvent.MOUSE_UP, doSome);
stage.addEventListener (MouseEvent.CLICK, doSome);
stage.addEventListener (MouseEvent.DOUBLE_CLICK, doSome);
}
private function doSome(eve:MouseEvent):void
{
trace (eve.type);
}
}
}
when i instantiate it like this.... assuming that the class is in same directory as the .fla...
Quote:
var sone:SomeThing = new SomeThing()
it gives me small error like this.....
Quote:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at com.drmax.ui::SomeThing/init()
at com.drmax.ui::SomeThing()
at Untitled_fla::MainTimeline/frame1()
can some one tell me why its happening and how can i add events on stage from a class...
Creating A Component Within A Component Class
Basically I have a component with I have associated a class with - and then attached it to stage using attachMovie and make references to it using its linked name which works great. However within this class I want to attach another movie clip component - which works however how to I reference this second component from this class using linkage doesnt work neither does assigning it to variable. The only way is to call the class - which gives undesired results.
What is the proper way to have a component within a component?
Dispatch Event From One Class To Another
Hi,
Could someone point me to a simple example of how to dispatch an event from one class that another class is able to listen to (or do you always have to create an instance of the class which dispatches the event within any class that wants to be notified?).
In a nutshell, I want a few different classes to react to (listen for) a particular event.
Thanks
Robin.
Event Class Issues
Hi guys, I need a real quick fix for a project due tonight!
Ok, it's basically for an on screen keyboard. My client fed me graphics of both up and down states for the keys, and the way I've set it up is to have a MC of each key's up state and down state, and an invisible MC to act as the actual button to trigger the event.
So for the "A" key, I have the A Up state: "A_Up", the A Down state: "A_Down", and the button "A". To get the keystroke to work, I have a dynamic text field "field" being fed by the string "words". Then I have the following code to get the key stroke to actually work:
Code:
A.addEventListener("click", addLetter);
function addLetter(evt:Event)
{
words = words + evt.target.name;
field.text = words;
}
Here's my problem. I need to also target the visibility of the A Up and Down states. I tried using:
Code:
function addLetter(evt:Event)
{
evt.target.name + "_Down".visible = false;
words = words + evt.target.name;
field.text = words;
}
but it didn't work (I knew it was a long shot).
Anybody have any suggestions?
Thanks so much!
Help How Do I Dispatch An Event From One Class To Another?
Hi!
I want to dispatch an event from the MODEL(Stations) to the VIEW, when the Stations.onResult() function has been executed.
How do I do this??
This is the MODEL:
Code:
package classes.model {
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import XMLList;
import mx.collections.XMLListCollection;
import flash.system.Security;
public class Stations {
private var _httpService:HTTPService = new HTTPService();
private var _xmlData:XMLList = new XMLList();
[Bindable]
private var _xmlDataCollection:XMLListCollection;
public function Stations():void {
_httpService.url = "http://localhost/te.php";
_httpService.useProxy = false;
_httpService.method = "POST";
_httpService.resultFormat = "e4x";
_httpService.addEventListener(ResultEvent.RESULT, onResult)
_httpService.send();
}
public function onResult(event:ResultEvent):void {
_xmlData = event.result.fields.field;
_xmlDataCollection = new XMLListCollection(_xmlData);
}
public function getTheData():XMLListCollection {
return _xmlDataCollection;
}
}
}
This is the VIEW:
Code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" initialize="init()">
<mx:Script>
<![CDATA[
import classes.model.Stations;
import mx.collections.XMLListCollection;
[Bindable]
private var stationData:Stations = new Stations();
private function init():void {
trace (stationData.getTheData());
}
]]>
</mx:Script>
<mx:VBox>
<mx:DataGrid id="stationGrid" dataProvider="{stationData.getTheData()}" />
</mx:VBox>
</mx:Panel>
Please help!
[as2]Event Listener In A Class... HELP
I can't seem to figure out how to use an event listener in an AS2 class. Someone please help me. I feel like a moron. Here's my code, and please excuse if it's completely wrong, I'm not very good at classes yet:
PHP Code:
import flash.filters.BlurFilter;import flash.ui.Mouse.*;import flash.geom.Point.*;class ProximityBlur extends MovieClip{ var targetX:Number; var targetY:Number; var distance:Number; var myStage:MovieClip; //stage var bf:BlurFilter; var mLis:Object = new Object(); var targetClip:MovieClip; function ProximityBlur(myClip:MovieClip, movieHome:MovieClip) { targetClip = myClip; targetX = targetClip._x; targetY = targetClip._y; myStage = movieHome; bf = new BlurFilter(0,0,3);//I've used multiple methods trying to get this to work... thus the reason you see both of the lines below... myStage.onMouseMove = blurClip(targetClip); Mouse.addListener(mLis); } mLis.onMouseMove = function()//ERROR on this line! "This statement is not permitted in a class definition" { distance = Math.sqrt(((targetX - _xmouse)*(targetX - _xmouse)) + ((targetY - _ymouse)*(targetY - _ymouse))) trace(distance); } function blurClip(myMC:MovieClip) { distance = Math.sqrt(((targetX - _xmouse)*(targetX - _xmouse)) + ((targetY - _ymouse)*(targetY - _ymouse))) trace(distance); if(distance <= 100) { bf.blurX = distance/10; bf.blurY = distance/10; myMC.filters = [bf]; } }}
Any help would be very much appreciated. I just don't understand why I can't use a mouse event in an AS2 class. Oh, I forgot to mention that I got this working perfectly just coding it on the timeline, but I want to make it reusable and I can't seem to get how to turn it into a class.
Possible To Dispatch Event Within A Class?
Is there a way where you can dispatch an event from a class? Like for example, with the LoadVars object you can listen to the onLoad event and the event triggers when the object has loaded. I want to do something like that. I have searched a lot and tried but all in vain
This is my problem:
I have created a class named Settings and with this class I create an object with two members, fontSize and speech. Font size is a number whilst speech is a boolean. I have defined the getter/setter methods for both the fontSize and speech members of the class. What I need to do is that when I change the value of the fontSize or speech, an event is dispatched. I have searched on dispatching events and this is what I am doing to dispatch an event. See my code listed below for the class Settings.as
PHP Code:
class Settings {
//private members for the class Settings
private var _fontSize:Number;
private var _speech:Boolean;
//Declare the dispatchEvent method as a member of this class (found in help)
private var dispatchEvent:Function;
//Constructor method
public function Settings(fontSize:Number, speech:Boolean) {
//initialize the class so it can dispatch events (also found in help)
mx.events.EventDispatcher.initialize(this);
this._fontSize = fontSize;
this._speech = speech;
}
//Getter method for fontSize member
public function get fontSize():Number {
return _fontSize;
}
//Setter method for fontSize member
public function set fontSize(nFontSize:Number):Void {
_fontSize = nFontSize;
//Here i want to dispatch an event since the font size member has changed.
//This is the way I found out about dispatching events
dispatchEvent({type:"onFontChange", target:this});
}
//Getter method for speech member
public function get speech():Boolean {
return _speech;
}
//Setter method for speech member
public function set speech(bSpeech:Boolean):Void {
_speech = bSpeech;
//Here i want to dispatch an event since the speech member has changed.
//This is the way I found out about dispatching events
dispatchEvent({type:"onSpeechChange", target:this});
}
}
Now after having created that class, this is the way I am listening to the event I should be dispatching once the Settings object have been created and one property of the object have changed:
PHP Code:
//Creating the Settings object
var mySettings:Settings = new Settings(12,true);
//Creating the listener object
var myListener:Object = new Object();
//Setting the object to listen to the onFontChange event
myListener.onFontChange = function(oEvent:Object):Void {
trace("New Font Size: " + oEvent.target.fontSize);
trace("Speech is: " + oEvent.target.speech);
}
mySettings.addEventListener("onFontChange",myListener);
mySettings.fontSize = 10;
When I am compiling the swf, it is giving me this error:
PHP Code:
**Error** Scene=Scene 1, layer=actions, frame=1:Line 35: There is no method with the name 'addEventListener'.
mySettings.addEventListener("onFontChange",myListener);
Total ActionScript Errors: 1 Reported Errors: 1
Is there any one can help me with dispatching events within a class? Else inform me if it is possible to do so or not?
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,
Getting An Event From A Static Class
I have a Settings/Config class. All its methods are static. The first thing I do in my swf is to load the settings in the form of an XML file. As the rest of my code relies on this file being loaded, I need to listen for an onLoad event from this Class before running it.
Can't use EventDispatcher as the 3 functions (addEventListener/removeEventListener/dispatchevent) are not static,
So how can I get an event out of it?
Thanks
Event Class Issues
Hi guys, I need a real quick fix for a project due tonight!
Ok, it's basically for an on screen keyboard. My client fed me graphics of both up and down states for the keys, and the way I've set it up is to have a MC of each key's up state and down state, and an invisible MC to act as the actual button to trigger the event.
So for the "A" key, I have the A Up state: "A_Up", the A Down state: "A_Down", and the button "A". To get the keystroke to work, I have a dynamic text field "field" being fed by the string "words". Then I have the following code to get the key stroke to actually work:
Code:
A.addEventListener("click", addLetter);
function addLetter(evt:Event)
{
words = words + evt.target.name;
field.text = words;
}
Here's my problem. I need to also target the visibility of the A Up and Down states. I tried using:
Code:
function addLetter(evt:Event)
{
evt.target.name + "_Down".visible = false;
words = words + evt.target.name;
field.text = words;
}
but it didn't work (I knew it was a long shot).
Anybody have any suggestions?
Thanks so much!
Dispatching Event To Another Class
I've searched through this forum and elsewhere, and I still need to some help.
I have an ImageContainer class (extends movieClip) that creates a bunch of LoadImage classes (extends Sprite) that essentially has loader to load in a jpg and gets added as a child to the ImageContainer class. Works great.
Now it's time to attach listeners to events of loading the image. I see in the adobe docs, it uses this in the constructor:
ActionScript Code:
configureListeners(loader.contentLoaderInfo);
to fire this function to add the listeners:
ActionScript Code:
private function configureListeners(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
//etc...
}
This works. Now what I wanted is for my ImageContainer class to be able to listen to both the ProgressEvent.PROGRESS and Event.COMPLETE events to instantiate a preloader movieClip I have in the library, and move on to the next image when the last one is complete (sequential loading).
I got this to work by adding the line
ActionScript Code:
dispatchEvent();
in the listener, and adding the listeners in the ImageContainer.
Ok questions. I have read pretty much unanimously here that the way to have another class listen to another's events, is by extending the EventDispatcher class (in my case the LoadImage class instead of Sprite). I couldn't get to work, this needs to extend a Sprite to be added as a child.
So Is this the preferred method in this case? Been on a learning trip with classes and AS3. I want to try to use the preferred or best practices.
Thanks in advance.
Detecting An Event In A Class.
Hi,
My main stage contains an object called StartCat of type CenterCategory(that I have created and which extends sprite). That object contains all the graphics & buttons that are loaded in that class.
Inside that object, Clicking on one of the buttons should clear all the data from the stage (everything that was loaded inside the class and a new object of type CenterCategory is loaded with new graphics and buttons)
I am not sure how to "tell" the stage to listen when a button is clicked inside that object. How do I transfer that kind of information?
I have an addEventListener on each button on screen that calls a function.
What should that function do so the stage loads a new object of type CenterCategory?
In a nutshell, what i am writing is a simple website with a line of buttons.
each button has an array of sub buttons which are loaded instead of all the data on screen.
Another small issue I'm having trouble with
The CenterCategory has some variables inside it and some event listeners.
If I set in the stage: StartCat = null, will it clear all the memory of the variables inside the class, or should i have a private function which is called inside that class that clears all the variables to null?
Thanks a lot,
Guy
How Do I Dispatch An Event From One Class To Another?
Hi!
I want to dispatch an event from the MODEL(Stations) to the VIEW, when the Stations.onResult() function has been executed.
How do I do this??
This is the MODEL:
ActionScript Code:
package classes.model {
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import XMLList;
import mx.collections.XMLListCollection;
import flash.system.Security;
public class Stations {
private var _httpService:HTTPService = new HTTPService();
private var _xmlData:XMLList = new XMLList();
[Bindable]
private var _xmlDataCollection:XMLListCollection;
public function Stations():void {
_httpService.url = "http://localhost/te.php";
_httpService.useProxy = false;
_httpService.method = "POST";
_httpService.resultFormat = "e4x";
_httpService.addEventListener(ResultEvent.RESULT, onResult)
_httpService.send();
}
public function onResult(event:ResultEvent):void {
_xmlData = event.result.fields.field;
_xmlDataCollection = new XMLListCollection(_xmlData);
}
public function getTheData():XMLListCollection {
return _xmlDataCollection;
}
}
}
This is the VIEW:
ActionScript Code:
<?xml version="1.0" encoding="utf-8"?>
<mx:Panel xmlns:mx="http://www.adobe.com/2006/mxml" initialize="init()">
<mx:Script>
<![CDATA[
import classes.model.Stations;
import mx.collections.XMLListCollection;
[Bindable]
private var stationData:Stations = new Stations();
private function init():void {
trace (stationData.getTheData());
}
]]>
</mx:Script>
<mx:VBox>
<mx:DataGrid id="stationGrid" dataProvider="{stationData.getTheData()}" />
</mx:VBox>
</mx:Panel>
Please help!
Using Event Listeners In A Class
Hello, I've been trying to get into classes recently, and have hit a problem using event listeners in a class.
I've been triggering a function in my class on a FileReference event (also in my class). The problems is that the function runs, but can't see any of my class variables.
Below is a simplified example, which will output: "Message is: undefined"
Thank you for any help you can give me,
Cheers,
James
Code from flash file:
Code:
var myTest = new Test();
Code from Test.as:
Code:
import flash.net.FileReference;
class Test{
private var msg:String;
private var file:FileReference;
private var fileListener:Object;
public function Test(){
msg = "Hello, Can You See Me?";
file = new FileReference;
fileListener = new Object();
file.addListener(fileListener);
fileListener.onSelect = selectedFiles;
file.browse();
}
public function selectedFiles(f:FileReference){
trace("Message is: " + msg);
}
}
AS 3.0: Extending Event Class
I am having trouble trying to figure out how to properly extend the Event class to add parameters to events. Here is what I have. If anyone knows how to do this properly please let me know.
Attach Code
package internalAssets{
import flash.events.Event;
public class DomainEvent extends Event{
//local variables
public static var COMPLETE:String = Event.COMPLETE;
public var domain:ApplicationDomain;
//constructor function
public function DomainEvent(type:String, domain:ApplicationDomain, bubbles:Boolean = false, cancelable:Boolean = false){
this.domain = domain;
}
}//end of class
}//end of package
Progress Event In Class
Hi, I'm trying to get a grip on writing classes. I have a simple preloader class which sort of works. When I trace _percentLoaded from within the class the percentages are output when I add the class to an fla. But, if I trace _percentLoaded from the fla I get NaN. Is there a way to pass the progress event data into the fla? Thanks
Attach Code
package com.zeno.interfaces
{
import flash.net.URLRequest;
import flash.display.*;
import flash.events.*;
public class SimpleLoader extends MovieClip
{
private var _address:String;
public var _percentLoaded:Number;
public function SimpleLoader (_address:String)
{
var myLoader:Loader = new Loader();
addChild (myLoader);
var myRequest:URLRequest = new URLRequest (_address);
myLoader.load (myRequest);
myLoader.contentLoaderInfo.addEventListener (Event.COMPLETE, swfLoaded);
myLoader.contentLoaderInfo.addEventListener (ProgressEvent.PROGRESS, swfProgress);
var percent:Number;
}
private function swfLoaded (event:Event):void
{
trace ("loaded");
}
public function swfProgress (event:ProgressEvent):void
{
var swfLoadInfo:LoaderInfo = LoaderInfo(event.target);
_percentLoaded = swfLoadInfo.bytesLoaded/swfLoadInfo.bytesTotal*100;
trace (Math.floor(_percentLoaded));
}
}
}
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;
}
}
}
Dispatching An Event From One Class To The Other
I've been racking my head hitting walls at all corners over this issue. Heh, if I had any hair on my head it would have been all ripped out hours, no days ago! Okay, hours. =)
The Problem:
I have two document classes. The main document class creates a empty movieClip and adds it to the stage in which the second document classes published swf is loaded into. The second document class has a button component on the stage in which once clicked just traces 'hello' to the output window.
What I want to do is upon clicking this button a Event is dispatched from the second document class, to the main document class. Now, I've Googled everything in this known world and have tried to implement examples to no avail. I'm really at a loss right now yet I stubbornly intend to keep banging my head against the problem.
Below I have pasted both document classes minus the examples I've tried to implement thus far.
Any help with this issue will be most graciously appreciated!
~e
Attach Code
Main document class
package com
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.net.URLRequest;
import com.Control_Events;
public class Main_Events extends MovieClip
{
public var emptyClip:MovieClip;
public function Main_Events()
{
emptyClip = new MovieClip;
stage.addChild(emptyClip);
loadClip();
}
public function loadClip():void
{
var url:URLRequest = new URLRequest('button_events.swf');
var ldr:Loader = new Loader();
emptyClip.addChild(ldr);
ldr.load(url);
}
}
Second Document Class
package com
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class Button_Events extends MovieClip
{
public function Button_Events()
{
tButton.addEventListener(MouseEvent.CLICK, tButton_onClick);
}
public function tButton_onClick(e:MouseEvent):void
{
trace('hello');
}
}
}
Class Event Handlers
Hi all, I’m trying to create a basic movie control with a progress bar class. It will have a draggable playhead that will allow you to scrub the timeline. I have the basic ground work for the progress bar class. It assigns properties and names ms to use for the class on the stage. Inside the mcs I have a handle which allows you to drag and scrub the timeline.
I am trying to assign events to the handle bar for dragging and require some properties of the class to do so. As of now I am assigning the button events in the class so at runtime when creating the instance the handle is assigned its events. The issue is I can’t get the properties in the class because of scoping. One I define events in the class the are targeted and therefore outside the class.
My question is where should one assign mouse events for the class parts? And in doing so, if a class has properties to use how do you access them?
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);
}
///////////////////////////////////////////////////////////////////////
}
}
Problem With Event Handlers In Class Def.
EDIT: ok so I found a working solution but I am confused as to why I need it for the code to work...what I did was create property for the object to reference itself...could anyone explain why I had to do this. solution in code:
Code:
function Ball () {
//SOLVED by creating a reference to itself
this.me = this;
//define callback for onPress event
this.onPress = function () {
//HAVE TO REFERENCE this WITH this.me ... WHY?
this.me.hit();
//_root method that DOES execute
_root.pressed();
}
}
Im having problems directing event callbacks, defined for a class, to custom methods defined for the class. I assume its a scope problem but I can't figure it out. Below is my stripped down code to really isolate the problem. For some reason when I target a method defined in _root, it executes, but nothing happens when I target a class method (comments in code explain this). You can cut and paste, but remeber that in order for this movie to work you need to create a library symbol and set its linkage id to "BallSymbol"... also export it. Thanks for the help. Flash MX btw.
Put this on main timeline:
Code:
//BALL CLASS
function Ball () {
//define callback for onPress event
this.onPress = function () {
//method I want to execute but DOESNT
this.hit();
//_root method that DOES execute
_root.pressed();
}
}
//make MC superclass
Ball.prototype = new MovieClip();
//hit() method for Ball class
Ball.prototype.hit = function () {
trace("hit");
}
//THIS EXECUTES ON THE TIMELINE
//CREATE AN INSTANCE ON STAGE AND INCLUDE IT IN AN MC FROM LIBRARY
//just a holder
_root.createEmptyMovieClip("holder_mc", 1);
//obj instance
var obj = new Ball();
//attach symbol from lib and associate it with obj
holder_mc.attachMovie("BallSymbol", "1_mc", 1, obj);
//the pressed() method
_root.pressed = function () {
trace("rootpress");
}
Still Struggling With An OnLoad Event For A New Class
Hi all,
In my post yesterday I said I solved my problem.. well.. almost..
I got
- 1 fla file to test my classes.
- 1 AS file for the class RSSFeed
- 1 AS file for the class RSSItem
From the fla file i instantiate a new RSSFeed:
Code:
var feed2:RSSFeed = new RSSFeed("http://nu.nl/deeplink_rss2/index.jsp?r=Algemeen"); // sample RSSfeed
stop();
I also got a callBack function (an icky, emergency solution for the moment..)
Code:
callBack = function(obj){
_global.intFeeds = intFeeds - 1;
trace("callback: "+obj.ItemCollection[0].Title); // just a test value..
}
When making a new RSSFeed object this happens:
Private properties are set
XMLfeed is being fetched from server
Looping through XML while setting more private properties.
When it finds an <item> tag. It creates an RSSItem object and stores it in an array.
call _root.callBack(this) (so the fla knows it can do something with the created object)
This all is very icky. The best thing would be something like an onLoad event which you can call from the fla.
I extended the class from movieClip and tried some others, but i can't seem to get it working.
Anyone got experience in this and is willing to help me?
I included my files here for information and testing purpouses.
Catch Event In Extended Class
hi,
i created a class extended from MovieClip,
how can i catch the events of movieclip? like moving, sizing etc...
ha?
Avi.
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! !
Catching An Event Fired In Another Class
Hey Everyone,
I have one main class and two subclasses. The main class instantiates the two subclasses. One of the subclasses is a circle class that loads in images and masks them, and the other is a list class that lists out a bunch of buttons. I have over 200+ buttons being generated from an xml file in the list class. What I want to have happen is this:
On rollover of one of the list buttons, load the corresponding image into the circle class.
How do I add an event listener that fires upward into the main class so I can load the image into the circle class?
Attached is my current code.
Thanks, TK
Code:
//LIST CLASSSS!!!!!
package src
{
import com.onebyonedesign.utils.ContentScroller;
import flash.display.*;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class BLNavStation_List extends Sprite implements BLDisplayObject
{
public var ListContent:Sprite;
public var category:BLNavStation_Item;
private var ListBG:Sprite
private var ListMask:Sprite;
private var ListScroll:Sprite;
private var ListHolder:Sprite;
private var XMLObject:XML;
private var urlLoader:URLLoader;
private var urlRequest:URLRequest;
private var cs:ContentScroller;
private var AssetsLoaded:Boolean = false;
public var LIST_W:uint = 300;
public var LIST_H:uint = 500;
public function BLNavStation_List()
{
CreateList("http://localhost/phpengines/main_list_print.php");
}
public function reposition():void
{
if(AssetsLoaded){
//this.x = (stage.stageWidth)-(ListBG.width);
//this.y = (stage.stageHeight/2)-(this.height/2);
}
}
public function clean():void
{
}
private function CreateList(str:String):void {
//DRAW BACKGROUND
ListBG = new Sprite();
ListBG.graphics.lineStyle();
ListBG.graphics.beginFill(0xFFFFFF,0.2);
ListBG.graphics.drawRoundRect(0,0, LIST_W, LIST_H, 20, 20);
ListBG.graphics.endFill();
//DRAW MASK
ListMask = new Sprite();
ListMask.graphics.lineStyle();
ListMask.graphics.beginFill(0x000000, 0.2);
ListMask.graphics.drawRoundRect(5, 5, LIST_W-10, LIST_H-10, 20, 20);
//SET UP LISTAREA
ListContent = new Sprite();
ListContent.x = 5;
ListContent.y = 5;
ListContent.mask = ListMask;
//SET UP SCROLLBAR
ListScroll = new Sprite();
ListScroll.graphics.lineStyle();
ListScroll.graphics.beginFill(0x555555, 1);
ListScroll.graphics.drawRoundRect(LIST_W-5, 5, 15, 50, 5, 5);
ListScroll.graphics.endFill();
//SET UP XML CONTENT
urlRequest = new URLRequest(str);
urlLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, initListener);
urlLoader.load(urlRequest);
}
private function initListener(e:Event):void {
AssetsLoaded = true;
XMLObject = new XML(urlLoader.data);
var counter:uint = 0;
for each (var SUBJECT:XML in XMLObject.*) {
category = new BLNavStation_Item();
category.y = counter * 30;
category.text = SUBJECT.@NAME;
ListContent.addChild(category);
category.addEventListener(MouseEvent.CLICK, clickListener);
counter++;
}
addChild(ListBG);
addChild(ListMask);
addChild(ListContent);
addChild(ListScroll);
cs = new ContentScroller(ListContent, ListMask, ListScroll, 3, "vertical");
}
private function clickListener(e:MouseEvent):void {
trace(e.target.text);
}
}
}
Code:
//CIRCLE CLASSSSS!!!
package src
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.net.URLRequest;
public class BLNavStation_Circle extends MovieClip implements BLDisplayObject
{
private var CircleLoader:Loader;
public function BLNavStation_Circle()
{
}
public function loadImage(str:String):void {
CircleLoader = new Loader();
CircleLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
CircleLoader.load(new URLRequest(str));
}
public function reposition():void
{
this.x = (stage.stageWidth /2)-(this.width /2);
this.y = (stage.stageHeight/2)-(this.height/2);
}
public function clean():void
{
CircleLoader = null;
}
private function loadComplete(e:Event):void {
this.ImageTarget.addChild(e.target.content);
this.ImageTarget.mask = this.ImageMask;
}
}
}
Code:
//MAIN CLASSSSS!!
package src
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.*;
import flash.net.*;
import flash.system.*;
import flash.utils.*;
public class BLNavStation extends MovieClip implements BLDisplayObject
{
private var AssetsLoaded:Boolean = false;
private var navList:BLNavStation_List;
private var assetLoader:Loader;
private var assetRequest:URLRequest;
private var assetContext:LoaderContext;
private var assetList:Array;
private var assetHolder:*;
private var NavPortal:Class;
private var NavP:MovieClip;
public function BLNavStation()
{
assetLoader = new Loader();
assetRequest = new URLRequest("bl_navAssets.swf");
assetContext = new LoaderContext(false, ApplicationDomain.currentDomain);
assetLoader.contentLoaderInfo.addEventListener(Event.INIT, initListener);
assetLoader.load(assetRequest, assetContext);
}
public function clean():void {
//
}
public function reposition():void {
if(AssetsLoaded) {
if(stage.stageWidth >= 800){
NavP.reposition();
} else {
///
}
}
}
private function initListener(e:Event):void {
assetLoader.removeEventListener(Event.INIT, initListener);
AssetsLoaded = true;
assetHolder = e.target.content;
assetList = assetHolder.getAssets();
NavPortal = getDefinitionByName(assetList[0]) as Class;
NavP = new NavPortal();
addChild(NavP);
NavP.reposition();
navList = new BLNavStation_List();
addChild(navList);
navList.ListContent.addEventListener(MouseEvent.ROLL_OVER, clickFunction);
}
private function clickFunction(e:MouseEvent):void{
if(e.target == category){
trace("yep");
}
}
}
}
Dispatch Stage Event From Class
I'm setting up an event listener from the main timeline and creating an instance of a Game class called game as shown below. After the game object has been created I then want to call public functions on it from the timeline... but it seems that I a null handle on game when the event is dispatched... even though it is dispatched from the end of the Game class constructor.
Code:
var gameInit:Event = new Event("gameInit", true);
addEventListener("gameInit", loadGame);
var game:Game = new Game(strPlayerSide, xmlCampaign);
function loadGame(evt:Event):void {
//this function does run after dispatch is called
//from end of Game constructor
trace(game); //returns null
//perform actions on game... but unable to since game is null
//but if click on a button on stage that references game a
//second later game is now a valid object and I can run functions
}
In the Game class I'm dispatching the gameInit event on the timeline at the end of the class constructor. The trace in loadGame returns null... however I created a click MouseEvent on a MC on the stage and when I click it game is an object. It seems like a timing issue... by the time I have clicked the MC game is now an object.
I would think dispatching the timeline event at the end of the Game constructor would be the correct time for me to assume the game object is now valid and can run public functions on it from the timeline.
Thanks for any help,
Brent
Dispatching Instance Event From Class.
i need to dispatch an event to an instance of my class.
right now i am just doing the following.
in my class
Code:
function myClass(){
//do a bunch of stuff
onVarsLoaded();
}
public function onVarsLoaded():Void{
return;
}
and on my instance
Code:
var mycl:myClass = new myClass();
mycl.onVarsLoaded = function(){
//do stuff here.
}
this works, but im sure its not the correct way to do things.
whats the best way to do this?
Accessing Varibles In A Class From An Event
Here is my first OOP Actionscript.... just doing a quick loading script and i'm having problem accessing one of the private variables from an event handler
Code:
/* FRAME 1 */
#include "Arrays.as"
var global_loader:Load = new Load();
/* LOAD.AS */
class Load {
private var _totalPercentage:Number = 0;
private var _totalLoads:Number = 0;
private var _movieClipLoader:Object;
private var _movieClipTargets:Array;
private var i:Number;
public function Load() {
// each time a new class or load function is called we increment the counter
this._movieClipLoader = new MovieClipLoader();
this._movieClipTargets = new Array();
this._movieClipLoader.onLoadProgress = function(movieClip:Object, loadedBytes, totalBytes) {
movieClip["amount_loaded"] = loadedBytes/totalBytes
};
this._movieClipLoader.onLoadComplete = function(movieClip:Object) {
// THIS WILL HAVE TO DO UNTIL WE FIGURE IT OUT
// THIS IS WHERE THE TROUBLE STARTS
trace(this._movieClipTargets) // <--- I WANT TO USE THIS VARIABLE
_root.global_loader.removeClip(movieClip); // <---- THIS WORKS BUT IS STUPID !!!!
this._movieClipTargets.removeUnique(movieClip); // <-- THIS IS WHAT I REALLY WANT TO DO
_root.global_loader.removeClip(movieClip);
};
}
public function removeClip(movieClip:Object) { // <---- I SHOULDNT NEED THIS FUNCTION
trace("remove clip called");
this._movieClipTargets.removeUnique(movieClip);
trace(this._movieClipTargets)
}
public function addItem(fileURL:String, movieClip:Object) {
// each time a new class or load function is called we increment the counter
this._movieClipLoader.loadClip(fileURL, movieClip);
this._movieClipTargets.pushUnique(movieClip);
trace(this._movieClipTargets)
this._totalLoads++;
}
public function removeItem() {
// each time a new class or load function is called we decrement the counter
this._totalLoads--;
}
public function get movieClipTargets():Object {
return this._movieClipTargets;
}
public function set movieClipTargets(value:Array):Void {
this._movieClipTargets = value;
}
public function get totalPercentage():Number {
// this is where we calculate everything
this._totalPercentage = 0;
for(i = 0; i < this._movieClipTargets.length; i++) {
this._totalPercentage = this._totalPercentage + this._movieClipTargets[i]["amount_loaded"];
}
this._totalPercentage = Math.round((this._totalPercentage / this._movieClipTargets.length)*100)
if(isNaN(this._totalPercentage)) {
// not loading
this._totalPercentage = 100;
}
return this._totalPercentage;
}
public function set totalPercentage(value:Number):Void {
this._totalPercentage = value;
}
public function get totalLoads():Number {
return this._totalLoads;
}
public function set totalLoads(value:Number):Void {
this._totalLoads = value;
}
}
What is the best way to get the variable _movieClipTargets from the onlLoadComplete handeler?????
Thaniks anyone for help on this one... feeling stuck and stupid!
Andre
Class Instances And An OnMouseDown Event
Hi guys,
I'm having trouble wrapping my head around why this happens. If I create 2 instances and releated clips I get the following output no matter which of the MovieClips I click on.
parentButt_mc _level0.testClip2
parentButt_mc _level0.testClip1
Could somebody explain to me why this is happening? I could see it only ever returning 1 clip, but why both?
class TestClass{
var parentButt_mc:MovieClip;
public function TestClass (mc:MovieClip) {
this.parentButt_mc = mc;
var thisObj = this;
this.parentButt_mc.onMouseDown = function() {
trace("parentButt_mc " + thisObj.parentButt_mc);
}
}
}
Thanks in Advance,
Todd
Removing A Timer Event From Another Class
How do I remove a timer event from another class. Or how do I reference a timer in another class, this doesnt work: parent.parent.removeChildAt(2).timer.removeEventLi stener(...
or
parent.parent.gallery.timer.removeEventListener(.. .
Code:
private function handleClick (evt:MouseEvent)
{
parent.parent.removeChildAt(2).timer.removeEventListener(TimerEvent.TIMER, onTimer);
parent.parent.removeChildAt(2)
loadPage(parent.parent)
}
Basically I have a button that removes a Sprite but when I remove it I get this error message:
Quote:
Error #1009: Cannot access a property or method of a null object reference.
at com.edition.slideshow::SlideShow/:nTimer()
at flash.utils::Timer/flash.utils:Timer::_timerDispatch()
at flash.utils::Timer/flash.utils:Timer::tick()
Button Event Within My Document Class
Hi. I have the following code:
proceedBut.addEventListener(MouseEvent.CLICK, myLink);
function myLink(event: MouseEvent) {
var linkMain:URLRequest = new URLRequest("http://www.myURL/home.html");
navigateToURL(linkMain,"_self");
}
If I place a Movie Clip on my stage, give it the instance name "proceedBut" and place the above code on the same frame of my timeline, it works perfectly.
If I am using the document class 'Main.as', where does this code appear in the package?
When I do this:
package {
import flash.display.Sprite;
import flash.net.navigateToURL;
import flash.net.URLRequest;
public class Main extends Sprite {
public function Main() {
proceedBut.addEventListener(MouseEvent.CLICK, myLink);
function myLink(event: MouseEvent) {
var linkMain:URLRequest = new URLRequest("http://www.myURL/home.html");
navigateToURL(linkMain,"_self");
}
}
}
}
I get the error:
1046: Type was not found or was not a compile-time constant: MouseEvent.
Please help
Event Listener Not Working In My Class?
I made a thumbnail class for a client's website, but it won't work. Somehow, the event listener never gets called for Event.COMPLETE even though the picture is very obviously visible on the screen. It is supposed to trace "loading..." when the image loads, but it doesn't.
Here is my code, I don't really know what else to say.
Code:
package
{
import flash.display.MovieClip;
import flash.text.TextField;
import flash.display.Loader;
import flash.events.Event;
import flash.net.URLRequest;
public class thumbnail extends MovieClip
{
public var myimgurl:String;
public var loader:Loader;
public function thumbnail(imgurl:String, thename:String)
{
Name.text = thename;
myimgurl = "images/unzipped/"+imgurl;
loadingbar.visible = true;
loadingtext.visible = true;
loader = new Loader();
photo.addChild(loader);
loadimg();
trace(imgurl);
trace(thename);
}
private function loaded(e:Event):void
{
trace("loading...");
}
private function loadimg()
{
//photo -- name of MC that holds the image.
var URLreq = new URLRequest(myimgurl);
loader.load(URLreq);
loader.addEventListener(Event.INIT, loaded);
}
}
}
(That is my first AS3 class, by the way.)
Thanks for any help!
Dispatching Event From One Class And Listening In Another
Hi Actionscriptors,
I have a problem with dispatching custom event from one class and listening to that event in another class. I am new with the concept of dispatching custom event. So please bare if this explanation seems very long.
Scenario is
theres a main doc class which has a function called fButtonClicked. And i have a movieClip with a button in it and i have assigned that movieClip a class called mcButton. I have created a custom event class which dispatches an event called BUTTON_CLICK. and when i click on the button inside the mcButton movieClip i want to dispatch an event and i have added the listener to that event in the main document class.
the problem is
to call the function in custom event class that dispatches the event and to add listener to that event, i have to create an object of that class hence i have to create objects in both the classes. hence i am having problem with using the listener added in document class.
heres the code
CustomEvent.as - custom event class
ActionScript Code:
package
{
import flash.events.EventDispatcher;
import flash.events.Event;
public class CustomEvent extends EventDispatcher
{
public static var BUTTON_CLICK="button_click";
public function click ():void
{
dispatchEvent(new Event(CustomEvent.BUTTON_CLICK));
}
}
}
SampleEvent.as - document class
ActionScript Code:
package{
import flash.display.MovieClip;
import flash.events.Event;
public class SampleEvent extends MovieClip {
public var objCustomEvent:CustomEvent;
public var mc:MovieClip;
public function SampleEvent () {
mc = new mcButton(this);
addChild(mc);
objCustomEvent = new CustomEvent();
objCustomEvent.addEventListener(CustomEvent.BUTTON_CLICK,fLol);
}
public function fLol (evt:Event) {
trace("Button Clicked");
}
}
}
mcButton.as - movieClip class that contains the button that needs to dispatch an event
ActionScript Code:
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
public class mcButton extends MovieClip {
public var objEvent:CustomEvent;
public var docClass;
public function mcButton (_docClassRef) {
docClass = _docClassRef;
objEvent = new CustomEvent();
btn.addEventListener(MouseEvent.CLICK,fClick);
}
public function fClick (evt:MouseEvent) {
objEvent.click();
//docClass.objCustomEvent.click();
}
}
}
so as temporary solution i have created only one instance of that custom event class in document class and used that object to call the function in CustomEvent class to dispatch the event. Is there any way to make a static method to dispatch the event. so next time if i need to dispatch the event i could just say something like CustomEvent.click();
Thanks for taking out time and reading the whole thing.
Thanks,
Pratik. Velani
Event In One Class Invoking Function In Another
Hey all,
I know someone has asked this before, but I can't find the thread.
I have a class setting up an addEventListener:
ActionScript Code:
public function theIndex() {
for (var a:uint = 0; a < 100; a ++) {
var tf:TextField = new TextField();
tf.name = String(a);
tf.text = "mytext" +tf.name;
tf.x = 10;
tf.y = tf.textHeight * a*10;
tf.addEventListener(MouseEvent.MOUSE_DOWN,checkChapterS);
addChild(tf);
}
}
with the idea of invoking checkChapterS in the document class. Of course, when I compile it, it says it can't find checkChapterS. How do have the above class call that function which is located in the base class?
Thx
Listen For Custom Event From Another Class
hi,
I'm trying to listen in class A to a custom event fired in class B.
The listener in class A is however never triggered, unless I fire the event in class B from a timer...
Example Dispatcher class:
ActionScript Code:
package {
import flash.display.*;
import flash.events.*;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class Dispatcher extends Sprite {
public static const CUSTOM_EVENT:String = "customEvent";
public function Dispatcher() {
init();
}
public function init():void {
//listen to the event inside this class
addEventListener(Dispatcher.CUSTOM_EVENT, localEventHandler);
// dispatch the event
dispatchEvent(new Event(Dispatcher.CUSTOM_EVENT) );
// using the above dispatchEvent, we can only listen to it in this class...
// if I use a timer to trigger the event, I can also listen for it outside this class
var myTimer:Timer = new Timer(2000, 2);
myTimer.addEventListener("timer", timerHandler);
//myTimer.start();
}
private function timerHandler(e:Event):void {
trace("timerHandler: " + e);
dispatchEvent(new Event(Dispatcher.CUSTOM_EVENT) );
}
private function localEventHandler(e:Event):void {
trace("localEventHandler()");
}
}
}
Example listener class:
ActionScript Code:
package {
import flash.display.*;
import flash.events.*;
public class EventListener extends Sprite {
var myDispatcher:Dispatcher;
public function EventListener() {
init();
}
private function init():void {
myDispatcher = new Dispatcher();
myDispatcher.addEventListener(Dispatcher.CUSTOM_EVENT, myFunction);
}
private function myFunction(e:Event):void {
trace("Event received");
}
}
}
I must be doing something wrong but I can't figure out what..
Any help would be greatly appreciated
Event Listener From Inside A Class AS2
HI all
I want to register a class for an event so all instances of that class
receive the event
conceptually like this:
class cms {
public var editing:Boolean = false;
public function cms() {
this.addEventListener("editMe");
}
public function toggleEdit():Void{
if(this.editing==true){
this.editing = false;
}else{
this.editing = true;
}
trace(this.editing);
}
public function clickHandler(e:Object){
trace('yeah got that')
}
}
am I barking up the wrong tree or perhaps just barking?
Cheers
Catching An Event Fired In Another Class
Hey Everyone,
I have one main class and two subclasses. The main class instantiates the two subclasses. One of the subclasses is a circle class that loads in images and masks them, and the other is a list class that lists out a bunch of buttons. I have over 200+ buttons being generated from an xml file in the list class. What I want to have happen is this:
On rollover of one of the list buttons, load the corresponding image into the circle class.
How do I add an event listener that fires upward into the main class so I can load the image into the circle class?
Attached is my current code.
Thanks, TK
Attach Code
//LIST CLASSSS!!!!!
package src
{
import com.onebyonedesign.utils.ContentScroller;
import flash.display.*;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
public class BLNavStation_List extends Sprite implements BLDisplayObject
{
public var ListContent:Sprite;
public var category:BLNavStation_Item;
private var ListBG:Sprite
private var ListMask:Sprite;
private var ListScroll:Sprite;
private var ListHolder:Sprite;
private var XMLObject:XML;
private var urlLoader:URLLoader;
private var urlRequest:URLRequest;
private var cs:ContentScroller;
private var AssetsLoaded:Boolean = false;
public var LIST_W:uint = 300;
public var LIST_H:uint = 500;
public function BLNavStation_List()
{
CreateList("http://localhost/phpengines/main_list_print.php");
}
public function reposition():void
{
if(AssetsLoaded){
//this.x = (stage.stageWidth)-(ListBG.width);
//this.y = (stage.stageHeight/2)-(this.height/2);
}
}
public function clean():void
{
}
private function CreateList(str:String):void {
//DRAW BACKGROUND
ListBG = new Sprite();
ListBG.graphics.lineStyle();
ListBG.graphics.beginFill(0xFFFFFF,0.2);
ListBG.graphics.drawRoundRect(0,0, LIST_W, LIST_H, 20, 20);
ListBG.graphics.endFill();
//DRAW MASK
ListMask = new Sprite();
ListMask.graphics.lineStyle();
ListMask.graphics.beginFill(0x000000, 0.2);
ListMask.graphics.drawRoundRect(5, 5, LIST_W-10, LIST_H-10, 20, 20);
//SET UP LISTAREA
ListContent = new Sprite();
ListContent.x = 5;
ListContent.y = 5;
ListContent.mask = ListMask;
//SET UP SCROLLBAR
ListScroll = new Sprite();
ListScroll.graphics.lineStyle();
ListScroll.graphics.beginFill(0x555555, 1);
ListScroll.graphics.drawRoundRect(LIST_W-5, 5, 15, 50, 5, 5);
ListScroll.graphics.endFill();
//SET UP XML CONTENT
urlRequest = new URLRequest(str);
urlLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, initListener);
urlLoader.load(urlRequest);
}
private function initListener(e:Event):void {
AssetsLoaded = true;
XMLObject = new XML(urlLoader.data);
var counter:uint = 0;
for each (var SUBJECT:XML in XMLObject.*) {
category = new BLNavStation_Item();
category.y = counter * 30;
category.text = SUBJECT.@NAME;
ListContent.addChild(category);
category.addEventListener(MouseEvent.CLICK, clickListener);
counter++;
}
addChild(ListBG);
addChild(ListMask);
addChild(ListContent);
addChild(ListScroll);
cs = new ContentScroller(ListContent, ListMask, ListScroll, 3, "vertical");
}
private function clickListener(e:MouseEvent):void {
trace(e.target.text);
}
}
}
//CIRCLE CLASSSSS!!!
package src
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.net.URLRequest;
public class BLNavStation_Circle extends MovieClip implements BLDisplayObject
{
private var CircleLoader:Loader;
public function BLNavStation_Circle()
{
}
public function loadImage(str:String):void {
CircleLoader = new Loader();
CircleLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
CircleLoader.load(new URLRequest(str));
}
public function reposition():void
{
this.x = (stage.stageWidth /2)-(this.width /2);
this.y = (stage.stageHeight/2)-(this.height/2);
}
public function clean():void
{
CircleLoader = null;
}
private function loadComplete(e:Event):void {
this.ImageTarget.addChild(e.target.content);
this.ImageTarget.mask = this.ImageMask;
}
}
}
//MAIN CLASSSSS!!
package src
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.*;
import flash.net.*;
import flash.system.*;
import flash.utils.*;
public class BLNavStation extends MovieClip implements BLDisplayObject
{
private var AssetsLoaded:Boolean = false;
private var navList:BLNavStation_List;
private var assetLoader:Loader;
private var assetRequest:URLRequest;
private var assetContext:LoaderContext;
private var assetList:Array;
private var assetHolder:*;
private var NavPortal:Class;
private var NavP:MovieClip;
public function BLNavStation()
{
assetLoader = new Loader();
assetRequest = new URLRequest("bl_navAssets.swf");
assetContext = new LoaderContext(false, ApplicationDomain.currentDomain);
assetLoader.contentLoaderInfo.addEventListener(Event.INIT, initListener);
assetLoader.load(assetRequest, assetContext);
}
public function clean():void {
//
}
public function reposition():void {
if(AssetsLoaded) {
if(stage.stageWidth >= 800){
NavP.reposition();
} else {
///
}
}
}
private function initListener(e:Event):void {
assetLoader.removeEventListener(Event.INIT, initListener);
AssetsLoaded = true;
assetHolder = e.target.content;
assetList = assetHolder.getAssets();
NavPortal = getDefinitionByName(assetList[0]) as Class;
NavP = new NavPortal();
addChild(NavP);
NavP.reposition();
navList = new BLNavStation_List();
addChild(navList);
navList.ListContent.addEventListener(MouseEvent.ROLL_OVER, clickFunction);
}
private function clickFunction(e:MouseEvent):void{
if(e.target == category){
trace("yep");
}
}
}
}
Event Handler In Class - Question
Hi.
I've created the following class that is attached to an Movie Clip object in library, positions that object , and make it moves:
I want to add the property to my class, that when the bullet hits an another object on stage, the event listener is removed and the bullet stops. What I don't know is where t put this piece of code, inside the class, or in the actions panel of the FLA file, and how would that piece of code look like?
Here is the code that I've put in the actions panel:
var newSquare:Square = new Square(300,200);
addChild(newSquare);
var newBullet:Bullet = new Bullet(10,200);
addChild(newBullet);
if (newBullet.hitTestObject(newSquare)) {
trace("HIT");
}
I tried to make the collision test in this last IF statement but TRACE doesn't trigger when the bullet passes over the square.
And here is the code for the square Class:
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Square extends MovieClip {
private var pozX:Number;
private var pozY:Number;
function Square(pozX, pozY):void {
this.x = pozX;
this.y = pozY;
}
}
}
Attach Code
//BULLET CLASS
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Bullet extends MovieClip {
private var speedX:Number=10;
private var pozX:Number;
private var pozY:Number;
public var evtBullet:Event;
function Bullet(pozX, pozY):void {
this.x = pozX;
this.y = pozY;
this.addEventListener(Event.ENTER_FRAME,moveBullet);
}
public function moveBullet(evtBullet:Event):void {
evtBullet.target.x+= speedX;
if (evtBullet.target.x > stage.stageWidth - evtBullet.target.width / 2 || evtBullet.target.x < evtBullet.target.height / 2) {
speedX=- speedX;
}
}
}
}
Edited: 09/29/2008 at 05:44:38 PM by Mixa94
Custom Class Event Prototyping
Ive been having a problem with a MovieClip prototype. The code i used is below - the problem being that the onLoad event never happens. Can anyone see an obvious problem? If i change the onLoad event to apply to the MovieClip class and not the PlaylistItem class then the event fires fine.
//constructor
PlaylistItem = function(){}
//inherit from MovieClip
PlaylistItem.prototype = new MovieClip();
PlayListItem.prototype.init = function(sInitTitle, sInitURL, iInitNum){
this.sTitle = sInitTitle;
this.sURL = sInitURL;
this.iNum = iInitNum;
this.sName = "track"+iInitNum;
}
//onLoad method
PlayListItem.prototype.onLoad = function(){
this._y = 20 * (this.iNum - 1);
}
//register class with library object
Object.registerClass("playlistitem_mc", PlaylistItem);
Thanks for any help with this - im at a brick wall if i cant understand why this doesnt work!
mafro
Event Handlers In A Class Definition
I'm trying to rewrite a procedural ActionScript program as an OOP one: in the procedural version I set up event handlers for movieclips on the stage with a loop and it worked fine. However, when I put these event handlers in a class definition, it's no good. Simplified version below, which is just supposed to make a sound when the user clicks on the box
class definition:
class Event_stuff {
var nLpCntr1:Number = 0;
var nNumberOfChoiceBoxes:Number = 3;
var sInstanceName:String = "";
var bChoiceBoxFocus:Boolean = true;
function setUp_event_handlers () {
//_level0.oSoundForClick.start();
for (nLpCntr1 = 1; nLpCntr1 <=nNumberOfChoiceBoxes; nLpCntr1 ++) {
sInstanceName = "choice_" + nLpCntr1;
_level0 [sInstanceName].onRelease = makeNoise;
}
}
function makeNoise () {
if (bChoiceBoxFocus) {
_level0.oSoundForClick.start();
}
}
}
I use the next bit of code in an FLA file (with three movieclips with names choice_1 to choice_3 on the stage)
var myEvent1:Event_stuff = new Event_stuff ();
sSoundForClick = "twang";
oSoundForClick = new Sound ();
oSoundForClick.attachSound (sSoundForClick);
myEvent1.setUp_event_handlers ();
but when I run it, no sound - the problem is that function makeNoise in the class definition doesn't pick up that bChoiceBoxFocus is true (although if I cut the initialization of bChoiceBoxFocus at the beginning of the class definition it causes an error There is no property with the name 'bChoiceBoxFocus'.
Any help greatly appreciated - I'm new to OOP stuff, so apologies for any wrong use of terminology
AS3: Creating A Custom Event Class
Could anyone tell me how to create custom event from beginning to end in AS3?
I'd like to know how to create a custom event that extends the Event class and then how to dispatch it. Also, I'd like to know how to catch it using the addEventListener() in the format Event.ENTER_FRAME or Event.CHANGE etc...
I'm having some difficulty understanding how events work. I believe "ENTER_FRAME" is a constant holding some value but I don't see how that could dispatch an event. From what I understand; ENTER_FRAME is a static variable of the Event class?
Could someone clarify things plz.
Thanks a bunch.
Dispatch Event From Class To Movieclip
In frame 1 of my AS2 .swf:
Code:
import com.classes.ParseXML;
var xml:ParseXML = new ParseXML("xml/site.xml");
xml.addEventListener("Finished", this.init)
function init(){
// run init
}
After I run through a few functions in that class I would like to dispatch an event to the swf like I did in AS2:
Code:
//ParseXML class
//declaring variables and such
private static var evtDisDependancy = EventDispatcher.initialize(ParseXML.prototype);
//inside some function
this.dispatchEvent({type:"Finished"})
Now, apparently a lot has changed in AS3. Could someone please explain to me how I would dispatch this same type of event in AS3 ... or if there is new logic that I need to learn?
Thank you!
Problem With Custom Event Class
Hi,
I making custom Event class, I did it, it works but have some problems.
I make to show some photos in the swf
I import my class album, and this class, call another class loadImages. loadImages, put photos in Scene, I want to make when an image load, to dispatchEvent, and album class to get the event. I make listeners to get the event, but they didn't.
Here is the all. http://theflashblog-bg.com/resources/Event.zip
here is code in the main timeline
ActionScript Code:
import classes.album;var MyPhotoAlbum:album = new album();MyPhotoAlbum.loadXML("photoflow.xml");MyPhotoAlbum.name ="myALb";addChild(MyPhotoAlbum);
my event class
ActionScript Code:
package classes.events_v3 { import flash.events.*; public class flowEvent extends Event { public static const PLC:String = "photo load complited"; public function flowEvent() { super(type, true); } }}
my album class
ActionScript Code:
package classes{ import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.MovieClip; import flash.display.Loader; import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; import flash.xml.XMLDocument; import classes.loadImages; //import classes.events_v3.flowEventDispatcher; import classes.events_v3.flowEvent; //////// public class album extends MovieClip { //Property; specifies the number ot photos public var allPhotos:uint = 0; //Property; boolean value indicatin whether all of the images have loaded or not public var allLoaded:Boolean = false; //Property; the path to the folder containing external images. public var folderPath:String = "images/"; //Property; the max height of the photos. public var photoHeight:Number = 200; //Property; an array containing each photo's object data. public var photosData:Array = new Array(); //Property; the max width of the photos. public var photoWidth:Number = 200; //The path and name of the XML file to load. The XML file contains the list of images to load. public var xmlPath:String = ""; //Property; the type of scaling used. Options are "showAll", "scaleToFit" and "noScale". public var scaleMode:String = "noScale"; //Property: margin top, right, bottom, left private var margin:Array = new Array(10,10,10,10); public var holderColor:uint = 0xffffff; //The color of the border that appears around each image while it is loading. public var holderBorderColor:uint = 0xe4e4e4; public function album() { } //Method; loads the specified XML file. public function loadXML(XMLurl:String) { xmlPath = XMLurl; var loader:URLLoader = new URLLoader(); loader.addEventListener(Event.COMPLETE, onLoadXML); loader.load(new URLRequest(XMLurl)); } public function showForm():void { var i:uint; for (i=0; i<allPhotos; i++) { var temp:loadImages = new loadImages(photosData[i][".name"],photoWidth ,photoHeight, photosData[i][".url"], scaleMode, holderColor, holderBorderColor,margin); temp.x = i*240; temp.name = "photo"+String(i)+"_mc"; //addEventListener(flowEvent.PLC, photoHaveBeenLoad); addChild(temp); } } public function photoHaveBeenLoad(info:Event) { trace(info.target); } ///from loadXML(), when XMLLoaded; private function onLoadXML(info:Event) { var photoDataXML:XMLDocument = new XMLDocument(); photoDataXML.ignoreWhite = true; photoDataXML.parseXML(info.target.data); //Вземане на allPhotos, folderPath, photosData allPhotos = photoDataXML.firstChild.childNodes.length; folderPath = photoDataXML.firstChild.attributes["path"]; var i:uint; for (i=0; i<allPhotos; i++) { photosData.push({".url":String(folderPath+photoDataXML.firstChild.childNodes[i].attributes["url"]), ".name":String(photoDataXML.firstChild.childNodes[i].attributes["name"]),".desc":String(photoDataXML.firstChild.childNodes[i].firstChild)}); } showForm(); } }}
my loadImageClass
ActionScript Code:
package classes{ import flash.display.Shape; import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Loader; import flash.display.MovieClip; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.ProgressEvent; import flash.net.URLRequest; import flash.text.TextField; import classes.events_v3.flowEvent; import classes.album; public class loadImages extends MovieClip { //prop:Name of the picture private var Pcaption:String = ""; //prop:Photo Width to become private var PW:Number; //prop:Photo Height to become private var PH:Number; //prop:Photo Width private var PWreal:Number; //prop:Photo Height private var PHreal:Number; //prop:url to the photo private var Purl:String = ""; //prop: scaleMod private var PScaleMode:String = ""; //prop: Photo background color private var PBGColor:uint = 0xffffff; //prop: Photo border color private var PBColor:uint = 0xffffff; //prop: margin top, right, bottom, left private var margin:Array = new Array(0,0,0,0); private var _loaderImage:Bitmap = new Bitmap(); public var loader:Loader = new Loader(); public var resizeStatus = true; public var keepRatio = true; //percent from photo loading private var onLoadingPrecent:uint; ///the Ruler public function loadImages(_caption:String, W:uint, H:uint, url:String, scaleMode:String, bgColor:uint, bgBorderColor:uint, photoMargin:Array):void { ///init Vars Pcaption = _caption; PW = W; PH = H; Purl = url; PScaleMode = scaleMode; PBGColor = bgColor; PBColor = bgBorderColor; margin = photoMargin; this.bg_mc.addChild(drowShape(PW, PH, PBGColor, PBColor)); loadImage(Purl); } public function drowShape(W, H, bgColor, borderColor):Shape { var shape:Shape = new Shape(); shape.graphics.beginFill(bgColor); shape.graphics.lineStyle(1, borderColor); shape.graphics.drawRect(0, 0, W, H); shape.graphics.endFill(); return shape; } ///Lets all begin private function loadImage(url:String) { setPreloader(); loader.load(new URLRequest(url)); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete); loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoading); this.photo_mc.addChildAt(loader ,0); } ///Pictures is Loaded private function onLoadComplete(info:Event):void { hidePreloader(); var mm:Loader = Loader(info.target.loader); var image:Bitmap = Bitmap(mm.content); //set postion setPostion(image); //optimizations image = optimiseImage(image); this.photo_mc.addChild(image); ///dispatch var ff:album = new album(); addEventListener(flowEvent.PLC, ff.photoHaveBeenLoad); dispatchEvent(new Event(flowEvent.PLC)); } ///return loading percent in MCs TextField private function onLoading(info:ProgressEvent):void { onLoadingPrecent = int(100*info.bytesLoaded/info.bytesTotal); this.preloader_mc.persent_txt.text = String(onLoadingPrecent)+" %"; } ///hide preloader after image load private function hidePreloader():void { this.preloader_mc.visible = false; } ///set loaded image postions private function setPostion(image:Bitmap) { PWreal = int(image.width); PHreal = int(image.height); switch (PScaleMode) { case "showAll" : var NewW:Number = 0; var NewH:Number = 0; var propToWidth:Number = (PW -margin[1]-margin[3])/PWreal; var propToHeight:Number = (PH -margin[0]-margin[2])/PHreal; if (propToWidth>=propToHeight) { NewW = PWreal*propToHeight; NewH = PHreal*propToHeight; } else { NewW = PWreal*propToWidth; NewH = PHreal*propToWidth; } image.width = NewW; image.height = NewH; image.x = margin[3]; trace(PH+"x"+NewH); image.y = PH - NewH -margin[0]; PWreal = NewW; PHreal = NewH; break; case "scaleToFit" : image.width = PW-margin[1]-margin[3]; image.height = PH-margin[0]-margin[2]; image.x = margin[3]; image.y = margin[0]; break; case "noScale" : image.width = PWreal - margin[1] - margin[3]; image.height = PHreal - margin[0] - margin[2]; image.x = (PW - image.width)/2; image.y = (PH - image.height)/2; break; default : break; } } ///set loaded image optimization private function optimiseImage(image:Bitmap):Bitmap { image.smoothing = true; return image; } ///set preloader private function setPreloader():void { this.preloader_mc.x = (PW-this.preloader_mc.width)/2; this.preloader_mc.y = (PH-this.preloader_mc.height)/2; this.caption_txt.x = 10; this.caption_txt.y = this.preloader_mc.y+this.preloader_mc.height+10; this.caption_txt.width = (PW -20); this.caption_txt.text = Pcaption; } ////////////get and set functions public function get loaderImage():Bitmap { return _loaderImage; } }}
so u can see for now I'm getting the event with this lines in loadImages.as
ActionScript Code:
var ff:album = new album(); addEventListener(flowEvent.PLC, ff.photoHaveBeenLoad); dispatchEvent(new Event(flowEvent.PLC));
but I want to add dispatchEvent in albun like so
ActionScript Code:
temp.name = "photo"+String(i)+"_mc"; //addEventListener(flowEvent.PLC, photoHaveBeenLoad); addChild(temp);
but if I write addEventListener, didn't get the event. What to do?
Custom Event Class Did Not Work :(
ActionScript Code:
package com.blah.dfm{
import flash.events.Event;
import flash.xml.XMLDocument;
public class XMLLoaderEvents extends Event {
public static const LOADED:String = "loaded";
private var _xml:XMLDocument = new XMLDocument();
public function get xml():XMLDocument {
return _xml;
}
public override function clone():Event {
return new XMLLoaderEvents(type, bubbles, cancelable);
}
public function XMLLoaderEvents(type:String, bubbles:Boolean=false, cancelable:Boolean=false):void {
trace("huh?!");
super(type, bubbles, cancelable);
//_xml = xml;
}
}
}
this is custom event class, but when I dispath it gets error:
Quote:
huh?!
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at com.theflashblogbg.dfm::XMLLoader/:mlLoaded()
at flash.events::EventDispatcher/flash.events:EventDispatcher::dispatchEventFunctio n()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/flash.net:URLLoader::onComplete()
there is what I dispatch, this is written in class
ActionScript Code:
var mc:MovieClip = new MovieClip();
mc.stage.dispatchEvent(new XMLLoaderEvents("loaded"));
->>>>>>>>>>>>>>>>>>>>>>>
ops I do it.
|