Can a Flex 3 method detect the calling object? - actionscript-3

If I have a method such as:
private function testMethod(param:string):void
{
// Get the object that called this function
}
Inside the testMethod, can I work out what object called us? e.g.
class A
{
doSomething()
{
var b:B = new B();
b.fooBar();
}
}
class B
{
fooBar()
{
// Can I tell that the calling object is type of class A?
}
}

Sorry the answer is no (see edit below). Functions received a special property called arguments and in AS2 it used to have the property caller that would do roughly what you want. Although the arguments object is still available in AS3 the caller property was removed from AS3 (and therefore Flex 3) so there is no direct way you can do what you want. It is also recommeded that you use the [...rest parameter](http://livedocs.adobe.com/flex/3/langref/statements.html#..._(rest)_parameter) language feature instead of arguments.
Here is a reference on the matter (search for callee to find the relevant details).
Edit: Further investigation has shown that it is possible to get a stack trace for the current executing function so if you are lucky you can do something with that. See this blog entry and this forum post for more details.
The basic idea from the blog post is you throw an Error and then catch it immediately and then parse the stack trace. Ugly, but it may work for you.
code from the blog post:
var stackTrace:String;
try { throw new Error(); }
catch (e:Error) { stackTrace = e.getStackTrace(); }
var lines:Array = stackTrace.split("\n");
var isDebug:Boolean = (lines[1] as String).indexOf('[') != -1;
var path:String;
var line:int = -1;
if(isDebug)
{
var regex:RegExp = /at\x20(.+?)\[(.+?)\]/i;
var matches:Array = regex.exec(lines[2]);
path = matches[1];
//file:line = matches[2]
//windows == 2 because of drive:\
line = matches[2].split(':')[2];
}
else
{
path = (lines[2] as String).substring(4);
}
trace(path + (line != -1 ? '[' + line.toString() + ']' : ''));

Is important to know that stackTrace is only available on the debugger version of Flash Player. Sorry! :(

I'd second the idea of explicitly passing a "callingObject" parameter. Unless you're doing really tricky stuff, it should be better for the caller to be able to supply the target object, anyway. (Sorry if this seems obvious, I can't tell what you're trying to accomplish.)

To add to the somewhat ambiguous first paragraph of James: the arguments property is still available inside a Function object, but the caller property has been removed.
Here's a link to the docs: http://livedocs.adobe.com/flex/3/langref/arguments.html

This might help someone, I'm not sure... but if one is using an Event this is possible using the e.currentTarget as follows:
private function button_hover(e:Event):void
{
e.currentTarget.label="Hovering";
}

Related

An attempt at understanding what ECMAScript-6 Function.prototype.bind() actually does

This question is a follow-up to this one. For some reason I'm coming back to JS after 7 years and boy, I can hardly recognize the dear old beast.
Purely for educational purpose, I decided to rewrite naive implementations of the various things Function.prototype.bind() allows to do. It's just an exercise to try to understand what's going on and spark a few questions.
I would be happy to stand corrected for all the mistakes and misunderstandings in my examples and comments.
Also, this code is not mine. I got the idea from a blog and only slightly tweaked it, but unfortunately I lost track of the source. If anyone recognizes the original, I'll be happy to give due credit. Meanwhile, I apologize for the blunder.
Naive binding
The initial idea is simply to do what lambda calculus savvies apparently call a "partial application", i.e. fixing the value of the first parameters of a function, that also accepts an implicit "this" first parameter, like so:
Function.prototype.naive_bind = function (fixed_this, ...fixed_args) {
const fun = this; // close on the fixed args and the bound function
return function(...free_args) { // leave the rest of the parameters free
return fun.call(fixed_this, ...fixed_args, ...free_args);
}
}
Binding constructors (1st round)
class class1 {
constructor (p1, p2) {
this.p1 = p1;
this.p2 = p2;
}
}
var innocent_bystander = { "huh?":"what?" }
var class2 = class1.naive_bind(innocent_bystander);
class2 (1,2) // exception: class constructor must be invoked with new (as expected)
console.log(new class2(1,2)) // exception: class constructor must be invoked with new (Rats!)
function pseudoclass1 (p1, p2) {
this.p1 = p1;
this.p2 = p2;
}
var pseudoclass2 = pseudoclass1.naive_bind(innocent_bystander);
pseudoclass2 (1,2) // same exception (as expected)
console.log(new pseudoclass2(1,2)) // same again (at least it's consistent...)
Tonnerre de Brest ! Apparently the runtime is not happy with a mere wrapper based on Function.prototype.call().
It seems the real bind() is adding the dollop of secret sauce needed to give the generated function the appropriate "constructor" flavour (Apparently by "constructor" the ECMA 262 specification does not mean a class constructor, but any function that can be invoked with "new" and use "this" to populate the properties and methods of a freshly created object)
Binding other functions
var purefunction1 = console.log
var purefunction2 = purefunction1.naive_bind (null, "Sure,", "but")
purefunction2 ("you can still", "bind pure", "functions")
// sure, but you can still bind pure functions
// ...and make animals talk (by binding simple methods)
var cat = { speech: "meow" }
var dog = { speech: "woof" }
var fish= { speech: "-" }
var talk = function(count) { console.log ((this.speech+", ").repeat(count-1) + this.speech + "!") }
talk.naive_bind (cat,1)(); // meow!
talk.naive_bind (dog,1)(); // woof!
talk.naive_bind (cat)(3) // meow, meow, meow!
talk.naive_bind (fish)(10) // -, -, -, -, -, -, -, -, -, -!
// and bind arrow functions
// ("this" is wasted on them, but their parameters can still be bound)
var surprise = (a,b,c) => console.log (this.surprise, a,b,c)
var puzzlement = surprise.naive_bind(innocent_bystander, "don't", "worry");
// "this" refers to window, so we get our own function as first output.
surprise ("where", "am", "I?") // function surprise(a, b, c) where am I?
// the bound value of this is ignored, but the other arguments are working fine
puzzlement("dude") // function surprise(a, b, c) don't worry dude
Apparently, everything works as expected. Or did I miss something?
Binding constructors (2nd round)
We apparently can't get away with passing a wrapper to new, but we can try invoking new directly.
Since the value of this is provided by new, the construction-specialized wrapper has only to worry about real constructor parameters.
Function.prototype.constructor_bind = function (...fixed_args) {
const fun = this;
return function(...free_args) {
return new fun (...fixed_args, ...free_args);
}
}
var class1_ctor = class1.constructor_bind(1);
console.log (class1_ctor(2)) // class1 { p1:1, p2:2 }
var monster = (a,b) => console.log ("boooh", a, b)
var abomination = monster.constructor_bind(1);
console.log (abomination(2)) // exception: fun is not a constructor (as expected)
Well, that seems to cut it. I imagine the real bind() is far safer and faster, but at least we can reproduce the basic functionalities, namely:
providing a fixed value of this to methods
doing partial applications on any legit function, though constructors require a specific variant
edit: questions removed to comply with SO policy.
Replaced by just one, the one that matches the title of this post, and that I tried to explore by providing a naive and possibly erroneous equivalent of what I thought the real function did:
Please help me understand how the native Function.prototype.bind() method works, according to the version 6.0 of the ECMAScript specification.
The only bit you have been missing is the introduction of new.target in ES6, which a) makes it possible to distinguish between [[call]] and [[construct]] in a function and b) needs to be forwarded in the new call.
So a more complete polyfill might look like this:
Function.prototype.bind = function (fixed_this, ...fixed_args) {
const fun = this;
return function(...free_args) {
return new.target != null
? Reflect.construct(fun, [...fixed_args, ...free_args], new.target)
: fun.call(fixed_this, ...fixed_args, ...free_args);
}
}
Some other details would involve that fun is asserted to be a function object, and that the returned bound function has a special .name, an accurate .length, and no .prototype. You can find these things in the spec, which apparently you've been reading already.

closures with popups using flex 4.6

I have this custom event handler that shows a popup and accepts input from the user:
private var mySkinnablePopupContainer:MySkinnablePopupContainer;
private function handleShowGridPopupEvent(event:ShowGridPopupEvent):void {
var mouseDownOutSideHandler:Function = function(mdEvent:FlexMouseEvent):void {
// At this point, event.targetControl contains the wrong object (usually the previous targetControl)
if (mdEvent.relatedObject != event.targetControl) {
mySkinnablePopupContainer.close();
}
}
var gridPopupSelectionHandler:Function = function(popEvent:PopUpEvent):void {
if (!popEvent.commit) return;
// At this point, event.targetData contains the wrong object (usually the previous targetData)
myModel.doSomethingWithData(popEvent.data.selectedItem, event.targetData);
}
if (!mySkinnablePopupContainer) {
mySkinnablePopupContainer = new MySkinnablePopupContainer();
mySkinnablePopupContainer.addEventListener(PopUpEvent.CLOSE, gridPopupSelectionHandler);
mySkinnablePopupContainer.addEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE, mouseDownOutSideHandler);
}
// At this point, event.targetData contains the correct object
mySkinnablePopupContainer.dataProvider = getMyDPArrayCollection(event.targetData);
mySkinnablePopupContainer.open(this);
var point:Point = event.targetControl.localToGlobal(new Point());
mySkinnablePopupContainer.x = point.x + event.targetControl.width - mySkinnablePopupContainer.width;
mySkinnablePopupContainer.y = point.y + event.targetControl.height;
}
Every time the function handler gets called, it will have the correct ShowGridPopupEvent object but by the time it calls the
gridPopupSelectionHandler, it will contain the old object from a previous call. It works the first time, subsequent calls fails.
Somehow the reference to the event object changed somewhere in between before opening the popup and after.
Any idea what am I doing wrong here? Is this a bug with flex?
found the prob. since im attaching listener only once, it will reference the old listener, with the reference to the old data. i guess i was expecting its reference to be updated whenever i create the closure. not in this case. possible fix is to remove the listener and re-add it again but I abandoned the idea of using closures, and aside from what RIAStar mentioned, it is also impractical as it only gives more overhead by creating a new function for every invocation of the handler.

AS3 functions replacing

I used to work on AS2 and make games, and now I wanna learn AS3 and have all its nice features (using Flash CS IDE). Now I m trying to rewrite a function to discard it.
function something():void{
//do something
}
function something():void{}
like this. please help or just give some alternatives, thanks.
What you're trying to do is very illogical - a function should be defined once and exist always. Not only that, but it should definitely always behave the same way, especially considering AS3 does not support overloading.
AS3 introduces the OOP paradigm for you to use - this further emphasises the above - you should create classes which define a fixed collection of properties and methods. This way, the intent of each class in your application is clear, and what you expect something to be able to do won't change.
If you absolutely must be able to delete functions, you can assign them to a dynamic object and remove or redefine them with the delete keyword:
var methods:Object = {
something: function():void
{
trace('Still here.');
}
};
methods.something(); // Still here.
delete methods.something;
methods.something(); // TypeError: something is not a function.
methods.something = function():void
{
// Define new function.
}
Or assign an anonymous function to a variable of type Function, from which point you can set the reference to null:
var something:Function = function():void
{
trace("Still here.");
}
something(); // Still here.
something = null;
something(); // TypeError: value is not a function.
something = function():void
{
// Define new function.
}

Evaluate where a function call originated from

Okay so I have a function called changeHandler - it is called by several eventListeners in other functions. I want to write several if statements that evaluate the source of function call and change the dataProvider of my ComboBox depending on the originating function. Example: one of the many functions is called displayCarbs() and has an eventListener like so:
function displayCarbs(event:MouseEvent):void {
myComboBox.addEventListener(Event.CHANGE, changeHandler);
}
(I've removed all of the unnecessary code from the function above)
The if statement inside the changeHandler will look something like this:
if (****referring function = displayCarbs****) {
myComboBox2.dataProvider = new DataProvider(carbItems);
}
I've searched high and low for something that can achieve this, but I just don't have a good enough grasp of AS3 or vocabulary to describe what describe what I mean to get the answer from Google.
The simplest way I can think of... Couldn't you simply create a text string that updates to the name of function before going to changeHandler then in turn changeHandler can check string content and act accordingly..
public var referring_function:String;
function displayCarbs(event:MouseEvent):void
{
referring_function = "displayCarbs";
myComboBox.addEventListener(Event.CHANGE, changeHandler);
}
function displayCarbs(event:Event):void
{
if (referring_function == "displayCarbs")
{ myComboBox2.dataProvider = new DataProvider(carbItems); }
if (referring_function == "displayOthers")
{ myComboBox2.dataProvider = new DataProvider(otherItems); }
// etc etc
}
I cant remember right now if you need == or just = when checking the If statement against strings.
I know there is an accepted answer already, but based on what I gleaned about the problem, here is a solution that wouldn't require adding another variable to check :
function displayCarbs(event:MouseEvent):void
{
myComboBox.addEventListener(Event.CHANGE, changeHandler);
}
function changeHandler(event:Event):void
{
var comboBox:ComboBox = event.target as ComboBox;
if (comboBox.dataProvider == uniqueProvider)
{
myComboBox2.dataProvider = new DataProvider(appropriateItems);
}
}
This should work if the second dataProvider is determined based on the first dataProvider. This of course requires that your uniqueProvider is a class member variable so it has scope within the handler.

Calling functions in Actionscript: "Term is undefined and has no properties"

I'm writing a genetic fitness program, and I'm currently writing some code that will calculate the 'fitness' value of each organism.
I'm trying to call a function that initializes each genotype;
function random_genotype_initialisation():void
{
//stuff
}
By using the typical method-calling I'm used to in C# and Java;
random_genotyoe_initialisation();
However this returns the error: "TypeError: Error #1010: A term is undefined and has no properties."
I've looked elsewhere for help, and I've found suggestions such as declaring a variable and 'calling' that.
var rep = replicate_new_generation();
rep.call();
Any suggestions?
I assume there's an undefined value inside your random_genotype_initialisation() function. You are correct, you call a function in as3 same as in java/c/c++/c#/js/etc.
The snippet is a bit wrong because you store the result of the replcate_new_generation into rep, but that is a void function, so rep will be void and therefore not have call():
var rep = replicate_new_generation();//rep = void at this point
rep.call();//call does not exist for rep
Do you mean ?
var rep:Function = replicate_new_generation;
rep.call();
Which is same as: replicate_new_generation();
If the error is generating within the function perhaps you should post the body
of the function as well ?
C# is VERY similar to AS3, I have no idea what you are trying to do or why your code did not work since you didn't provide a very good example. But you can call functions directly as long as it is accessible just in any normal way.
say, inside a class you have:
class Boo {
private function foo():void {
trace("bar");
}
public function foobar():void {
foo();
}
}
class FoobarCaller {
public function FoobarCaller (){
var asdf:Boo = new Boo();
asdf.foobar();
}
}
that works, just as it would in C# or any other "standard coding language. However, without a better question it's impossible to say what it is you have done wrong