/knockout-router

Router for Knockout JS components with syntax inspired by ReactRouter

Primary LanguageTypeScriptMIT LicenseMIT

Knockout Router

Simple router designed for usage with Knockout JS components with syntax inspired by ReactRouter

Build Status GitHub license npm version

Example

<knockout-router rootUrl="/virtualApp" params="actions: actions">
  <home-view route="/:userId" action="loadUser"></home-view>
  <feeds-view route="/:userId/feeds" action="loadFeeds"></feeds-view>
</knockout-router>

<template id="home-view">
  <h1>Home</h1>
  <a data-bind="path: '~/' + params.userId() + '/feeds'">Feeds</a>
</template>

<template id="feeds-view">
  <h1>Feeds</h1>
  <a data-bind="path: '~/' + params.userId() + '/feeds'">Posts</a>
  <a data-bind="path: '~/' + params.userId() + '/feeds/images'">Images</a>
  
  <knockout-router routePrefix="/:userId/feeds">
    <posts-view route="/"></posts-view>
    <images-view route="/images"></images-view>
  </knockout-router>
</template>

<template id="posts-view">
  <h2>Posts</h2>
</template>

<template id="images-view">
  <h2>Images</h2>
</template>
import ko from "knockout";
import "knockout-router";

Array.from(document.querySelectorAll("template"))
  .map(node => node.getAttribute("id"))
  .forEach(id => {
    ko.components.register(id, template: { element: id });
  });

ko.applyBindings({
  actions: {
    async loadUser({ params }) {
      let resp = await fetch("/api/users/" + params.userId);
      // ...
    },
    async loadFeeds({ params }) {
      let resp = await fetch("/api/feets/" + params.userId);
      // ...
    }
  }
});

Documentation

Configuring routes

TBD

Router options


Route options


Actions and route context

TBD

Actions


Route context


Route component lifecycle


Custom bindings

TBD

path


query


activePathCss