How to share info between collections.save.before and collections.save.after?

Is there a best practice for sharing information between collections.save.before and collections.save.after so that I can compare the updated data?

Example: If a Collection called Users has a field called username and I want to execute something if the value is updated. Like an email indicating their username changed.

You can nest these events. I wrote a quick example (not tested):

$app->on('collections.save.before', function($name, &$entry, $isUpdate) {

    // new entries don't need comparison
    if (!$isUpdate) return;

    // fetch current entry
    $origEntry = $this->module('collections')->findOne($name, ['_id' => $entry['_id']);

    // add event to '...after' queue, that is aware of $origEntry
    $this->on('collections.save.after', function($name, &$entry, $isUpdate) use($origEntry) {

        // compare original entry with current entry and do great things

    }, -9999); // low priority to fire after all other 'collections.save.after' events

}, 9999); // high priority to fire before all other 'collections.save.before' events
1 Like