5

In CF10, I want to access a variable Test object using onMissingMethod function in TestHelper object, but I am getting an error.

Test.cfc

component  {

public Any function init(){
    instance = { x = 1 };
    return this;
}

public numeric function getX(){

    return instance.x;

}

}

TestHelper.cfc

component  {

public Any function init( ){
    variables.testObj = new Test();
    return this;
}

public any function onMissingMethod( required string missingMethodName, required struct missingMethodArguments ){

    var func = variables.testObj[ arguments.missingMethodName ];
    return func( argumentCollection = arguments.missingMethodArguments );

}

}

Calling the object

obj = new TestHelper();
writeOutput( obj.getX() );  //Element INSTANCE.X is undefined in VARIABLES

In CF10, this gives me an error that element X is undefined in instance. It doesn't seem to recognize the variable instance. I could explicitly define getX function in TestHelper, but I was hoping I could use the onMissingMethod function.

Am I misunderstanding how onMissingMethod supposed to work here? FWIW, the code works in Railo.

user2943775
  • 263
  • 3
  • 8

1 Answers1

2

If I understand your issue, I'm surprised this code runs on Railo. I don't think it should.

The issue is with this code:

var func = variables.testObj[ arguments.missingMethodName ];
return func( argumentCollection = arguments.missingMethodArguments );

Here you are pulling the function getX() out of variables.testObj, and running it in the context of your TestHelper instance. And that object doesn't have a `variables.x. Hence the error.

You need to put your func reference into variables.testObj, not pull getX out of it. So like this:

var variables.testObj.func = variables.testObj[ arguments.missingMethodName ];
return variables.testObj.func( argumentCollection = arguments.missingMethodArguments );

That way you're running func() (your proxy to getX()) in the correct context, so it will see variabales.x.

Given this situation, there's no way this code should work on Railo (based on the info you've given us being all the relevant info, anyhow).

Adam Cameron
  • 29,677
  • 4
  • 37
  • 78
  • Adam, you are right (as usual). When I tested it in Railo, I was actually doing `return variables.testObj[ arguments.missingMethodName ] ( argumentCollection = arguments.missingMethodArguments );`. But CF10 does not like this code, so I thought I could just assign the method to a variable func and then call it on the next line. I didn't realize that doing so takes the method out of its context. Thanks for the clarification. Much appreciated. – user2943775 Apr 30 '15 at 11:01
  • No probs. Yeah, we tried to get Adobe to add that syntax, but they wouldn't. There is `invoke()` though, which might help? https://wikidocs.adobe.com/wiki/display/coldfusionen/Invoke – Adam Cameron Apr 30 '15 at 11:31