Generate JSON collection of subpages with a route?

So I’ve been able to convert the json method from using a template + a folder and empty text file, to the one shown here, below (it’s divided in three files):

// plugins/api.php
<?php

$prefix = "api/v1";

kirby()->routes([
  [
    'method' => 'GET',
    'pattern' => "{$prefix}/events",
    'action' => function() {

      // Get the events pages
      $events = page('events')->children()->visible();
      $data = [];

      // Transform for API delivery
      foreach ($events as $event) {
        $data[] = $event->serialize();
      }

      return response::json($data);
    }
  ]

]);

?>

// controllers/events.php
<?php

return function ($site, $pages, $page) {
  if (get('format') == 'json') {
    $data = [
      'uid'   => $page->uid(),
      'title' => $page->title()->toString(),
      'text'  => (string) $page->kirbytext(),
    ];

    die(response::json($data, 200));
  }
}

?>

// models/event.php
<?php

class EventPage extends Page {
  public function serialize() {
    return [
      'uid'     => $this->uid(),
      'url'     => $this->url(),
      'title'   => $this->title()->html()->toString(),
      'text'    => $this->text()->kirbytext()->toString()
    ];
  }
}

?>

Everything works.

I now use this other method to expose my json page’s url to Javascript, as suggested here by the person who made _kirby-json-api.

<script type="text/javascript">
    /**
     * Kirby JavaScript settings object. It contains settings and functions that JavaScript code
     * potentially needs to know about when dealing with Kirby
     */
    window.Kirby = {
        baseUrl: '<?php echo $site->url() ?>',
        url: function (path) {
            return this.baseUrl + (path && path[0] === '/' ? path : '/' + path);
        },
    };
</script>