0.0.5 • Published 4 years ago

ember-contextual-services--alpha v0.0.5

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

ember-contextual-services

Eliminate Prop-Drilling by Providing Ephemeral Services based on the route!

Supports

  • Ember.js v3.4 or above

Installation

ember install ember-contextual-services--alpha

Usage

All ContextualServices are classes that can hold any state or perform any action. They could represent specific interfaces to APIs, or a way of accessing data loaded from ember-data from deep within the route's component tree.

NOTE: all of these examples are available for viewing in the tests/dummy folder.

in routes/wherever/-contexts/local-service.js;

import { ContextualService } from 'ember-contextual-services';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export class LocalService extends ContextualService {
  @service router;

  @tracked foo = 0;

  @action incrementFoo() {
    this.foo++;
  }
}

in routes/wherever/some-route.js

import Route from '@ember/routing/route';
import { withContextualServices } from 'ember-contextual-services';

import { LocalService } from './-contexts/local-service';

@withContextualServices(LocalService)
export default class SomeRoute extends Route {

}

or if you want to utilize the route's model hook for data-loading, you could do:

@withContextualServices(PersonService)
export default class SomeRoute extends Route {
  @context(PersonService) personService;

  async model() {
    let response = await fetch('https://swapi.co/api/people/1/');
    let json = await response.json();

    this.personService.data = json;
  }
}

and finally, in a component that is rendered by your route's template or a tree of components fromy our route's template,

import Component from '@glimmer/component';

import { context } from 'ember-contextual-services';

import { LocalService } from 'my-app/routes/whatever/-contexts/local-service';

export default class ServiceConsumer extends Component {
  @context(LocalService) localService;
}

Contributing

See the Contributing guide for details.

License

This project is licensed under the MIT License.