Skip to content

Commit

Permalink
* core: support for setting options from $options.
Browse files Browse the repository at this point in the history
  • Loading branch information
catouse committed Sep 10, 2024
1 parent f1e4d19 commit 17d98ed
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
18 changes: 15 additions & 3 deletions lib/core/src/component/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,7 @@ export class Component<O extends {} = {}, E extends ComponentEventsDefnition = {
this._gid = gid;
this._element = element;

this._options = {...DEFAULT, ...(options?.$optionsFromDataset !== false ? $element.dataset() : {})} as ComponentOptions<O>;
this.setOptions(options);
this.resetOptions(options);
this._key = this.options.key ?? `__${gid}`;

if (ALL.has(element)) {
Expand Down Expand Up @@ -333,17 +332,30 @@ export class Component<O extends {} = {}, E extends ComponentEventsDefnition = {
*/
setOptions(options?: Partial<ComponentOptions<O>>, reset?: boolean): ComponentOptions<O> {
if (reset) {
this._options = {
const finalOptions = {
...this.constructor.DEFAULT,
...(options?.$optionsFromDataset !== false ? this.$element.dataset() : {}),
...options,
} as ComponentOptions<O>;
const {$options} = finalOptions;
if ($options) {
const extraOptions = typeof $options === 'function' ? $options(this.element, finalOptions) : $options;
if (extraOptions) {
$.extend(finalOptions, extraOptions);
}
delete finalOptions.$options;
}
this._options = finalOptions;
} else if (options) {
$.extend(this._options, options);
}
return this._options!;
}

resetOptions(options?: Partial<ComponentOptions<O>>) {
return this.setOptions(options, true);
}

/**
* Emit a component event.
* @param event The event name.
Expand Down
4 changes: 3 additions & 1 deletion lib/core/src/component/types/component-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ export type ComponentBaseOptions = {
/**
* The component options.
*/
export type ComponentOptions<O extends {} = {}> = ComponentBaseOptions & O;
export type ComponentOptions<O extends {} = {}> = ComponentBaseOptions & O & {
$options?: Partial<O> | ((element: HTMLElement, options: Partial<O>) => Partial<O> | undefined);
};

0 comments on commit 17d98ed

Please sign in to comment.