knockout-contrib

:metal: KnockoutJS Goodies Monorepo

View the Project on GitHub Profiscience/knockout-contrib

router.plugins.with

Version Dependency Status Peer Dependency Status Dev Dependency Status Downloads

Allows extending the context for a route with arbitrary data

Usage

import { Route, withRoutePlugin } from '@profiscience/knockout-contrib'

Route.usePlugin(withRoutePlugin)

// Sync
new Route('/', {
  with: {
    myAdditionalProp: true,
  },
})

// Accessor
new Route('/', {
  with: (ctx) => {
    // synchronous
    return {
      myAdditionalProp: true,
    }

    // async via promises
    return Promise.resolve({
      myAdditionalProp: true,
    })
  },
})

Now, in the viewModel (as well as any subsequent middleware), ctx.myAdditionalProp will be true.

NOTE: If you’re using TypeScript, it’s worth noting that the return type is strongly typed. The properties it adds must be defined on the IContext interface, or cast as any.

e.g.

declare module '@profiscience/knockout-contrib-router' {
  interface IContext {
    myAdditionalProp?: boolean
  }
}

// ...or...

new Route('/', {
  with: {
    myAdditionalProp: true,
  } as any,
})