I have a Red5 service function that receives a single string as a parameter, and another function that takes no parameters, like the code below:
public class AService
{
private String someName;
public void setName(String aName)
{
someName = aName;
}
.
.
public String makeMessage()
{
return("Hello, "+someName);
}
.
.
other functions
}
I also have an ActionScript function that calls the service function, using the dynamic parameter:
public class Connector
{
private var netConn: NetConnection;
public function invokeCall(theFunc:String,...theParams): void
{
var resp:Responder = new Responder(checkResult);
netConn.call(theFunc,resp,theParams);
}
.
.
}
I am aware that the "...theParams" is actually an array of parameter objects. I also know that the NetConnector class' call() method uses that parameter object array. Unfortunately, when I do an invokeCall() on my service's makeMessage() method (without putting in a parameter) like so:
invokeCall("AService.makeMethod");
I get a function nonexistent message from Red5. The only way I can make it work is to create two invoke methods, one with parameters and one without, and call that function without parameters.
Furthermore, calling my setName() function, like so:
invokeCallwithPrams("AService.setName","factor3");
doesn't seem to work unless I change the signature of my service function:
public class AService
{
private String someName;
public void setName(String[] aName)
{
someName = aName[0];
}
.
.
public String makeMessage()
{
return("Hello, "+someName);
}
.
.
other functions
}
which I don't mind (even though the Red5 documentation indicates that I shouldn't have to treat the parameter as an array), except that when I pass the string "factor3" into the NetConnection class' call() method, somehow it becomes "[factor3]" in setName()!
Obviously, something is screwy here, but I haven't been able to figure it out.
I am using Red5 Version 1.0.1 and my Actionscript is Version 3.
Can anyone explain to me what is going on and (more importantly) how to fix this???
If so, please advise...
UPDATE: The weirdness continues
I did a test in which I changed the parameter of the function I used to set up and invoke the NetConnection class' call() method. Instead of passing it a "...theParams", I changed it to theParams:String, like so:
public function invokeCall(theFunc:String,theParams:String): void
{
var resp:Responder = new Responder(checkResult);
netConn.call(theFunc,resp,theParams);
}
Interestingly, the brackets that appear in my service method setName() go away!
Whatever this problem is, it has something to do with the dynamic parameters in Actionscript. I suspect that I have found a bug in Actionscript 3 that does not allow it to properly handle dynamic parameters that are passed to a method from another method.
Has anyone else seen this problem? Is there any solution? The dynamic parameters are supposed to allow anyone to add parameters as necessary and make them any object that is necessary. Unfortunately, it doesn't look like you can use dynamic parameters passed from another method without them being screwed up.
This looks like a serious bug in Actionscript. Am I correct?
Someone please advise...
I found the solution. It is not a bug in Actionscript, it is a bit of strangeness in the language.
The basic information about the solution can be found here:
AS3 variable length argument expand to call another function with var length args
Based on what is there, I needed to do the following in the method I am using for invokeCallwithParams:
.
.
var conn:Connector = new Connector();
private function invokeCaller(fName:String,...cParams)
{
cParams.unshift(fName);
conn.invokeCall.apply(conn,cParams);
}
This eliminates the unnecessary brackets passed into my setName() service function, meaning that I can pass dynamic, variable length parameters from one method to another...
Related
I've got a method that accepts a parameter of type Class, and I want to only accept classes that extend SuperClass. Right now, all I can figure out to do is this, which does a run-time check on an instance:
public function careless(SomeClass:Class):void {
var instance:SomeClass = new SomeClass();
if (instance as SuperClass) {
// great, i guess
} else {
// damn, wish i'd have known this at compile time
}
}
Is there any way to do something like this, so I can be assured that a Class instance extends some super class?
public function careful(SomeClass:[Class extends SuperClass]):void {
var instance:SuperClass = new SomeClass();
// all is good
}
If you are going to instantiate it anyway, why not accept an object instead which allows you to type it to :SuperClass?
careless(SomeClass);
//vs.
careless(new SomeClass);
Not too much of a problem there as far as your code goes.
There are a few differences though:
The object has to be created, because an object is required. If your function does not instantiate the class under some circumstances, this can be a problem. Additional logic to pass either an object or null can bloat the function call.
If you cannot call the constructor outside that function, it won't
work either.
All that is solved by the factory pattern. Pass a factory as the parameter that produces SuperClass objects.
function careful(factory:SuperClassFactory)
Your requirements:
I want to only accept classes that extend SuperClass
and
I need to pass in a Class so that it can be instantiated many times
by other objects later
Can be met by passing in an instance of the class you need, and using the Object.constructor() method.
public function careful(someInstance:SuperClass):void {
//you probably want to store classRef in a member variable
var classRef: Class = someInstance.constructor();
//the following is guaranteed to cast correctly,
//since someInstance will always be a descendant of SuperClass
var myInst:SuperClass = new classRef() as SuperClass;
}
More reading here.
You can't do that in ActionScript 3. In languages like C# you can do something like (forgive me if the syntax is off):
public void Careless<T>() where T : SuperClass
But AS3 does not have 'generics'. Unfortunately the only way I know how to do what you want is the way you have already done.
A pattern that might be more suitable for your use case might be something like:
class SuperClass
{
public static function careless():void
{
var instance:SuperClass = new SuperClass();
// ...
}
}
The only way to have static type checking in ActionScript 3 is to provide an instance of a class.
It is possible but it's expensive. You can use on a Class (not instance) the:
flash.utils.describeType
You then get an XML with a bunch of information including inheritance for that class. Like I said it's an expensive process and probably creating an instance and checking it will be in most cases faster.
I want to implement the ability to step back / forward in the application.
Thought about this: there is some array that references to functions and to step back / forward, you just need to call the last element in the array.
Class Manager:
public class Manager
[...]
private static var _forward:Vector.<Function>;
[...]
public static function set forward(f:Function):void{
_forward.push(f);
}
public static function get forward():Function{
return _forward[_forward.length-1];
}
Use in another class :
[... ]
Manager.forward = _map.moveObject (mo, 0 , 150, -150 );
[... ]
Such use is causing the error .
Is it the correct idea and implementation ? If not, how can I fix this?
Thanks!
It doesn`t work because
_map.moveObject(mo, 0, 150, -150);
returns not function, but the result of the function (in this case, apparently void). To get a reference to a function to do so:
Manager.forward = _map.moveObject;
It is now clear that in addition to the functions and parameters of the need (and their number may vary), and also have to store. Generally this problem is solved with the use of pattern Command. About with this interface:
package
{
public interface ICommand
{
function execute():*;
function undo():void;
function redo();
}
}
I have 2 classes representing 2 objects. From the "whoCalledMe" function, I want to find out what object called the function (without passing that information in as an argument). I've used a make-believe property, "caller", that would give me the reference I'm looking for. Is there a generic way I can get a reference to the caller from there?
package {
public class ObjectCallingTheFunction {
public var IDENTITY:String = "I'm the calling function!";
public function ObjectCallingTheFunction() {
var objectWithFunction:ObjectWithFunction = new ObjectWithFunction();
objectWithFunction.whoCalledMe();
}
}
}
package {
public class ObjectWithFunction {
public function whoCalledMe ():void {
trace(caller.IDENTITY); // Outputs: "I'm the calling function!"
}
}
}
It would help to know why you need this, because I have a feeling that you don't really. If the method is anonymous, you can bind the 'this' keyword by using .apply on the method:
var foo:Function = function(arg:int):void
{
trace(this);
};
var bar:Object = {
toString: function():String { return "bar"; }
};
var baz:Object = {
toString: function():String { return "baz"; }
};
foo.apply(bar); // <-- Prints "bar"
foo.apply(baz); // <-- Prints "baz"
If the method is an instance method method however, it's a bound method and thus "this" will always point to the instance of the class it's declared in, no matter if you redefine it by using the apply method. If it's a static method, "this" doesn't make sense and the compiler will catch it.
Other than that, there's really no way short of declaring it as a parameter. There used to be a caller property on the arguments object, but it was deprecated when AS3 was released. You can get a reference to the function itself through arguments.callee, but that's not really what you asked for.
In AS3 you can throw an error and then parse the Stack Trace to find out detailed informations.
You can check here for an example:
http://www.actionscript-flash-guru.com/blog/18-parse-file-package-function-name-from-stack-trace-in-actionscript-as3
If you want to find the called function's name you can follow this example:
http://www.flashontherocks.com/2010/03/12/getting-function-name-in-actionscript-3/
I guess you want to know the caller in debug purpose. if so I would recommend setting a breakpoint in the method/function instead of tracing. When the code breaks you can backtrace the caller and a lot more. Works in Flash IDE as well as Flashbuilder. Google "as3 breakpoints" if you are new to breakpoints.
Here is the official Adobe article on using arguments.callee
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/arguments.html
It includes sample code.
Hope this helps.
I have a service class which has overloaded constructors. One constructor has 5 parameters and the other has 4.
Before I call,
var service = IoC.Resolve<IService>();
I want to do a test and based on the result of this test, resolve service using a specific constructor. In other words,
bool testPassed = CheckCertainConditions();
if (testPassed)
{
//Resolve service using 5 paramater constructor
}
else
{
//Resolve service using 4 parameter constructor
//If I use 5 parameter constructor under these conditions I will have epic fail.
}
Is there a way I can specify which one I want to use?
In general, you should watch out for ambiguity in constructors when it comes to DI because you are essentially saying to any caller that 'I don't really care if you use one or the other'. This is unlikely to be what you intended.
However, one container-agnostic solution is to wrap the conditional implementation into another class that implements the same interface:
public class ConditionalService : IService
{
private readonly IService service;
public ConditionalService()
{
bool testPassed = CheckCertainConditions();
if (testPassed)
{
// assign this.service using 5 paramater constructor
}
else
{
// assign this.service using 4 parameter constructor
}
}
// assuming that IService has a Foo method:
public IBaz Foo(IBar bar)
{
return this.service.Foo(bar);
}
}
If you can't perform the CheckCertainConditions check in the constructor, you can use lazy evaluation instead.
It would be a good idea to let ConditionalService request all dependencies via Constructor Injection, but I left that out of the example code.
You can register ConditionalService with the DI Container instead of the real implementation.
My underlying problem was that I was trying to resolve my class which had the following signature:
public DatabaseSchemaSynchronisationService(IDatabaseService databaseService, IUserSessionManager userSessionManager)
This was basically useless to me because my usersessionmanager had no active NHibernate.ISession because a connection to my database had not yet been made. What I was trying to do was check if I did have a connection and only then resolve this class which served as a service to run database update scripts.
When changing my whole class to perform the scripts in a different way, all I needed in its constructor's signature was:
public DatabaseSchemaSynchronisationService(ISessionFactory sessionFactory)
This allowed me to open my own session. I did, however have to first check if the connection was ready before attempting to resolve the class, but having IDatabaseSchemaSynchronisationService as a parameter to another class's constructor; this class also gettting resolved somewhere where I could not check the db connection was a bad idea.
Instead in this second class, I took the IDatabaseSchemaSynchronisationService paramater out of the constructor signature and made it a local variable which only gets instantiated (resolved) :
if (connectionIsReady)
Thanks to everyone who answered.
How does one get a reference the the getter and setter functions in actionscript 3?
if a method is defined on the calls, e.g.
public function blah():String { ...}
I can get a reference to it by just saying blah or this.blah
How do get a reference to
public function get blah2():String {}
public function set blah2(b:String):void {}
Thanks!
Original response:
Unfortunately, you will not be able to store references to those as functions. The getter and setter methods are actually built around the idea that you shouldn't be able to and they therefore function as a property.
Is there a reason that you need to reference the functions specifically?
The comment I'm responding to:
I want to dynamically add external interface methods based on custom metadata tags, e.g. [External]. I was able to do this for the regular methods, but I'm trying to extend this to getter/setters as well. To do this, I need to get a reference to the function dynamically, so I can execute it with the right args using the apply function.
I think you're better off using a multi-step approach in that case. Since getters and setters function as a property and not a method, it would make sense to test to see if it is a property and then simply assign it a value directly. Would you be able to use this:
if( foo.blah2 is Function )
{
foo.blah2.apply( foo, arr );
}
else
{
foo.blah2 = arr[ 0 ];
}