2019-06-19 17:31:49 +08:00
|
|
|
import { currentInstance } from './component'
|
|
|
|
|
2019-08-16 22:02:53 +08:00
|
|
|
export interface InjectionKey<T> extends Symbol {}
|
2019-06-19 17:31:49 +08:00
|
|
|
|
2019-08-20 02:45:11 +08:00
|
|
|
export function provide<T>(key: InjectionKey<T> | string, value: T) {
|
2019-06-19 17:31:49 +08:00
|
|
|
if (!currentInstance) {
|
|
|
|
// TODO warn
|
|
|
|
} else {
|
2019-06-19 22:48:22 +08:00
|
|
|
let provides = currentInstance.provides
|
|
|
|
// by default an instance inherits its parent's provides object
|
|
|
|
// but when it needs to provide values of its own, it creates its
|
|
|
|
// own provides object using parent provides object as prototype.
|
|
|
|
// this way in `inject` we can simply look up injections from direct
|
|
|
|
// parent and let the prototype chain do the work.
|
|
|
|
const parentProvides =
|
|
|
|
currentInstance.parent && currentInstance.parent.provides
|
|
|
|
if (parentProvides === provides) {
|
|
|
|
provides = currentInstance.provides = Object.create(parentProvides)
|
|
|
|
}
|
2019-06-19 17:31:49 +08:00
|
|
|
provides[key as any] = value
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-20 02:45:11 +08:00
|
|
|
export function inject<T>(key: InjectionKey<T> | string): T | undefined
|
|
|
|
export function inject<T>(key: InjectionKey<T> | string, defaultValue: T): T
|
2019-08-16 22:02:53 +08:00
|
|
|
export function inject(key: InjectionKey<any> | string, defaultValue?: any) {
|
2019-06-19 17:31:49 +08:00
|
|
|
if (!currentInstance) {
|
|
|
|
// TODO warn
|
|
|
|
} else {
|
2019-06-19 22:50:14 +08:00
|
|
|
// TODO should also check for app-level provides
|
2019-06-19 22:48:22 +08:00
|
|
|
const provides = currentInstance.parent && currentInstance.provides
|
2019-08-21 02:28:44 +08:00
|
|
|
return provides && key in provides
|
|
|
|
? (provides[key as any] as any)
|
|
|
|
: defaultValue
|
2019-06-19 17:31:49 +08:00
|
|
|
}
|
|
|
|
}
|