Throughout my views I have something similar (overly simplified here for discussion):
// header.php
<script>
<?= UIAdvert::$header; /* should echo onetwothree */ ?>
</script>
UIAdvert::$code .= 'one';
// sidebar.php
UIAdvert::$code .= 'two';
// footer.php
UIAdvert::$code .= 'three';
Using the view::BeforeRender I set UIAdvert::$header = UIAdvert::$code so that when the output buffer is flushed, I would be able to echo "onetwothree" in the header script.
This wasn't working as intended. So I changed the event from BeforeRender to BeforeRenderView. However that resulted in 'twothree' but not 'onetwothree' and the event gets called thrice (once for each view, though I can live with that for now).
What is a good way to achieve this?