Skip to content

Commit

Permalink
Make dispatchEvent fire for camelCased event props
Browse files Browse the repository at this point in the history
  • Loading branch information
Brian Kim committed Mar 4, 2024
1 parent dc904d9 commit 445746f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/crank.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1935,12 +1935,27 @@ export class Context<T = any, TResult = any> implements EventTarget {
{
setEventProperty(ev, "eventPhase", AT_TARGET);
setEventProperty(ev, "currentTarget", ctx.owner);
const propCallback = ctx.ret.el.props["on" + ev.type] as unknown;

// dispatchEvent calls the prop callback if it exists
let propCallback = ctx.ret.el.props["on" + ev.type] as unknown;
if (typeof propCallback === "function") {
propCallback(ev);
if (immediateCancelBubble || ev.cancelBubble) {
return true;
}
} else {
// Checks for camel-cased event props
for (const propName in ctx.ret.el.props) {
if (propName.toLowerCase() === "on" + ev.type.toLowerCase()) {
propCallback = ctx.ret.el.props[propName] as unknown;
if (typeof propCallback === "function") {
propCallback(ev);
if (immediateCancelBubble || ev.cancelBubble) {
return true;
}
}
}
}
}

const listeners = listenersMap.get(ctx);
Expand Down
13 changes: 13 additions & 0 deletions test/events.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,19 @@ test("event props", () => {
Assert.is(mock.callCount, 1);
});

test("event props camelCased", () => {
let ctx!: Context;
function Component(this: Context, _props: {onFoo: (ev: Event) => any}) {
ctx = this;
return <span>Hello</span>;
}

const mock = Sinon.fake();
renderer.render(<Component onFoo={mock} />, document.body);
ctx.dispatchEvent(new Event("foo"));
Assert.is(mock.callCount, 1);
});

test("error thrown in listener", () => {
let ctx!: Context;
function Component(this: Context) {
Expand Down

0 comments on commit 445746f

Please sign in to comment.