Example: States & Routes

Sourcecode

              


  // IntroState is the default state (ie. entry point)
  class IntroState extends IF.State
  {
    static ROUTE = '/';

    static TEMPLATE = `
    <h1>Hello!</h1>
    <a href="<%= urlToPasswordState %>">NEXT ›</a>
    `;
    async enter()
    {
      this.app.view.render(
              this.app.container,
              IntroState.TEMPLATE,
              {
                urlToPasswordState : this.app.router.createUrl( 'question' )
              }
      );
    }
  }

  // QuestionState asks for the name and calls WelcomeState with parameter
  class QuestionState extends IF.State
  {
    static ROUTE = 'question';
    async enter()
    {
      const container = this.app.container;
      this.app.view.render(
              container,
              '<h1>Please, tell me your name.</h1><input placeholder="Your name"/><button>NEXT ›</button>'
      );
      container.querySelector( 'button' ).addEventListener( 'click', () => {
        const name = IF.Helper.trim( container.querySelector( 'input' ).value );
        this.app.router.redirect( this.app.router.createUrl( 'welcome/' + ( name.length ? name : 'Stranger' ) ) );
      }, { once : true } );
    }
  }

  // WelcomeState accepts requires 'name' as parameter and outputs it
  class WelcomeState extends IF.State
  {
    static ROUTE = 'welcome/:name'

    async enter()
    {
      this.app.view.render(
        this.app.container,
        '<h1>Nice to meet you, <%= name %>!</h1><a href="<%= urlToForbiddenState %>">FORBIDDEN STATE ›</a><a href="<%= urlToIntroState %>">HOME ›</a>',
        {
          name : this.routeParams.getParam( 'name', 'Stranger' ),
          urlToForbiddenState : this.app.router.createUrl( ForbiddenState.ROUTE ),
          urlToIntroState : this.app.router.createUrl( IntroState.ROUTE )
        }
      );
    }
  }

  // ForbiddenState demonstrate the canEnter() function of each State.
  class ForbiddenState extends IF.State
  {
    static ROUTE = 'forbidden';

    // canEnter() is called before the State.enter function is triggered by IF.States logic
    canEnter()
    {
      alert( "Access Denied!" );
      return false;
    }

    // If IF.State.canEnter() returns false - this function is called to resolve the url to redirect to
    getRedirectUrl()
    {
      return this.app.router.createUrl( IntroState.ROUTE);
    }
  }

  // Settings for example environment
  const appSettings = { router : { basePath : "/04-states-and-routes/" } };

  const myApp = new IF.App( document.getElementById( 'app' ), appSettings );
  myApp.states.add( IntroState, QuestionState, WelcomeState, ForbiddenState );
  myApp.run();