Skip to content

Contexts

Compare
Choose a tag to compare
@tdumitrescu tdumitrescu released this 15 Dec 00:08
· 157 commits to master since this release

"Contexts" allow Panel components to inject arbitrary class/object dependencies into all descendants at runtime, similarly to React Context ("Context provides a way to pass data through the component tree without having to pass props down manually at every level"). This is especially useful for data which needs to be shared globally.

Components can provide named "default contexts" for themselves and descendants in their config objects. Components similarly declare which contexts they need by providing their names in the contexts config entry. Contexts can be accessed with the getContext() method, for example for use in view templates:

get config() {
  return {
    // provided to all descendants, including itself
    defaultContexts: {
      apiCache: new SharedCache(),
      moreSharedData: {foo: `bar`},
    },

    // used in this component
    contexts: [`apiCache`, `moreSharedData`],

    // calling a method on a context provided to the current component
    template: () => h(`p`, {}, `A value from the API Cache: ${this.getContext('apiCache').someMethod()}`),
  };
}