Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow action params for global events #495

Merged
merged 1 commit into from
Nov 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 5 additions & 14 deletions src/core/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,26 +30,17 @@ export class Action {
return `${this.eventName}${eventNameSuffix}->${this.identifier}#${this.methodName}`
}

get params(): object {
if (this.eventTarget instanceof Element) {
return this.getParamsFromEventTargetAttributes(this.eventTarget)
} else {
return {}
}
}

private getParamsFromEventTargetAttributes(eventTarget: Element): {[key: string]: any} {
const params = {}
get params() {
const params:{ [key: string]: any } = {}
const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`)
const attributes = Array.from(eventTarget.attributes)

attributes.forEach(({ name, value }: { name: string, value: string }) => {
for (const { name, value } of Array.from(this.element.attributes)) {
const match = name.match(pattern)
const key = match && match[1]
if (key) {
Object.assign(params, { [camelize(key)]: typecast(value) })
params[camelize(key)]= typecast(value)
}
})
}
return params
}

Expand Down
11 changes: 11 additions & 0 deletions src/tests/modules/core/action_params_tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export default class ActionParamsTests extends LogControllerTestCase {
<div id="nested"></div>
</button>
</div>
<div id="outside"></div>
`
expectedParamsForC = {
id: 123,
Expand All @@ -38,6 +39,16 @@ export default class ActionParamsTests extends LogControllerTestCase {
)
}

async "test global event return element params where the action is defined"() {
this.actionValue = "keydown@window->c#log"
await this.nextFrame
await this.triggerEvent("#outside", "keydown")

this.assertActions(
{ identifier: "c", params: this.expectedParamsForC },
)
}

async "test passing params to namespaced controller"() {
this.actionValue = "click->c#log click->d#log2"
await this.nextFrame
Expand Down