diff --git a/README.md b/README.md index 23d90fe..8fbaefc 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,14 @@ import { bootstrap } from '@leanadmin/alpine-typescript'; bootstrap(); ``` +Additionally, you can use the `addTitles()` function to add `x-title` attributes to all components. The class name of each component will be used as its title. This is useful if you're using tools like the [Alpine.js devtools](https://github.com/alpine-collective/alpinejs-devtools). + +```ts +import { addTitles } from '@leanadmin/alpine-typescript'; + +addTitles(); +``` + ## Usage You can use a component by calling `Alpine.component('componentName')(arg1, arg2)`. If your component has no arguments, still append `()` at the end of the call. diff --git a/src/index.ts b/src/index.ts index a77cfa0..278368a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -16,10 +16,12 @@ export abstract class AlpineComponent { $dispatch?: (event: string, data: object) => void; /** Execute a given expression AFTER Alpine has made its reactive DOM updates. */ - $nextTick?: (callback: () => void) => void; + $nextTick?: (callback: (_: any) => void) => void; /** Will fire a provided callback when a component property you "watched" gets changed. */ $watch?: (property: string, callback: (value: any) => void) => void; + + [key: string]: any; } export function registerComponents(components: { [name: string]: Function }): { [name: string]: ComponentConstructor } { @@ -63,6 +65,16 @@ export function convertClassToAlpineConstructor(component: any): ComponentConstr } } +export function addTitles(): void { + window.Alpine.onBeforeComponentInitialized((component: AlpineComponent) => { + if (! component.$el.hasAttribute('x-title')) { + if (component.$data.constructor.prototype instanceof AlpineComponent) { + component.$el.setAttribute('x-title', component.$data.constructor.name); + } + } + }); +} + export function bootstrap(): void { window.AlpineComponents = {};