Reflection callMethod context issue

This is my code:

I am getting null value of a_str ( desired value is “Hello” ) , even when I am providing the context of the instance of Main class, while using Reflect.callMethod.

What context should I provide so that I get the desired value?

Main.hx

class Main extends Sprite 
{
	var a_str = "Hello";
	var mc:MovieClip ; 
	
	public function new() {
		
	super();
	 addEventListener(Event.ADDED_TO_STAGE, addedToStage);
	 
	 mc = new MovieClip();
	 
	 mc.graphics.beginFill();
	 mc.graphics.drawRect(0, 0, 100, 100);
	 mc.graphics.endFill();
	 
	 mc.x = 100; mc.y = 200; 
	 addChild(mc);
	 }
 
 function addedToStage(e:Event):Void 
 {
	 removeEventListener(Event.ADDED_TO_STAGE, addedToStage);
	
	 Misc.testCallMethod(this,mc);// , Reflect.field(this, "f"), []);	 
	 
 }
 
  public function broadcaster(e:Event ):Void  {
	trace( 'Called');
	trace(a_str);  // This is showing null even when the context has been provided
 }	
}

Misc.hx

 class Misc  
{
   

	public function new() {
 	 }
 
public static function testCallMethod(pMain:Main,mc:MovieClip ):Void 
 {
	 var f2:Event->Void =  Reflect.field(mc, "addEventListener");
										
  	var f:Event->Void = Reflect.field(pMain, "broadcaster" ); 
 	 Reflect.callMethod(pMain ,f2, [ "click" , f]); //<<<context right now is pMain 
 }
 }

Have a look at the API docs for callMethod - only a few targets support context switching: https://api.haxe.org/Reflect.html?#callMethod

1 Like

Hmm… I am not able to understand it properly.

The object o is ignored in most cases. It serves as the this -context in the following situations:

  • (neko) Allows switching the context to o in all cases.
  • (macro) Same as neko for Haxe 3. No context switching in Haxe 4.
  • (js, lua) Require the o argument if func does not, but should have a context. This can occur by accessing a function field natively, e.g. through Reflect.field or by using (object : Dynamic).field . However, if func has a context, o is ignored like on other targets.

So this means that for most platforms including JS context switching is not available for haxe4 ? It will be ignored?

Also, is their any solution?

I changed the code like this to make it work. Calling the broadcaster inside the anonymous inline function saves the context .

public static function testCallMethod(pMain:Main,mc:MovieClip ):Void 
 {
	 var f2:Event->Void =  Reflect.field(mc, "addEventListener");
										
  	var f:Event->Dynamic->Void = Reflect.field(pMain, "broadcaster" ); 
  
	 Reflect.callMethod(pMain ,f2, [ "click" , function(e){
		 
		 Reflect.callMethod(pMain , f,[]); 
	 }]);
 }