Skip to content

Commit 910f2fd

Browse files
Nipun Paradkardhh
Nipun Paradkar
andauthored
Adds new Action Options, namely :self and :!self (#546)
Co-authored-by: David Heinemeier Hansson <[email protected]>
1 parent 5a60cde commit 910f2fd

File tree

4 files changed

+31
-1
lines changed

4 files changed

+31
-1
lines changed

docs/reference/actions.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ Custom action option | Description
107107
-------------------- | -----------
108108
`:stop` | calls `.stopPropagation()` on the event before invoking the method
109109
`:prevent` | calls `.preventDefault()` on the event before invoking the method
110+
`:self` | only invokes the method if the event was fired by the element itself
110111

111112
## Event Objects
112113

src/core/binding.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ export class Binding {
3131
}
3232

3333
handleEvent(event: Event) {
34-
if (this.willBeInvokedByEvent(event)) {
34+
if (this.willBeInvokedByEvent(event) && this.shouldBeInvokedPerSelf(event)) {
3535
this.processStopPropagation(event);
3636
this.processPreventDefault(event);
3737

@@ -77,6 +77,14 @@ export class Binding {
7777
}
7878
}
7979

80+
private shouldBeInvokedPerSelf(event: Event): boolean {
81+
if (this.action.eventOptions.self === true) {
82+
return this.action.element === event.target
83+
} else {
84+
return true
85+
}
86+
}
87+
8088
private willBeInvokedByEvent(event: Event): boolean {
8189
const eventTarget = event.target
8290
if (this.element === eventTarget) {

src/core/event_modifiers.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export interface EventModifiers extends AddEventListenerOptions {
22
stop?: boolean;
33
prevent?: boolean;
4+
self?: boolean;
45
}

src/tests/modules/core/event_options_tests.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,26 @@ export default class EventOptionsTests extends LogControllerTestCase {
190190
)
191191
}
192192

193+
async "test self option"() {
194+
this.setAction(this.buttonElement, "click->c#log:self")
195+
await this.nextFrame
196+
197+
await this.triggerEvent(this.buttonElement, "click")
198+
199+
this.assertActions(
200+
{ name: "log", eventType: "click" }
201+
)
202+
}
203+
204+
async "test self option on parent"() {
205+
this.setAction(this.element, "click->c#log:self")
206+
await this.nextFrame
207+
208+
await this.triggerEvent(this.buttonElement, "click")
209+
210+
this.assertNoActions()
211+
}
212+
193213
setAction(element: Element, value: string) {
194214
element.setAttribute("data-action", value)
195215
}

0 commit comments

Comments
 (0)