Skip to content

Commit

Permalink
[lit/context] Use target.set for setting context values
Browse files Browse the repository at this point in the history
`target.set` is the correct way to set values in decorators. It supports nested decorators and private fields.
  • Loading branch information
jun-sheaf committed Mar 26, 2024
1 parent dd74c60 commit 8b18d66
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/thirty-shirts-peel.md
@@ -0,0 +1,5 @@
---
'@lit/context': patch
---

Use `target.set` instead of member assignment
17 changes: 9 additions & 8 deletions packages/context/src/lib/decorators/consume.ts
Expand Up @@ -47,18 +47,19 @@ export function consume<ValueType>({
context: Context<unknown, ValueType>;
subscribe?: boolean;
}): ConsumeDecorator<ValueType> {
return (<C extends ReactiveElement, V extends ValueType>(
protoOrTarget: ClassAccessorDecoratorTarget<C, V>,
nameOrContext: PropertyKey | ClassAccessorDecoratorContext<C, V>
return ((
protoOrTarget: ClassAccessorDecoratorTarget<ReactiveElement, ValueType>,
nameOrContext:
| PropertyKey
| ClassAccessorDecoratorContext<ReactiveElement, ValueType>
) => {
if (typeof nameOrContext === 'object') {
// Standard decorators branch
nameOrContext.addInitializer(function (this: ReactiveElement): void {
nameOrContext.addInitializer(function (): void {
new ContextConsumer(this, {
context,
callback: (value: ValueType) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(this as any)[nameOrContext.name] = value;
callback: (value) => {
protoOrTarget.set.call(this, value);
},
subscribe,
});
Expand All @@ -69,7 +70,7 @@ export function consume<ValueType>({
(element: ReactiveElement): void => {
new ContextConsumer(element, {
context,
callback: (value: ValueType) => {
callback: (value) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(element as any)[nameOrContext] = value;
},
Expand Down

0 comments on commit 8b18d66

Please sign in to comment.