|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright (c) 2021 Vaadin Ltd. |
| 4 | + * This program is available under Apache License Version 2.0, available at https://vaadin.com/license/ |
| 5 | + */ |
| 6 | +import { dedupingMixin } from '@polymer/polymer/lib/utils/mixin.js'; |
| 7 | + |
| 8 | +/** |
| 9 | + * A mixin for connecting controllers to the element. |
| 10 | + * |
| 11 | + * @polymerMixin |
| 12 | + */ |
| 13 | +export const ControllerMixin = dedupingMixin( |
| 14 | + (superClass) => |
| 15 | + class ControllerMixinClass extends superClass { |
| 16 | + constructor() { |
| 17 | + super(); |
| 18 | + |
| 19 | + /** |
| 20 | + * @type {Set<import('lit').ReactiveController>} |
| 21 | + */ |
| 22 | + this.__controllers = new Set(); |
| 23 | + } |
| 24 | + |
| 25 | + /** @protected */ |
| 26 | + connectedCallback() { |
| 27 | + super.connectedCallback(); |
| 28 | + |
| 29 | + this.__controllers.forEach((c) => { |
| 30 | + c.hostConnected && c.hostConnected(); |
| 31 | + }); |
| 32 | + } |
| 33 | + |
| 34 | + /** @protected */ |
| 35 | + disconnectedCallback() { |
| 36 | + super.disconnectedCallback(); |
| 37 | + |
| 38 | + this.__controllers.forEach((c) => { |
| 39 | + c.hostDisconnected && c.hostDisconnected(); |
| 40 | + }); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Registers a controller to participate in the element update cycle. |
| 45 | + * |
| 46 | + * @param {import('lit').ReactiveController} controller |
| 47 | + * @protected |
| 48 | + */ |
| 49 | + addController(controller) { |
| 50 | + this.__controllers.add(controller); |
| 51 | + // Call hostConnected if a controller is added after the element is attached. |
| 52 | + if (this.$ !== undefined && this.isConnected && controller.hostConnected) { |
| 53 | + controller.hostConnected(); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Removes a controller from the element. |
| 59 | + * |
| 60 | + * @param {import('lit').ReactiveController} controller |
| 61 | + * @protected |
| 62 | + */ |
| 63 | + removeController(controller) { |
| 64 | + this.__controllers.delete(controller); |
| 65 | + } |
| 66 | + } |
| 67 | +); |
0 commit comments