- <cfscript>
- // I return a new object with only the given method names expsed
- // as behaviors on the resultant object.
- function exposeMethods( target, methods ){
- // Define the behavior that will be exposed. This method will
- // act as a proxy to the underlying behavior which will pass
- // the message onto the target component and return the value
- // returned from the target component.
- var behavior = function(){
- // Get the name of the function being invoked.
- var methodName = getFunctionCalledName();
- // Invoke the method on the taret object and return the
- // result to the calling context.
- return(
- invoke( target, methodName, arguments )
- );
- };
- // Create the object we are going to return.
- var proxy = {};
- // For each method name, expose the behavior through the
- // proxy object.
- arrayEach(
- methods,
- function( methodName ){
- // Expose the behavior.
- proxy[ methodName ] = behavior;
- }
- );
- // Return the new proxy object with exposed behaviors.
- return( proxy );
- }
- // ------------------------------------------------------ //
- // ------------------------------------------------------ //
- // ------------------------------------------------------ //
- // ------------------------------------------------------ //
- // Create a new account component instance.
- account = new Account( 100 );
- // Now, let's create a proxy to the given account component that
- // only exposes the credit and the balance methods but not the
- // debit method.
- goodAccount = exposeMethods(
- account,
- [ "credit", "getBalance" ]
- );
- writeOutput( "Account credited [50]. <br />" );
- // Credit the account.
- goodAccount.credit( 50 );
- // Now, I know this is going to fail, but for funzies, let's try
- // to call the non-exposed behavior - debit() - on the proxy.
- try {
- writeOutput( "Trying to debit()." );
- // Try to invoke the debit() method - a non-exposed behavior.
- goodAccount.debit( 25 );
- } catch( Any cfcatch ){
- writeOutput( " [ FAILED ] <br />" );
- }
- // Now, let's call the exposed behavior to get the balanace.
- writeOutput( "Balanace: " & goodAccount.getBalance() );
- </cfscript>