Skip to content

Commit

Permalink
feat(BaseController): New method eventName to generate an event nam…
Browse files Browse the repository at this point in the history
…e using the controllers identifier
  • Loading branch information
Sub-Xaero committed Sep 13, 2022
1 parent a600b77 commit c8a8d41
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
14 changes: 11 additions & 3 deletions docs/docs/controllers/extendable/base_controller.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ This controller provides the following methods to controllers that extend it.
| | `name` | The `name` attribute of the `meta` tag to fetch the value of | |


| Name | Parameters | Purpose | Return value |
|-------------|-------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------|
| `eventName` | | Construct an colon separated event name using the controllers identifier .i.e in `FooController` calling `eventName("loaded")` would result in `foo:loaded`. | `string` |
| | `eventName` | The name of the event to append to the controllers identifier to create a fully namespaced event | |


## Side Effects / Inherited Behaviour

If [debug mode](/docs/debugging) is enabled, any controller that extends BaseController controller will automatically log calls to any actions or methods, and events dispatched with the `dispatchEvent` method provided by stimulus-library.
Expand All @@ -49,12 +55,14 @@ If there are any getters, setters, methods or properties that should not be logg
```typescript
import {BaseController} from "stimulus-library";

export default class extends BaseController {
export default class FooController extends BaseController {
// ...

foo() {
this.dispatchEvent(this.el, "my-controller:something-happened", { bubbles: true, cancellable: true, detail: { element: this.el, data: 'thing' } } )
this.dispatchEvent(this.el, "foo:something-happened", { bubbles: true, cancellable: true, detail: { element: this.el, data: 'thing' } } ) // dispatches a custom event named `foo:something-happened`
// or
this.dispatchEvent(this.el, this.eventName("something-happened"), { bubbles: true, cancellable: true, detail: { element: this.el, data: 'thing' } } ) // also dispatches `foo:something-happened`
}

}
```
```
4 changes: 4 additions & 0 deletions src/utilities/base_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ export class BaseController extends Controller {
return element?.getAttribute('content') || null;
}

eventName(eventName: string) {
return `${this.identifier}:${eventName}`
}

dispatchEvent(element: HTMLElement, eventName: string, options: CustomEventInit = {}) {
dispatchEvent(this, element, eventName, options);
}
Expand Down

0 comments on commit c8a8d41

Please sign in to comment.