Can I safely pass null to Function.apply in place of thisArg argument? - actionscript-3

To make public API of SWF more reliable, I usually wrap callbacks in closure with try/catch block:
private function addCallback(functionName:String, closure:Function):void {
ExternalInterface.addCallback(functionName, wrapEventHandler(closure));
}
private function wrapEventHandler(closure:Function):Function {
var self:Main = this;
return function(...arguments):* {
try {
return closure.apply(self, arguments);
} catch (error:Error) {
// Print error report here
}
}
}
When exception occurs in 'closure', error report will be printed.
I noticed that it works fine even when using 'null' instead of 'self':
closure.apply(null, arguments);
Is it safe to use 'null' in this case?
Callback I register with ExternalInterface aren't static functions; they use Main's class fields.
It works just fine with null, NaN and self. I couldn't find any problems with using NaN/null.

Passing the this argument to apply() is optional, and the parameter default value is NaN.
Parameters
thisArg:* (default = NaN) — The object to which the function is
applied.
Likewise with, call():
You can pass the value null for the thisObject parameter to invoke a
function as a regular function and not as a method of an object.
For example, the following function invocations are equivalent:
Math.sin(Math.PI / 4)
Math.sin.call(null, Math.PI / 4)

Related

Responder callback methods

I need to create a Responder object, the constructor documentation says:
Parameters
result:Function — The function invoked if the call to the
server succeeds and returns a result.
status:Function (default = null) — The function invoked if the server returns an error.
What is the parameter of the status function? it says the signature is function(default = null), but it doesn't actually explain what is default.
What type is default?
What might it contain?
Here function(default = null) means that the default value for the second parameter is null rather than the signature if the status handler.
As for the signature of the status handler it depends on your client<->server protocol. For example look at the MessageResponder class that inherits the Responder that are used in the flex remoting. It has the strongly typing serialization of AMF directly to the IMessage:
public function MessageResponder(agent:MessageAgent, message:IMessage,
channel:Channel = null)
{
super(result, status);
...
}
...
final public function result(message:IMessage):void {...}
final public function status(message:IMessage):void {...}
In general you can pass the functions with the single Object argument:
public function status(message:Object):void {}
public function result(message:Object):void {}

AS3 - Check if a callback function meets certain argument criteria?

If I set up a function that accepts a callback:
function loadSomething(path:String, callback:Function):void;
And that callback should accept a given type, for example a String to represent some loaded information:
function onLoaded(response:String):void;
// Load some data into onLoaded.
loadSomething("test.php", onLoaded);
Is it possible to assess the function that will be used for callback and ensure that it has both a given amount of arguments and that the argument accepts the correct type? e.g.
function broken(arg:Sprite):void;
// This should throw an error.
loadSomething("test.php", broken);
I don't think you should bother doing this kind of check as it would create an uncessary overhead. You can simply throw the exception when you do the callback:
try {
doCallback(response);
} catch(e:*) {
trace('Incompatible callback');
}
If you really want to do the check, you might be able to do it using reflection. Just call describeType(callback) from flash.utils and parse the XML.
One simple thing you can do is to check the number of acceptable arguments by calling length property on method closure like:
function some ( val1 : int, val2 : int ) : void { return; }
trace(some.length); // traces 2
Other much more complex method maybe is to use AS3Commons bytecode library. You can experiment with dynamic proxies.

Question on Javascript Function Parameters

I was trying to write some javascript function and realised that
function testFunction(input_1, input_2, input_3) {
alert("alert");
}
however when i call the function like this:
<input type="button" value="click" onclick="testFunction("1", "2")">
why will it still work even with just two parameters?
You can call a Javascript function with any number of parameters, regardless of the function's definition.
Any named parameters that weren't passed will be undefined.
Extra parameters can be accessed through the arguments array-like object.
It doesn't actually matter how many parameters you are providing. the function interprets them and creates the arguments object (which acts as an array of parameters).
Here's an example:
function sum(){
if(arguments.length === 0)
return 0;
if(arguments.length === 1)
return arguments[0];
return arguments[0] + sum.apply(this, [].slice.call(arguments, 1));
}
It's not the most efficient solution, but it provides a short peak at how functions can handle arguments.
Because javascript treats your parameters as an array; if you never go beyond the second item, it never notices an argument is missing.
Javascript does not support Method overloading hence method will be execute in order of their occurence irrelevant of arguments passed Because javascript has no type checking on arguments or required qty of arguments, you can just have one implementation of testFunction() that can adapt to what arguments were passed to it by checking the type, presence or quantity of arguments..
Because Parameters are optional
Some Reading:
http://www.tipstrs.com/tip/354/Using-optional-parameters-in-Javascript-functions
Javascript is a very dynamic language and will assume a value of "undefined" for any parameters not passed a value.
Try using the below code
var CVH = {
createFunction: function (validationFunction, extParamData, extParamData1) {
var originalFunction = validationFunction;
var extParam = extParamData;
var extParam1 = extParamData1;
return function (src, args) {
// Proxy the call...
return originalFunction(src, args, extParam, extParam1);
}
}
}
function testFunction(input_1, input_2, input_3) {
alert("alert");
}
and you can call this function as below
<input type="button" value="click" onclick="CVH.createFunction(testFunction('1', '2'),'3','4')">
The third parameter can be optional and will have a null undefined default value.
If you explicitly want to have a required parameter, you need to require it via code inside the function.

ActionScript - Receiving Name of Calling Function or Constructor?

long shot: is it possible to get the name of a calling function or the constructor from the called function? is it possible to determine the previous function of the thread?
i would like to call some setter functions from my constructor and have my setter functions determine if it was the constructor that called them.
currently, i'm setting a boolean for this functionality, but perhaps there is another way?
public function Constructor(myNumber:Number)
{
this.myNumber = myNumber;
}
public function set myNumber(value:Number):void
{
myNumberProperty = value;
//if constructor called this, return;
//else do some other stuff;
}
Quote from liveDocs:
Unlike previous versions of ActionScript, ActionScript 3.0 has no arguments.caller property. To get a reference to the function that called the current function, you must pass a reference to that function as an argument. An example of this technique can be found in the example for arguments.callee.
It was in AS2.0... It unfortunately throws an error if done in AS3.0.
Technically, you should be able to do this by generating an error and getting its stack trace. The constructor will have to be on that stack trace.
try
{
throw new Error();
}
catch (e:Error)
{
// parse this for the constructor name
trace(e.getStackTrace());
}
That would be for detecting where a function call came from...
I would still go for your solution (setting the flag), as it's more oop and probably far faster in terms of performance.

calling super() from an actionscript constructor with varargs

If a constructor takes its parameters as a vararg (...) it seems to be impossible to create a subclass that will just pass on that vararg to the superclass.
There is a related question with fix for this same situation for normal functions: Wrapping a Vararg Method in ActionScipt but I cannot get that to work with a super call.
base class:
public class Bla
{
public function Bla(...rest)
{
trace(rest[0]); // trace the first parameter
}
}
subclass:
public class Blie extends Bla
{
public function Blie(...rest)
{
// this is not working, it will
// pass an array containing all
// parameters as the first parameters
super(rest);
}
}
if I now call
var b1 = new Bla('d', 'e');
var b2 = new Blie('a', 'b', 'c');
I get the output
d
a,b,c
And I want it to print out:
d
a
Aside from actually moving the handling of the parameters to the subclass or shifting it off to a separate initializer method, does anyone know how to get the super call right?
There's unfortunately no way to call the super constructor with ... args. If you remove the super() call, it will be called by the compiler (with no arguments). arguments is also not accessible from constructors.
If you can change the method signatures, you modify the arguments to accept an Array rather than ... args. Otherwise, as you mentioned, you could move it into an initializer method.
You may use a statement like this:
override public function doSomething(arg1:Object, ...args):void {
switch(args.length) {
case 0: super.doSomething(arg1); return;
case 1: super.doSomething(arg1, args[0]); return;
case 2: super.doSomething(arg1, args[0], args[1]); return;
}
}