Using An Event Listeners Function At Will - Event Dispatching?
Hi,
I have a event listener that turns a camera on and off according to how much motion there is:
ActionScript Code:
camera1 = Camera.getCamera(""+Number(aCameraComboBoxes[selComboBoxNum].selectedIndex-1));
aCameras[selComboBoxNum].addEventListener(ActivityEvent.ACTIVITY, activityHandler, false, 0, true);
private function activityHandler(event:ActivityEvent):void {
if(event.activating){
//camera is turning on
}else if (!event.activating){
//camera is turning off
}
}
All of this works but I need a way to rerun the addlistener's function without the camera actual turning on or off. Is there a way for me to use this function, and send it the variable it is looking for?
Thanks
ActionScript.org Forums > ActionScript Forums Group > ActionScript 3.0
Posted on: 10-20-2007, 04:44 AM
View Complete Forum Thread with Replies
Sponsored Links:
Using An Event Listeners Function At Will - Event Dispatching?
Hi,
I have a event listener that turns a camera on and off according to how much motion there is:
camera1 = Camera.getCamera(""+Number(aCameraComboBoxes[selComboBoxNum].selectedIndex-1));
aCameras[selComboBoxNum].addEventListener(ActivityEvent.ACTIVITY, activityHandler, false, 0, true);
private function activityHandler(event:ActivityEvent):void {
if(event.activating){
//camera is turning on
}else if (!event.activating){
//camera is turning off
}
}
All of this works but I need a way to rerun the addlistener's function without the camera actual turning on or off. Is there a way for me to use this function, and send it the variable it is looking for?
Thanks
View Replies !
View Related
Using An Event Listeners Function At Will - Event Dispatching?
Hi,
I have a event listener that turns a camera on and off according to how much motion there is:
camera1 = Camera.getCamera(""+Number(aCameraComboBoxes[selComboBoxNum].selectedIndex-1));
aCameras[selComboBoxNum].addEventListener(ActivityEvent.ACTIVITY, activityHandler, false, 0, true);
private function activityHandler(event:ActivityEvent):void {
if(event.activating){
//camera is turning on
}else if (!event.activating){
//camera is turning off
}
}
All of this works but I need a way to rerun the addlistener's function without the camera actual turning on or off. Is there a way for me to use this function, and send it the variable it is looking for?
Thanks
View Replies !
View Related
Dispatching 1 Event To Multiple Listeners
Hi,
Currently when I want to dispatch an event to multiple instances of the same class I set up a listener for that event on the stage in my classes constructor, so that it is an umbrella type listener. Then dispatch an event targeted at that class (from outside the class) like so, myClassInstance.dispatchEvent(new Event(myClass.MY_EVENT,true)); which then is received and acted on by all instances of that class. This works fine.
However, it I am wondering if there is a better method for dispatching an event to all instances of a class? It seems, that the various approaches I try fail due to scope issues with the event only being broadcast to one instance of the class, not all.
Ie, something like this;
ActionScript Code:
package { import flash.events.*; import flash.display.Sprite; import flash.display.Stage; public class testEvent extends Sprite { public var counter:int=0; public static const TEST_EVENT:String="testevent"; //constructor public function testEvent(image:int) { this.counter=image; var testContent = new Sprite() testContent.buttonMode=true; testContent.useHandCursor=true; testContent.graphics.beginFill(0x0000FF,100); testContent.graphics.drawRect(10,10,10,10); addChild(testContent) addEventListener(Event.ADDED_TO_STAGE,addedToStageHandler); addEventListener(MouseEvent.CLICK,handleClick);//slide images } //added to stage event listener private function addedToStageHandler(event:Event):void { stage.addEventListener(testEvent.TEST_EVENT,indicate); } //handle a click private function handleClick(e:MouseEvent):void { dispatchEvent(new Event(testEvent.TEST_EVENT,true)); } //custom event handler private function indicate(e:Event):void { if (this !== e.target) { this.y = 20 } else{ trace(e.target.counter) e.target.y = 10 } } }}
View Replies !
View Related
Dispatching An Event From Inside Another Events Listener Function
Hello,
Is it possible to dispatch an event from inside another events listener function and have it bubble up to the correct location or even bubble at all?
I have a feeling that since the dispatch is occuring from within another events listener function that it is locked somehow and cannot communicate outside of itself unless I create a custom event.
I ask because I am trying to do something like this:
ActionScript Code:
// test the HourGlassDial
oHourGlassDial = new HourGlassDial();
oHourGlassDial.addEventListener(HourGlass.HOUR_GLASS_ROTATED, onHourGlassRotated);
////////////////
public function onHourGlassRotated(e:Event):void
{
trace("onHourGlassRotated");
// Increment the oHourGlass by 1 frame
if (oHourGlass.currentFrame < oHourGlass.totalFrames) {oHourGlass.gotoAndStop(oHourGlass.currentFrame+1);}
}
ActionScript Code:
////////////////
public function onTimeIntervalComplete(e:HourGlassRotationIntervalEvent):void
{
trace("onTimeIntervalComplete: dispatching HOUR_GLASS_ROTATED event");
trace ("currentCount =" + e._timerEvent.target.currentCount);
trace ("repeatCount =" + e._timerEvent.target.repeatCount);
// dispatch the TIME_EXPIRED event to all subscribers
dispatchEvent(new Event(HourGlass.HOUR_GLASS_ROTATED));
}
////////////////
But when the onTimeIntervalComplete listener function runs I can see the traces for it, but when its suppose to dispatch the HOUR_GLASS_ROTATED event I never see the traces from the onHourGlassRotated listener function.
Any suggestions?
many thanks in advance,
frank grimes
View Replies !
View Related
Event Listeners And Function Args
Can arguments be passed to functions called from event listeners? For example something like:
Code:
button1.addEventListener(MouseEvent.CLICK, changeText(e, field1, "myText"));
button2.addEventListener(MouseEvent.CLICK, changeText(e, field2, "myText2"));
function changeText(e:MouseEvent, field, txt):void {
field.text = txt;
}
What I want to do is similar to the above, but of course a lot more complicated. Just wondering if the concept works or if I need to have a separate function for each button. I've never seen an example where args are passed to EventListener functions. Any other ideas?
View Replies !
View Related
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?
View Replies !
View Related
[CS3] Dispatching An Event From Inside An Event
Does anyone know how to dispatch an event from inside another event?
I get crazy! I have tried a hundred ways to dispatch an event from inside a onLoad event when loading a XML-file. It just doesn't work!!
Here is a simple example:
Code:
class myClass {
public var xmlData;
public var addEventListener:Function;
public var removeEventListener:Function;
public var dispatchEvent:Function;
function myClass() {
xmlData = new XML();
EventDispatcher.initialize(this);
}
function loadXML() {
xmlData.onLoad = function(success) {
if(success){
trace("success");
sendEventLoaded();
}
else trace("Error: Xml not loaded");
}
xmlData.load("filename.xml");
xmlData.ignoreWhite = true;
}
public function sendEventLoaded() { // send the Event
trace("sendEventLoaded()");
dispatchEvent({target:this, type:"isLoaded"});
}
}
The first issue is not dispatching the event itself, but calling the function sendEventLoaded(). It's like it can't be found from within the onLoad event. When the onLoad event occurs, the text "success" is traced, and but the text "sendEventLoaded()" is never executed!!
Does anyone know how to call the sendEventLoaded() from within the onLoad event? Or is there any other way to do this?
I'm thankful for any help I can get!!
View Replies !
View Related
Help With Adding Event Listeners Class Function
Alright so I am back with more things to learn. I have a class that I wrote in an actionscript file in which I need to have access the stage so that I can add an event listener.
Basically, what I have is something like this:
Code:
Package{
public class Example{
private var mainTimeline:MovieClip = new MovieClip();
public function example(){
mainTimeline.addEventListener(MouseEvent.CLICK, mouseEventHandler);
}
}
}
unfortunately when I run the application, the event listener is not picked up because the created movieclip is instantiated on the 0 Frame, whereas the current playhead is located on frame 2. Any help towards this would be of great assistance, thanks!
View Replies !
View Related
How Do I Create A Modular Function For Use With Event Listeners
OK I'm very new to AS3 and I'm curious as to how to get modular functions to work in AS3.
for instance if I have this code:
function snowfall(snowflake:MovieClip, movement:Number):void
{
snowflake.y = movement;
}
snowfall(snowflake1_mc, 10);
snowfall(snowflake2_mc, 20);
snowfall(snowflake3_mc, 30);
Now on the stage I place 3 instances of a snowflake movie clip. Each time I call the "snowfall" function I refer to a new instance of the snowflake movie clip and a different amount of movement along the y axis.
This is great but what if I want to use a button to control these snowflake movie clips and I want to maintain that modular nature? I don't really get how to do this. I created a button with an instance name of "myButton" and I've tried this code but it is throwing an error I don't really understand:
myButton.addEventListener(MouseEvent.CLICK, snowfall(snowflake3_mc, 30));
Can I not pass information to a function using an EventListener?
View Replies !
View Related
Making Multiple Event Listeners Run The Same Function
I have a block of code. I attached two different event listeners, one to the stage and one to a button. I want it so when the event is triggers, the event handler should run. Look at the code. Thanks.
Attach Code
package
{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
public class bobAI extends MovieClip
{
public function bobAI()
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, bob_respond);
enter_btn.addEventListener(MouseEvent.CLICK, bob_respond);
}
private function bob_respond(event:*):void
{
//I want this function to run regardless of the event type
trace("working...");
}
}
}
View Replies !
View Related
Calling Same Function From 2 Event Listeners, One Works, The Other Does Not
The function that is called is this:
ActionScript Code:
function newsTabSlideBack(evt:Event):void {
//trace("CLICKED4!!!");
trace(">>>>>>>>>>>>>>>>>>>>>>>>>>eventClick");
trace("evt = " + evt);
trace("evt.target = " + evt.target);
trace("evt.target.id = " + evt.target.id);// Get Item ID - need children
trace("evt.target.parent = " + evt.target.parent);
trace("evt.target.parent.parent = " + evt.target.parent.parent.parent);
trace("evt.target.parent.parent.parent.article = " + evt.target.parent.parent.parent.article);
trace("evt.target.parent.parent.parent.newsHolder = " + evt.target.parent.parent.parent.newsHolder);
trace("evt.target.parent.parent.parent.tabHolder.getChil dByName(newsTab1) = " + evt.target.parent.parent.parent.tabHolder.getChildByName("newsTab1"));// News ID
var newsHolderpos = evt.target.parent.parent.parent;
scrollTabs = new Tween(newsHolderpos.newsHolder, "x", Strong.easeInOut ,newsHolderpos.newsHolder.x ,-newsHolderpos.newsHolder.width/2,1,true);
trace("newsHolderpos.newsHolder.x" + newsHolderpos.newsHolder.x);
trace("newsHolderpos.newsHolder.width/2" + newsHolderpos.newsHolder.width/2);
}
Back Button 1 (located @ Movie Clip: Frame=1 Target="_level0.worldmap.backBtn"):
ActionScript Code:
function buildBackBtn():void {
//builds the back button that appears on the right hand side.
//check to see if the button is already present
var myPrevClip = getChildByName("backBtn");
if (myPrevClip!=null) {
removeChild(myPrevClip);
myPrevClip = null;
}
var backBtn:BackBtn = new BackBtn();
backBtn.name = "backBtn";
backBtn.buttonMode = true;
backBtn.x = outsideBorder.x + outsideBorder.width - backBtn.width - 20;
backBtn.y = outsideBorder.y + outsideBorder.height - backBtn.height - 20;
backBtn.addEventListener(MouseEvent.CLICK, newsTabSlideBack);
backBtn.addEventListener(MouseEvent.CLICK, backClick);
addChild(backBtn);
}
Back Button 2 (located @ Movie Clip: Frame=1 Target="_level0.worldmap.detailsPanel.detailsPanel _close"")::
ActionScript Code:
function buildTabs():void {
//builds the tabs in the details panel. These are BUTTONS.
var totalTabWidth:Number = 0;
var myContainer = getChildByName("detailsPanel");
var numTabs = myData[current_i_index].events[current_j_index].tabs.length;
for (var i=0; i<numTabs; i++) {
var myTab:Tab = new Tab();
myTab.name= "myTab"+i;
myTab.id = i;
myTab.x = myContainer.tabMenuBar_mc.x + (i*DISTANCE_BETWEEN_TABS) + (totalTabWidth);
myTab.y = myContainer.tabMenuBar_mc.y - myTab.height;
//Build a textfield in each TAB CONTAINER
var tabText:TextField = new TextField();
tabText.selectable = false;
tabText.autoSize = TextFieldAutoSize.LEFT;
tabText.mouseEnabled = false;
tabText.embedFonts = true;
tabText.antiAliasType = AntiAliasType.ADVANCED;
var myText:String = myData[current_i_index].events[current_j_index].tabs[i];
tabText.defaultTextFormat = tfTabs;
tabText.htmlText = myText;
myTab.width = tabText.width + 10;
tabText.x = myTab.x + (myTab.width - tabText.width)*0.5;
tabText.y = myTab.y + (myTab.height - tabText.height)*0.5;
totalTabWidth += myTab.width;
myContainer.addChild(myTab);
myContainer.addChild(tabText);
//add the events - but not for the first tab as its initially selected
if (i!=0) {
myTab.addEventListener(MouseEvent.CLICK, tabClick);
myTab.addEventListener(MouseEvent.MOUSE_OVER, tabMouseOver);
myTab.addEventListener(MouseEvent.MOUSE_OUT, tabMouseOut);
myTab.buttonMode = true;
} else {
myTab.gotoAndStop(2);
}
}
var origWidth:Number = myContainer.detailsPanel_bkgrnd.width;
var newWidth:Number = totalTabWidth +((numTabs-1) * DISTANCE_BETWEEN_TABS);//+ (2* myContainer.tabMenuBar_mc.x);
if (newWidth>=origWidth) {
//resize the width of the details panel because the tabs are low larger than the initial width of the details panel
myContainer.detailsPanel_bkgrnd.width = newWidth + BORDER_WIDTH;
myContainer.tabMenuBar_mc.width = newWidth;
var myTxtMc = myContainer.getChildByName("txtMc");
var myTF = myTxtMc.getChildByName("tf");
myTF.width = myContainer.tabMenuBar_mc.width;
}
//place the close button in the details panel in the correct position
myContainer.detailsPanel_close.x = myContainer.detailsPanel_bkgrnd.x + myContainer.detailsPanel_bkgrnd.width - myContainer.detailsPanel_close.width - BORDER_WIDTH;
myContainer.detailsPanel_close.y = myContainer.detailsPanel_bkgrnd.y +BORDER_WIDTH;
myContainer.detailsPanel_close.buttonMode = true;
myContainer.detailsPanel_close.addEventListener(MouseEvent.CLICK, backClickSmallButton);
myContainer.detailsPanel_close.addEventListener(MouseEvent.CLICK, newsTabSlideBack);
}
The Results for the traces in newsTabSlideBack are:
Back Button 1 results (does not work - can not reach main timeline) :
ActionScript Code:
evt = [MouseEvent type="click" bubbles=true cancelable=false eventPhase=2 localX=46 localY=8 stageX=673.9000000000001 stageY=342.45000000000005 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0]
evt.target = [object BackBtn]
evt.target.id = undefined
evt.target.parent = [object COMPONENTMAP_1]
evt.target.parent.parent = [object Stage]
ReferenceError: Error #1069: Property article not found on flash.display.Stage and there is no default value.
at xmlMap_cs3_3_fla::COMPONENTMAP_1/newsTabSlideBack()
Back Button 2 results (works):
ActionScript Code:
evt = [MouseEvent type="click" bubbles=true cancelable=false eventPhase=2 localX=8 localY=5 stageX=248.9 stageY=53.300000000000004 relatedObject=null ctrlKey=false altKey=false shiftKey=false delta=0]
evt.target = [object MovieClip]
evt.target.id = undefined
evt.target.parent = [object DetailsPanel]
evt.target.parent.parent = [object MainTimeline]
evt.target.parent.parent.parent.article = [object Article]
evt.target.parent.parent.parent.newsHolder = [object Sprite]
evt.target.parent.parent.parent.tabHolder.getChildByName(newsTab1) = [object NewsTab]
The error given is this :
ActionScript Code:
ReferenceError: Error #1069: Property article not found on flash.display.Stage and there is no default value.
at xmlMap_cs3_3_fla::COMPONENTMAP_1/newsTabSlideBack()
so, Why Does one work and the other does not?
Thanks,
Ian
View Replies !
View Related
Ease Animation Function - Evil Event Listeners
Last question before i turn in for the night
I've been working on a node class, which places a circle on the stage and holds information about it, such as ID and coordinates etc.
I've been working on an ease animation function for the class, so i can animate each node to a certain y location on the stage with a nice slow down as it reaches its target destination (sadly, i'm not sure how to apply this for BOTH x and y).
I have no idea how the ENTER_FRAME event listeners work, so this was my longshot attempt:
ActionScript Code:
public function easeNode($destination:Point) { var previousPosition:Point = new Point(node.x,node.y); var speed:int = randRange(4,12); node.addEventListener(Event.ENTER_FRAME, animation); function animation (e:Event):void { node.y += ($destination.y - node.y)/speed; if( node.y == previousPosition.y) { node.y = $destination.y; animation.removeEventListener(Event.ENTER_FRAME, animation); } previousPosition.y = node.y; } }
Useage:
ActionScript Code:
nodes[2].easeNode(new Point(43,34));
I'm getting this error at compile:
Quote:
Description:
1046: Type was not found or was not a compile-time constant: Event.
Source:
function animation (e:Event):void {
Can one of you AS3 gurus out there set me straight and point out my errors?
Thanks again guys, you're the best!
View Replies !
View Related
Event Listeners VS Event Functions
I'm working on a new project at work where there's lots of custom objects with lots and lots of event listeners. I keep finding myself saying, "why didn't they just use the built in objects with built in event handling?". However, from what I can see it seems like AS3 leans heavily towards using Event Listeners as opposed to putting event responsibility on the object itself (E.G. XML.onload). Is there an advantage to this (other than making it more Java like?) I've always favoured keeping the responsibility on the object itself because it seems like one less object to keep track of and also makes things feel more self contained. If I have 10 objects that fire 10 different events, I have to create 10 different event handlers (or 10 different case statements within the same event handler), whereas with self event handling, I just code in the event function.
Anyways, I wanted to open discussion to which method of event handling you prefer and why, and also what you believe the advantages to this. I was searching google for previous discussions on this but I couldn't seem to find anything, so I thought I'd get the ball rolling! Looking forward to reading these, try not to be too elitist in your posts!!
View Replies !
View Related
Dispatching An Event...
hey,
is it possible to dispatch an Event without doing it from within a class.. Sounds weird eh? I just want at a certain frame of a certain animation to add something like
this.dispatchEvent({type:"customEvent"});
and then catch somewhere else..
Is this doable or is it totally absurd?
View Replies !
View Related
Event Dispatching
Hi All...
Im having trouble dispatching a custom event called TransitionEvent into 2 different classes : Images and Captions.
The class below creates the two classes (Images and Captions). What i need to do is when an image finishes a transition, i need an event to be dispatched into the Caption class to display the text. Any Help would be appreciated.
ActionScript Code:
public class Banner extends Sprite {
private var xmlLoader:URLLoader;
private var images:Images;
private var captions:Captions;
private var bannersXml:XML;
function Banner() {
stage.stageWidth = 720;
stage.stageHeight = 200;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
this.addEventListener(TransitionEvent.TRANSITION, transition);
init();
}
private function init():void {
xmlLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
xmlLoader.load( new URLRequest('Banner.xml'));
}
private function xmlLoaded(e:Event):void {
bannersXml = XML(xmlLoader.data);
setupCaptions();
setupImages();
}
private function setupCaptions():void {
captions = new Captions(bannersXml);
}
private function setupImages():void {
images = new Images(bannersXml);
addChild(images);
addChild(captions);
}
private function transition(e:TransitionEvent):void {
trace(e);
}
}
Thanks
View Replies !
View Related
Event Dispatching Help
I'm trying to write a bare-bones event dispatcher, and would like to stick to procedural code if possible. My attempt is below, but why doesn't this work?
Basic Need: I want to have an Object (not a movieclip) that dispatches certain events, and have other objects react when the event fires. This is pretty straightforward to do normally, but I figured I'd harness the EventDispatcher class since it seems robust and would save me writing my own class (I'm trying to avoid custom classes for this project).
ActionScript Code:
import flash.events.EventDispatcher;
import flash.events.Event;
var foo = new MovieClip();
function myFunc(e) {
trace("worked");
}
foo.addEventListener("foobar", myFunc);
function dispatch() {
var d = new EventDispatcher();
var e = new Event("foobar");
d.dispatchEvent(e);
}
setInterval(dispatch, 500);
I would think that myFunc would be called, but it's not... help?
View Replies !
View Related
Event Dispatching
Hey Guys,
I'm having some trouble with my custom event dispatching. I set up a file in which I have created some custom events:
ActionScript Code:
package gallery{
import flash.events.Event;
public class GalleryEventManager extends Event {
public static const CONTENT_DISPLAYED:String = "CONTENT_DISPLAYED";
public static const CONTENT_REMOVED:String = "CONTENT_REMOVED";
public static const INITIAL_CONFIG_COMPLETE:String = "INITIAL_CONFIG_COMPLETE";
public static const NAV_BUTTON_INITIALISED:String = "NAV_BUTTON_INITIALISED";
public static const THUMB_BUTTON_SET_INITIALISED:String = "THUMB_BUTTON_SET_INITIALISED";
public static const THUMB_BUTTON_INITIALISED:String = "THUMB_BUTTON_INITIALISED";
public static const SUB_GALLERY_INITIALISED:String = "SUB_GALLERY_INITIALISED";
public function GalleryEventManager(type:String, bubbles:Boolean=false,cancelable:Boolean=false) {
super(type,bubbles,cancelable);
}
public override function clone():Event {
return new GalleryEventManager(type,bubbles,cancelable);
}
}
}
i'm gonna summarise a little here because i'm dealing with 4 different class files and dont think its appropriate to paste code for all of them but here is my best shot. Basically what this is an image gallery. The way i've set it up is that i preload in my xml file containing all my data and then attempt to "initialise" my objects - basically just call their constructor functions and assign vars but dont do any image loading or anything like that until everything is "initialised". After that, I wanna call a function which sets off my image loading code. The problem i'm having is that the code i'm using to dispatch my event is not working.
On the main timline(of the fla file) I have the following called after its successfully loaded in the xml file:
ActionScript Code:
var galleryXML:XML;//create a new xml object
var galleryXMLList:XMLList;//create an xml list to hold all the data
var galleryType:String;
var galleryNavButtonEmptyMC:GalleryNavButtonEmptyMC = new GalleryNavButtonEmptyMC();
galleryXML = XML(event.target.data);
galleryXMLList = galleryXML.children();
//figure out what type of gallery you are so can name the set
galleryType = galleryXMLList[0].attribute("type");
//create a nav button set
var galleryNavButtonSet:GalleryNavButtonSet = new GalleryNavButtonSet(this,galleryType, galleryXMLList, galleryNavButtonEmptyMC);
current_galleryNavButtonSet = galleryNavButtonSet; //update timeline reference to this gallery
galleryNavButtonSet.name = galleryType;
//set the stage position
galleryNavButtonSet.x = 36.4;//set the x value on stage
galleryNavButtonSet.y = 677;//set the y value on stage
addChild(galleryNavButtonSet);
galleryNavButtonSet.addEventListener(GalleryEventManager.INITIAL_CONFIG_COMPLETE, showGalleryContentPreloader);
and in the constructor function of my galleryNavButtonSet class i have the following line to trigger the event:
ActionScript Code:
this.dispatchEvent(new GalleryEventManager(GalleryEventManager.INITIAL_CONFIG_COMPLETE));
The problem is that it never actually fires and I don't know why. I'm guessing my lack of understanding of the event system is here. I'm confused as to whether perhaps my event being fired is getting lost at some point?
cheers for any help!!! and if anyone needs more code please let me know.
stacey
View Replies !
View Related
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?
View Replies !
View Related
Question On Event Dispatching.
Say you have a function below that disables the button the listener is registered to.
Quote:
button.addEventListener(MouseEvent.CLICK, runFunction);
public function runFunction(evt:MouseEvent) {
evt.target.enabled = false;
}
Now, what is the simplest means of simulating an event dispatch for the above function without actually clicking the button? Assume there are numerous buttons you would like to simulate for.
If it's addressed in another topic, could you provide a link?
View Replies !
View Related
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
View Replies !
View Related
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));
}
}
}
View Replies !
View Related
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.
View Replies !
View Related
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?
View Replies !
View Related
Dispatching One Event For Two Buttons
Hi
I have two buttons each in its own sprite now I want to listen for mouse overmout and click event on both. In a way that if you roll over button1 its color changes but at the same time button2 color changes as well.
To be more specific lets suppose I have a graphic button like map picutre for a country like UK and then I have text button for UK as well. What I want now is that when user either scrolls over UK map the map button color changes but at the same time the color for UL text button changes as well. same goes for click and out events for the two.
I hope this is maknig sense.
Thanks
View Replies !
View Related
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);
}
}
}
View Replies !
View Related
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');
}
}
}
View Replies !
View Related
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?
View Replies !
View Related
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
View Replies !
View Related
Event.COMPLETE Not Dispatching In Browsers
Im loading a jpg using a Loader object. when the Event.COMPLETE is dispatched, i resize the image. If i run the swf in the Flash player, it runs fine.. BUT when i run it in a browser from a HTTP server the Event.COMPLETE is NOT dispatching!!! (any browser)
heres the script:
ActionScript Code:
var ldr:Loader = new Loader();
var urlReq:URLRequest = new URLRequest("http://www.modernlifeisrubbish.co.uk/images/illustrations/google-as-a-giant-robot.jpg");
ldr.load(urlReq);
addChild(ldr);
ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
function loaded(event:Event):void
{
var contt:Bitmap = event.target.content;
contt.scaleY = .5;
contt.scaleX = .5;
}
any ideas how to resize the image when the file is loaded? (I also want to addChild after its loaded)
View Replies !
View Related
Dispatching Event From Movieclip Timeline
Hi all,
I have a movieclip linked to a class file that contains other movieclips inside it (unlinked to anything). These sub movieclips act as pages dropping down. There is about 4 of them, and I have been having a tough time getting the behavior I want to happen. Basically, I'm trying to dispatch an event to the parent class at a specific time when the page is done dropping/animating.
When I tell one of these 'page' movieclips to "play()" from the main movieclip's class file, is there any way to have it dispatch an event when it gets done that i can listen for in my main movieclips' class file?
Hope that make sense. I'd really appreciate any help.
View Replies !
View Related
Dispatching Event From Inside A MovieClip
Hello
I am making a project in which I am loading an swf file inside a movie clip now I want to know that when the loaded swf file has finished playing it dispatches an event or something that tells either the movie clip in which its loaded or the main swf that the loaded swf has finised playing.
Thanks in advance
View Replies !
View Related
Event Dispatching In Hierarchical AS3 Menus
Hi All,
I've written lots of hierarchical menus in AS2, am happy with XML, recursion and the Compound design pattern.
However, I'm about to built my first AS3 menu system, and what I want to know is where do people usually add their event listeners? Should I be adding them on each menu item, or just one on the whole menu system, and use event bubbling to capture and respond to clicks, rollouts, etc.
Any advice would be appreciated!
Thanks,
Dave
View Replies !
View Related
Very Simple Dispatching Event Not Working
Hi,
I am trying to dispatch events for the first time. I read Essential AS3 and it all seems clear, but I can't make it work.
Here is the code dispatching the event
Code:
public class SimpleApp2 extends Sprite{
var spb:SimplePuzzleBoard = new SimplePuzzleBoard();
public function SimpleApp2() {
trace("dispatching new event soon");
var ev:Event = new Event("myEvent", true, false);
trace(ev);
dispatchEvent(ev);
trace("event has been dispatched");
}
}
and here is where I attempt to handle the event:
Code:
class SimplePuzzleBoard2 extends Sprite {
public function SimplePuzzleBoard2() {
this.addEventListener("myEvent", handleAddPiece);
}
private function handleAddPiece(ev:Event) {
trace("event received, piece will be added");
}
}//class
And here's the output:
Code:
dispatching new event soon
[Event type="myEvent" bubbles=true cancelable=false eventPhase=2]
event has been dispatched
So the event is being created but either not dispatched or not received. I have been staring at this all day and I can't see what's wrong.
Thank you in advance!!!!
View Replies !
View Related
Dispatching Event From Inside A MovieClip
Hello
I am making a project in which I am loading an swf file inside a movie clip now I want to know that when the loaded swf file has finished playing it dispatches an event or something that tells either the movie clip in which its loaded or the main swf that the loaded swf has finised playing.
Thanks in advance
View Replies !
View Related
Dispatching Custom Event From A Class
Hi everyone,
I am writing a class that pulls all the files out of a directory, then filters for the specified file type. The class functions very well, but it can take a while if there are a lot of files. So, I thought it would be best to make the class dispatch events when progress is made, and when the process is complete. I made a custom event called DirectoryEvent, and tried to dispatch an event from the class. Unfortunately, when I test this in an FLA the event never occurs. The sources for all the files are below.
DirectoryFlattener.as
Code:
package com.seannichols.utils
{
import flash.filesystem.File;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import com.seannichols.events.DirectoryEvent;
public class DirectoryFlattener extends EventDispatcher
{
private var _dispatcher:EventDispatcher;
private var _onFilter:Boolean;
private var _currFile:Number;
private var _totalFiles:Number;
private var _decimal:Number;
protected function initDispatcher():void
{
_dispatcher = new EventDispatcher();
}
String.prototype.replace = function(pattern, replacement)
{
return this.split(pattern).join(replacement);
}
public function DirectoryFlattener():void
{
init();
}
private function init():void
{
}
private function filterFiles(cleanedFiles:Array, typeFilter:String):Array
{
var justSpecifiedType:Array = new Array();
for (var i:uint = 0; i < cleanedFiles.length; i++)
{
_onFilter = true;
_currFile = i + 1;
_totalFiles = cleanedFiles.length + 1;
_decimal = _currFile / _totalFiles;
this.dispatchEvent(new DirectoryEvent(DirectoryEvent.PROGRESS, {onFilter:_onFilter, currFile:_currFile, totalFiles:_totalFiles, decimal:_decimal}));
var fullPath:String = cleanedFiles[i].nativePath.replace("\","/");
var extensionStart:int = fullPath.lastIndexOf(".",fullPath.length);
var extension:String = fullPath.substring(extensionStart,fullPath.length);
if (extension == typeFilter)
{
justSpecifiedType.push(fullPath);
}
else
{
}
}
return justSpecifiedType;
}
private function cleanFileArray( files : Array ):Array
{
var arrayToReturn : Array = new Array();
for each (var fileOrDir:File in files)
{
if (fileOrDir.isDirectory)
{
var subArray:Array = this.cleanFileArray(fileOrDir.getDirectoryListing());
arrayToReturn = arrayToReturn.concat(subArray);
}
else if ( fileOrDir.isHidden )
{
}
else
{
arrayToReturn.push( fileOrDir );
}
}
return arrayToReturn;
}
public function flatDir(file:File, typeFilter:String):Array
{
var filesInDir:Array = file.getDirectoryListing();
var cleanedFiles:Array = cleanFileArray(filesInDir);
if (typeFilter == null)
{
return cleanedFiles;
}
else
{
var filesToReturn:Array = filterFiles(cleanedFiles,typeFilter);
return filesToReturn;
}
}
}
}
DirectoryEvent.as
Code:
package com.seannichols.events
{
import flash.events.Event;
public class DirectoryEvent extends Event {
public static const START:String = "start";
public static const PROGRESS:String = "progress";
private var _info:Object = null;
public function get info():Object {
return _info;
}
public function DirectoryEvent(type:String, info:Object){
super(type, true);
_info = info;
}
public override function clone():Event {
return new DirectoryEvent(type, _info);
}
}
}
Directory Flatten Test.fla (Layer: actions, frame:1)
Code:
import flash.filesystem.File;
import flash.events.Event;
import com.seannichols.utils.DirectoryFlattener;
import com.seannichols.events.DirectoryEvent;
var directory:File = File.documentsDirectory;
var dirFlattener:DirectoryFlattener = new DirectoryFlattener();
addEventListener(DirectoryEvent.PROGRESS, prog);
function prog(e:DirectoryEvent):void
{
trace("Progress:");
trace(" onFilter: " + e.target.info.onFilter.toString());
trace(" currFile: " + e.target.info.currFile);
trace(" totalFiles: " + e.target.info.totalFiles);
trace(" decimal: " + e.target.info.decimal);
}
try
{
directory.browseForDirectory("Select Directory");
directory.addEventListener(Event.SELECT, directorySelected);
}
catch (error:Error)
{
trace("<Error>" + error.message);
}
function directorySelected(event:Event):void
{
directory = event.target as File;
var flattened:Array = dirFlattener.flatDir(directory, ".mp3");
for(var i:uint = 0; i<flattened.length; i++)
{
var path:String = flattened[i];
var fileNameStart:int = path.lastIndexOf("\",path.length);
var fileName:String = path.substring(fileNameStart+1,path.length);
trace(fileName);
}
trace(" " + flattened.length + " MP3s found.");
}
I have tried adding the event listener to the DirectoryFlattener instance, but I get this error:
Description: 1061: Call to a possibly undefined method addEventListener through a reference with static type com.seannichols.utils:DirectoryFlattener.
Source: dirFlattener.addEventListener(DirectoryEvent.PROGRESS, prog);
View Replies !
View Related
Dispatching Custom Event To Multiple Objects.
Hello to everyone on this my first post to this list.
I have been reading through many posts in here related to the EventDispatcher class and I have to admit that I am more confused now, may be for the different ways of using this class.
Let me explain what I am trying to achieve.
The idea is simple, maybe the solution as well, I would like to broadcast a custom event and having a few objects to catch that event and response in different ways.
I have been following Patrick Mineault tutorial on Using EventDispatcher, on it an instance of a class is able to fire an event that the same instance will catch an deal with it.
But what I want to achieve is a bit different, I want that instance of the class to fire an event and having instances of different classes responding to that event.
So this is my question, how can I make different objects to register for the same custom event.
So far, if I implement Patrick's solution, I cannot have a second instance of the Timer class listening to the 'timeout' event dispatched for the first instance.
My idea was that a broadcasted event will be listened for everyone and only those registered to deal with it will catch it and deal with it.
Thank you for any help you can give.
View Replies !
View Related
Dispatching A Custom Event Just Received By A Dispatcher
Hello there.
I would like to know why this piece of code doesn't work.
When I try to dispatch a custom event "MyEvent" after receiving it from another dispatcher I get this error (at run-time):
TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::Event@a5c2101 in MyEvent.
at flash.events::EventDispatcher/flash.events:EventDispatcher::dispatchEventFunctio n()
at flash.events::EventDispatcher/dispatchEvent()
at MyListener/::handleMyEvent()
at flash.events::EventDispatcher/flash.events:EventDispatcher::dispatchEventFunctio n()
at flash.events::EventDispatcher/dispatchEvent()
at MyDispatcher/fire()
at MyListener/fire()
at testEvents$iinit()
I found a workaround as you can see below.
However I still do not understand why Flash cannot convert the event just received in MyEvent seen that the event just received is MyEvent!
Here it is the code.
// file: testEvents.as (the document class)
ActionScript Code:
package{ import flash.display.MovieClip; public class testEvents extends MovieClip{ public function testEvents():void{ // Creates MyListener that creates MyDispatcher var mylistener:MyListener = new MyListener(); // Sets a listener for MyEvent mylistener.addEventListener(MyEvent.MY_EVENT_1,handleMyEvent); // Starts MyListener that starts MyDispatcher that sends MyEvent mylistener.fire(); } private function handleMyEvent(event:MyEvent):void{ trace(event); } }}
// file: MyEvent.as
ActionScript Code:
package{ import flash.events.Event; public class MyEvent extends Event{ public static const MY_EVENT_1:String = "event1"; public function MyEvent(type):void{ super(type); } }}
// file: MyListener.as
ActionScript Code:
package{ import flash.display.Sprite; public class MyListener extends Sprite{ var mydispatcher:MyDispatcher = null; public function MyListener():void{ // Creates MyDispatcher mydispatcher = new MyDispatcher(); // Sets a listener for MyEvent mydispatcher.addEventListener(MyEvent.MY_EVENT_1,handleMyEvent) } public function fire():void{ // Starts MyDuspatcher that sends MyEvent mydispatcher.fire(); } private function handleMyEvent(event:MyEvent):void{ trace(event is MyEvent); // sure it is, in fact it returns true // ERROR at Run-time: TypeError: Error #1034: Type Coercion failed: cannot convert flash.events::Event@a5c2101 in MyEvent dispatchEvent(event); // To fix the Error I need to create another istance of MyEvent and dispatch it // dispatchEvent(new MyEvent(MyEvent.MY_EVENT_1)); } }}
// file: MyDispatcher.as
ActionScript Code:
package{ import flash.display.Sprite; public class MyDispatcher extends Sprite{ public function MyDispatcher():void{ // Does nothing } public function fire():void{ // Dispatch MyEvent dispatchEvent(new MyEvent(MyEvent.MY_EVENT_1)); } }}
In attach you can find a zip that contains the files, just dezip it in a dir and open the FLA and launch it.
What am I missing?
Sorry is this is a lame question but although I think I'm quite skilled in AS1-prototype, I'm learning AS3 in these days so I feel like a newbie again
View Replies !
View Related
Dispatching And Receiving Event Within Document Class
Hi all,
I am wonder how one would go about dispatching and receiving an event within a document class.
Currently I have the following code:
ActionScript Code:
public static var TEST_EVENT:String = "TEST_EVENT";public function MyDocClass(){ addEventListener(TEST_EVENT, testOK);}public function testDispatch():void{ dispatchEvent(new Event(TEST_EVENT));}public function testOK():void{ trace("test is ok");}
The problem with this is that i get an ArgumentError: Error #1063.
Any ideas?
Cheers
View Replies !
View Related
Dispatching Event From A Static Class (Singleton Desing Pattren)
Hello
I have a class name ImageLoader that is used to load image and the dispatch a complete event when the image is loaded. This class is implementing singleton design pattern which means that only one instance is created always for this class.
Everything is working fine it is loading the image but in the initListener function i am dispacthing a complete event to let the other class Content (which passes the image name to this class ) that the image is loaded and you can access it now.
BUt the problem is the event is never dispatched or may be it is but I am not catching it properly here is code for my ImageLoader class.
Code:
package
{
import flash.display.*;
import flash.net.*;
import flash.events.*;
public class ImageLoader extends Sprite
{
private static var _instance:ImageLoader;
private static var loadedImage:DisplayObject;
private static var loader:Loader;
private static var urlRequest:URLRequest;
public function ImageLoader(ImageLoaderEnforcer:ImageLoaderEnforcer)
{
}
public static function getInstance():ImageLoader
{
if (ImageLoader._instance == null)
{
ImageLoader._instance=new ImageLoader(new ImageLoaderEnforcer );
loader = new Loader();
loadedImage = new Sprite();
}
return ImageLoader._instance;
}
public function loadImage(image:String):void
{
urlRequest = new URLRequest(image);
loader.contentLoaderInfo.addEventListener(Event.INIT, initListener);
trace(image);
loader.load(urlRequest);
}
public function initListener(e:Event):void
{
loadedImage = DisplayObject(loader.content);
dispatchEvent(new Event(Event.COMPLETE));
}
public static function getImage():DisplayObject
{
return loadedImage;
}
}
}
class ImageLoaderEnforcer
{
}
in the other class content I am using the following code to register for complete event.
Code:
// Content class
ImageLoader.getInstance().loadImage("image1.jpg");
ImageLoader.getInstance().addEventListener(Event.COMPLETE, onComplete);
public function onComplete(e:Event):void
{
trace("Complete");
}
Any help will be aprreciated
View Replies !
View Related
Can You Initialize A Function With A Event Also Without Event?
For example i have this function:
function doSomething(event:MouseEvent):void {
trace("do a lot of coding...");
}
Now if i want to run the same function as above without the 'click event' on your mouse that does
not seem to be possible.
Is there a work around? Or is the best way to make a in between function like this:
function doManyThings() {
trace("a lot of code here..");
}
function doSomething(event:MouseEvent):void {
doManyThings();
}
View Replies !
View Related
[F8] Help Regarding Event Listeners
Hello All,
I would like some help with an effect I am trying achieve.
I am controlling the text displayed in a dynamic text field with the position of the mouse.
For Example:
[code]if(_root._ymouse <100) {
_root.variable=TextOne;
} else if (_root._ymouse >100) {
_root.variable=TextTwo;
}
I would like, every time the text changes a sound to be played. I know about Sound Objects and etc, I am just wondering the best way to call a function when the text in the text field changes. Would it be with an EventListener or something completely different?
If so, can yu give me an idea how I would code it, I dont have much experience with Event Listeners.
Thankyou v.much in advance.
View Replies !
View Related
Help With Event Listeners
Hello World!
This is my first post. I'm a professional junior programmer in C++ and Jscript, but I'm under something of a time crunch to figure out if Flash is the rapid-prototyping tool I should be using, so I appeal to your understanding if I haven't researched the problem thoroughly enough.
I've come across a problem with event handlers, which aren't behaving the way that I would expect them to. Consider this code:
Code:
package
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.MovieClip;
public class MapTile extends MovieClip
{
var bmp: Bitmap;
var scale:Number;
public function MapTile(canvas)
{
var temp:whiteBloodCell = new whiteBloodCell(0, 0);
bmp= new Bitmap(temp);
scale= canvas.SCREEN_WIDTH / canvas.TILE_SIZE / canvas.MAP_TILES;
bmp.scaleX = scale;
bmp.scaleY = scale;
bmp.x = 100;
bmp.y = 100;
bmp.alpha = 0.34;
canvas.addChild(bmp);
addEventListener(MouseEvent.CLICK, onMouseOver);
addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
trace("Excuse Me");
}
public function onMouseOver(e:MouseEvent)
{
trace("you are excused");
bmp.alpha = 1.0;
bmp.scaleX = 1;
bmp.x += 100;
}
}
}
What I want is this bitmap/movieclip to have rollover effects. This object is instantiated by my Main object, which properly handles other events. So, I'm a little confused. I have an object which handles events, but the objects in that object don't. Extending the Main class seems like bad design. What I really want to do is extend the Bitmap class so that I can do some particle effects on it, without having to bother Main.
Is the Main object acting like an observer, so it must pass a message to it's children?
View Replies !
View Related
Event Listeners
Do eventlistener only work while you're at the frame that you have established them on? It seems like...
I'm establishing a button and an event listener on mouse up in frame 2, but even though empty frame up to frame 50 for that layer, the event listener seems gone when I'm on frame 7 where I'm using that same button. It works when I'm on frame 2 and the function still exists on frame 7, but does not fire when I click the button. Why?
Allan
View Replies !
View Related
Event Listeners
Maybe I am missing something here. But what I am trying to do is cause a swf to advance one frame after an FLVPlayback component is finished playing the movie. What is happening is, well, nothing. The movie plays just fine. I have added some test code:
import mx.video.FLVPlayback;
var clip:FLVPlayback;
function finishedClip()
{
trace('finished');
}
clip.addEventListener("complete", finishedClip());
the FLVPlayer is labled clip. As soon as I publish the swf, it will trace 'finished'. I have tried other events such as stop, playing, ready.... they all trace at the load of the swf and not when the event is happening. It looks as though nothing knows what the FLVPlayer is doing. If anyone has any clue as to what is going on here, Please let me know. Thnx!!
AC
View Replies !
View Related
Event Listeners
I know other people are having the same trouble with this and I've found a few threads that seem to solve the problem, but I'm not having any luck with it. I would like to detect the end of an .flv so I can add actions afterwards. Maybe someone here can help me out?
Code:
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
ns.setBufferTime(5);
myVideo.attachVideo(ns);
path = "videos/";
ns.play(path+"test.flv");
var listenerObject:Object = new Object();
// listen for complete event
listenerObject.complete = function(eventObject:Object):Void {
trace("flv complete....");
};
myVideo.addEventListener("complete", listenerObject);
View Replies !
View Related
Help With Event Listeners
Flash CS3, actionscript 2.0
I have a timeline animation that I am trying to convert to actionscript. Basically there are 8 movie clips that I have added to the timeline that fade in at different times. I have the code for each of the tweens figured out (var laugh:Tween = new Tween(laugh_mc, "_alpha", Strong.easeIn, 0, 100, 17, false) but I need one to start one, then when its finished, go to the next one without using go to and play. I'm a bit of a newbie to actionscript so if someone could provide an example, it would be much appreciated.
Thanks!
View Replies !
View Related
Event Listeners?
Is it possible to remove an event listener on a class, from outside of that class?
Let's say I have a class and do this.
thisClass.addEventListener(Event.ENTER_FRAME, eFrameRight)
could I remove it from outside of "thisClass"
Because I wanna remove the child that is "thisClass" and it's event listeners, but it isn't working.
View Replies !
View Related
Event Listeners And Components In V.2
I am having trouble trying to figure out the correct coding format for calling a function after a selection on a Combo Box is made in V.2 Actionscript.
For example, if I wanted to change the rotation of a MC by what option a user selected in a COmbo Box. I know that in V.1 the code would be something like this on frame 1 of the movie:
function generalHandler(currentComponent){
if (currentComponent._name == "rotationValue" ) {
mySquare._rotation = currentComponent.getValue();
}
}
FYI -
rotationValue = Instance Name of the COmbo Box
mySquare = Instance name of the Square MC
generalHandler = Name of Function which is linked in the Change HAndler Parameter in FLash MX, but the change handler is not there in MX 2004 which I am working with.
What I am aware of is that in MX2004 you need to add a component listener event to this, instead of using the Change Handler option. The problem is, I am completely confused on the code needed to do this.
I came up w/ something like this for the V.2 Actionscript code:
rotation = new Object();
rotation.change = function (evt){
mySquare._rotation = evt.target;
}
rotationValue.addEventListener ("change", rotation);
I am not even sure how close this is, but it doesn't work I know that much.
Can anyone get me starightened out on this new method? I think it is the theory of what is going on that eludes me. I have looked on the boards as well as in Macromedia Flash MX2004 help. I found a few things, but haven't been able to smooth out the confusion.
Any help would be appreciated
Thanks
dutchoh1
View Replies !
View Related
|