|
| 1 | +import { getOwner, setOwner } from "@ember/application"; |
| 2 | +import { assert } from "@ember/debug"; |
| 3 | +import { associateDestroyableChild } from "@ember/destroyable"; |
| 4 | + |
| 5 | +/** |
| 6 | + * A util to abstract away the boilerplate of linking of "things" with an owner |
| 7 | + * and making them destroyable. |
| 8 | + * |
| 9 | + * |
| 10 | + * Example as a class property: |
| 11 | + * ```js |
| 12 | + * import { link } from 'ember-resources/link'; |
| 13 | + * |
| 14 | + * class MyClass { ... } |
| 15 | + * |
| 16 | + * export default class Demo extends Component { |
| 17 | + * @link(MyClass) myInstance; |
| 18 | + * } |
| 19 | + * ``` |
| 20 | + * |
| 21 | + * Example inline usage: |
| 22 | + * ```js |
| 23 | + * import Component from '@glimmer/component'; |
| 24 | + * import { cached } from '@glimmer/tracking'; |
| 25 | + * import { link } from 'ember-resources/link'; |
| 26 | + * |
| 27 | + * export default class Demo extends Component { |
| 28 | + * @cached |
| 29 | + * get myFunction() { |
| 30 | + * let instance = new MyClass(this.args.foo); |
| 31 | + * |
| 32 | + * return link(instance, this); |
| 33 | + * } |
| 34 | + * } |
| 35 | + * ``` |
| 36 | + */ |
| 37 | +function link(_prototype: object, key: string, descriptor?: Descriptor): void { |
| 38 | + if (!descriptor) return; |
| 39 | + |
| 40 | + assert(`@link can only be used with string-keys`, typeof key === 'string'); |
| 41 | + |
| 42 | + |
| 43 | + let { initializer } = descriptor; |
| 44 | + |
| 45 | + assert( |
| 46 | + `@link may only be used on initialized properties. For example, ` + |
| 47 | + `\`@link foo = new MyClass();\``, |
| 48 | + initializer |
| 49 | + ); |
| 50 | + |
| 51 | + |
| 52 | + let caches = new WeakMap<object, any>(); |
| 53 | + |
| 54 | + // https://github.com/pzuraq/ember-could-get-used-to-this/blob/master/addon/index.js |
| 55 | + return { |
| 56 | + get(this: object) { |
| 57 | + let child = caches.get(this); |
| 58 | + |
| 59 | + if (!child) { |
| 60 | + child = initializer.call(this); |
| 61 | + |
| 62 | + associateDestroyableChild(this, child); |
| 63 | + |
| 64 | + let owner = getOwner(this); |
| 65 | + |
| 66 | + if (owner) { |
| 67 | + setOwner(child, owner); |
| 68 | + } |
| 69 | + |
| 70 | + caches.set(this, child); |
| 71 | + assert(`Failed to create cache for internal resource configuration object`, child); |
| 72 | + } |
| 73 | + |
| 74 | + return child; |
| 75 | + }, |
| 76 | + } as unknown as void /* Thanks TS. */; |
| 77 | +} |
0 commit comments