View Full Version : Why doesnt as3 throw an error with addEventListener(string, function)
furyan.be
January 14th, 2009, 11:07 AM
Hi
the callback function uses a parameter from the Event type, but why doesnt as3 give an error when you type
addEventListener("click", func);
function func(event:Event):void
{
}
func needs an argument from the type Event, but how does as3 ignore this?
irrationalistic
January 14th, 2009, 11:23 AM
This isn't necessarily an error. That first part of the eventListener actually takes in a string anyways. For example, MouseEvent.CLICK is a variable that might look like: public static var CLICK:String = "click";
senocular
January 14th, 2009, 11:50 AM
func needs an argument from the type Event, but how does as3 ignore this?
And isn't that what func has? A parameter of the type Event?
furyan.be
January 14th, 2009, 11:55 AM
I thought it to be expecting a parameter of the type Event
But if you call a function without its parenthesis it makes a new object automaticly?
senocular
January 14th, 2009, 12:17 PM
Ooooh, you mean the use of func in addEventListener. There, you're not calling func, you're just using a reference to the func function. A function isn't called unless you use those parenthesis. For example:
function addOneAndOne():Number {
return 1 + 1;
}
trace(addOneAndOne);
If you ran this code, what would you expect? A trace of 2? In fact, that's not what you would get. Instead, you'd get a trace of "function Function() {}" which is the string Flash gives you when you have a reference to a function. Like other variables, you can pass functions around by value without actually calling them. In fact you can assign functions to other variables and call the function through that variable.
function addOneAndOne():Number {
return 1 + 1;
}
var tempFunction:Function = addOneAndOne;
trace(addOneAndOne()); // 2
trace(tempFunction()); // 2
Notice that no parens were used in the assignment to tempFunction. This means addOneAndOne isn't actually called. Instead you're just obtaining the value of that function. Because tempFunction then gets the value of addOneAndOne, it can be called with parens () and run the same function.
The same concept is being applied to addEventListener. By passing in a reference to func in the call to addEventListener, you're allowing addEventListener to save a temporary reference to that function which it can call whenever a click event occurs.
:)
furyan.be
January 14th, 2009, 12:28 PM
Ahhh that explains alot! tyvm!
Powered by vBulletin® Version 4.1.10 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.