[Coldbox 6.5.2] When calling RunEvent(), Can You Manually Populate a Fresh RC Scope?

Here’s a scenario I’ve run into: I’ve got a Galleries handler that processes an array of uploaded media files and adds them to a Gallery. I also have a Media handler that already has actions in place for handling media files (creating thumbnails, etc). I’d like to have the Gallery handler loop through the array of media files and call the Media handler for processing. Here’s a rough example:

// Galleries Handler
function handleForm( event, rc, prc ) {
  
  // loop through all of the uploaded media
  rc.mediaList.each( function( item ) {
    
    // we already have a handler action that can process media
    // run the event just as if we uploaded a single media file
    runEvent( 'Media.handleForm' );

  } );

}

The problem is, the Galleries rc scope will be polluted with data that the Media handler does not need. I’d like to start fresh so that the Media handler’s rc scope only contains the data I want to feed it during each loop.

I know that runEvent() has the eventArguments property which gets added as arguments to the method in the target handler like this:

function handleForm( event, rc, prc, [eventArguments...] ) { ... }

If possible, I don’t want Media.handleForm() to care whether it’s being called from runEvent(). Is there another way to accomplish what I’m trying to do here? There must be a way to either run an event completely encapsulated with it’s own rc scope that I can manually feed it (similar to Testbox’s execute() method).

Thanks for your suggestions and guidance. :slight_smile:

The short answer is no. The request collection (rc) is, by nature, global to the entire HTTP request. eventArguments is what I would have suggested, but really it sounds like you should move the logic to a service to further encapsulate it from a re usability standpoint. Which is really more/less the same as using eventArguments. But really that’s the way you’d get a fresh invocation of the method where you can 100% control the inputs and outputs and keep them separate from the rest of the thread.

The other option is simply to ignore extra rc values in your Media.handleForm action if they’re not hurting anything. Since you’re running each runEvent() synchronously, you can even modify the rc “scope” manually between loops if you need to stage it correctly for each media call.

  // loop through all of the uploaded media
  rc.mediaList.each( function( item ) {
    rc.mediaID = item;
    runEvent( 'Media.handleForm' );
  } );
1 Like

Thanks Brad. You’re probably right that leveraging a service to do the dirty work is the right approach. The downside is that I tend to put my validation logic in handlers, so I’ll need to do a little code duplication. Thanks for the insight! :slight_smile:

1 Like

There’s nothing wrong with calling the event. You just have to stage the rc for each iteration to have what it expects.