∺ Hingejs

Router

This Router service is used to handle routes for a Single page Application (SPA)

↩ Go Back

Working sample

Page1 Page2

Sample code

HTML

      <h-route-link data-route="docs/">
        Page1
      </h-route-link>
      <h-route-link data-route="docs/page2">
        Page2
      </h-route-link>

      <h-route-display></h-route-display>
  

JavaScript

      <script type="module">
        import 'https://cdn.jsdelivr.net/npm/@hingejs/webcomponents@latest/index.min.js'
        import { Router } from 'https://cdn.jsdelivr.net/npm/@hingejs/services/index.min.js'

        /* using the HingeJS scaffold files will have a way to import html pages with webpack html-loader */
        const HtmlCache = new Map()
        HtmlCache.set('page1.html', '<template><p>Page 1</p></template><style>p { color: red; }</style>')
        HtmlCache.set('page2.html', '<template><p>Page 2</p></template><style>p { color: blue; }</style>')


        const RouteCtrlPage1 = async (req, next) => {
          req.exit(() => {
            console.log('anything you want to do before this function is complete')
          })
          const routeDisplay = document.querySelector('h-route-display')
          await routeDisplay.insertContent(HtmlCache.get('page1.html'))
          next()
        }

        const RouteCtrlPage2 = async (req, next) => {
          const routeDisplay = document.querySelector('h-route-display')
          await routeDisplay.insertContent(HtmlCache.get('page2.html'))
          next()
        }

        Router.defaultPath('docs/')
        Router.setPath('docs/', RouteCtrlPage1)
        Router.setPath('docs/page2', RouteCtrlPage2)

      </script>