blib/lib/HTML/Object/EventTarget.pm untested

filter: Statementstmt 0.0% 0 / 262 Branchbran 0.0% 0 / 138 Conditioncond 0.0% 0 / 134 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 567 CC 70 SCAR 47.9
CC
70
Cov
0%
addEventListener
240.0
handleEvent
210.0
removeEventListener
156.0
CRAP 120.6
1 ##----------------------------------------------------------------------------
2 ## HTML Object - ~/lib/HTML/Object/EventTarget.pm
3 ## Version v0.3.0
4 ## Copyright(c) 2022 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2021/12/11
7 ## Modified 2025/10/16
8 ## All rights reserved
9 ##
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package HTML::Object::EventTarget;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'HTML::Object' );
20 # Changed inheritance from Module::Generic to HTML::Object::Element, because I need modules like
21 # HTML::Object::DOM::TextTrack that inherits from EventTarget to also have the parent method provided
22 # by the core module HTML::Object::Element
23 use parent qw( HTML::Object::Element );
24 use vars qw( $PACK_SUB_RE $SIGNALS $VERSION );
25 use HTML::Object::EventListener;
26 use Scalar::Util ();
27 use Wanted;
28 our $PACK_SUB_RE = qr/^(((?<pack>[a-zA-Z\_]\w*(?:\:\:\w+)*)\:\:)?(?<sub>\w+))$/;
29 # Hash reference of signal to array of object to remove their listeners
30 our $SIGNALS = {};
31 our $VERSION = 'v0.3.0';
32 };
33  
34 use strict;
35 use warnings;
36  
37 sub init
38 {
39 my $self = shift( @_ );
40 $self->{tag} = 'eventtarget';
41 $self->{_init_strict_use_sub} = 1 unless( CORE::exists( $self->{_init_strict_use_sub} ) );
42 $self->{_exception_class} = 'HTML::Object::Exception' unless( CORE::exists( $self->{_exception_class} ) );
43 $self->SUPER::init( @_ ) || return( $self->pass_error );
44 $self->{event_listeners} = {};
45 return( $self );
46 }
47  
48 sub addEventListener
49 {
50 my $self = shift( @_ );
51 my $type = shift( @_ ) || return( $self->error( "No event listener type was provided." ) );
52 my $callback = shift( @_ ) || return( $self->error( "No event listener callback was provided." ) );
53 return( $self->error( "Event listener type \"$type\" contains illegal characters. It should contain only alphanumeric and _ characters." ) ) if( $type !~ /^\w+$/ );
54 $type = lc( $type );
55 if( !ref( $callback ) && $callback =~ /$PACK_SUB_RE/ )
56 {
57 my( $pack, $sub ) = @+{qw( pack sub )};
58 $pack ||= caller;
59 if( my $ref = $pack->can( $sub ) )
60 {
61 $callback = $ref;
62 }
63 else
64 {
65 return( $self->error( "Unknown subroutine \"$callback\" in package \"$pack\"." ) );
66 }
67 }
68 return( $self->error( "Event listener callback is not a code reference." ) ) if( ref( $callback ) ne 'CODE' );
69 my $opts = $self->_get_args_as_hash( @_ );
70 my @ok_params = qw( capture once passive signal debug );
71 my $params = {};
72 @$params{ @ok_params } = CORE::delete( @$opts{ @ok_params } );
73 my $post_processing;
74 $post_processing = CORE::delete( $opts->{post_processing} ) if( CORE::exists( $opts->{post_processing} ) && ref( $opts->{post_processing} ) eq 'CODE' );
75 if( scalar( keys( %$opts ) ) )
76 {
77 warn( "Unrecognised options: '" . join( "', '", sort( keys( %$opts ) ) ) . "'\n" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
78 }
79 $params->{capture} //= 0;
80 $params->{once} //= 0;
81 $params->{passive} //= 0;
82 my $key = join( ';', $type, Scalar::Util::refaddr( $callback ), $params->{capture} );
83 $self->{event_listeners} = {} if( !CORE::exists( $self->{event_listeners} ) );
84 my $repo = $self->{event_listeners};
85 my $debug = CORE::delete( $params->{debug} ) || 0;
86 my $eh = HTML::Object::EventListener->new(
87 type => $type,
88 code => $callback,
89 options => $params,
90 element => $self,
91 debug => $debug,
92 ) || return( $self->pass_error( HTML::Object::EventListener->error ) );
93 if( $params->{signal} && $params->{signal} =~ /^\w+$/ )
94 {
95 $SIG{ $params->{signal} } = \&_signal_remove_listeners;
96 $SIGNALS->{ $params->{signal} } = [] if( !CORE::exists( $SIGNALS->{ $params->{signal} } ) );
97 push( @{$SIGNALS->{ $params->{signal} }}, $eh );
98 }
99 $repo->{ $type } = {} if( !CORE::exists( $repo->{ $type } ) );
100 $repo->{ $type }->{sequence} = $self->new_array if( !CORE::exists( $repo->{ $type }->{sequence} ) );
101 $repo->{ $type }->{ $key } = $eh;
102 if( $repo->{ $type }->{sequence}->has( $key ) )
103 {
104 $repo->{ $type }->{sequence}->remove( $key );
105 }
106 $repo->{ $type }->{sequence}->push( $key );
107 # Call any post-processing callback if necessary.
108 # Those are used so that event monitoring can be enabled upon setting event handlers and not before, on some data like array or scalar
109 # See HTML::Object::LDOM::List for example
110 if( defined( $post_processing ) )
111 {
112 $post_processing->( $eh );
113 }
114 return( $eh );
115 }
116  
117 sub dispatchEvent
118 {
119 my $self = shift( @_ );
120 my $event = shift( @_ ) || return( $self->error( "No event object was provided." ) );
121 return( $self->error( "Event object provided ($event) is not an HTML::Object::Event" ) ) if( !$self->_is_a( $event => 'HTML::Object::Event' ) );
122 $event->target( $self );
123
124 my $type = $event->type || return( $self->error( "The event has no type associated with it!" ) );
125 $type = lc( $type );
126 my $can_cancel = $event->cancelable;
127 return( $self ) if( $can_cancel && $event->cancelled );
128 # from current element to top one
129 my $path = $event->composedPath;
130 $event->eventPhase( $event->CAPTURING_PHASE );
131 # Go from top to our element, i.e. reverse
132 $path->reverse->foreach(sub
133 {
134 my $node = shift( @_ );
135 $event->currentTarget( $node );
136 $node->handleEvent( $event ) || do
137 {
138 warn( "Error handling event: ", $node->error ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
139 };
140 if( $can_cancel && $event->cancelled )
141 {
142 return(0);
143 }
144 # Make sure to return true to keep looping
145 return(1);
146 });
147 return( $self ) if( $can_cancel && $event->cancelled >= $event->CANCEL_IMMEDIATE_PROPAGATION );
148 $event->eventPhase( $event->AT_TARGET );
149 $event->currentTarget( $self );
150 $self->handleEvent( $event );
151 return( $self ) if( $can_cancel && $event->cancelled >= $event->CANCEL_PROPAGATION );
152 # This event does not bubble, so we do nothing more
153 return( $self ) if( !$event->bubbles );
154 $event->eventPhase( $event->BUBBLING_PHASE );
155 # Now, go from our element to the top one
156 $path->for(sub
157 {
158 my( $i, $node ) = @_;
159 # Skip the first one which is us.
160 return(1) if( $i == 0 );
161 $event->currentTarget( $node );
162 $node->handleEvent( $event ) || do
163 {
164 warn( "Error handling event: ", $node->error ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
165 };
166 if( $can_cancel && $event->cancelled )
167 {
168 return(0);
169 }
170 # Make sure to return true to keep looping
171 return(1);
172 });
173 return( $self );
174 }
175  
176 sub event_listeners { return( shift->_set_get_hash( 'event_listeners', @_ ) ); }
177  
178 sub getEventListeners
179 {
180 my $self = shift( @_ );
181 my $type = shift( @_ );
182 return( $self->error( "No event type propoded to get its event listeners." ) ) if( !defined( $type ) || !CORE::length( $type ) );
183 $self->{event_listeners} = {} if( !CORE::exists( $self->{event_listeners} ) );
184 my $repo = $self->{event_listeners};
185 return if( !scalar( keys( %$repo ) ) );
186 $repo->{ $type } = {} if( !CORE::exists( $repo->{ $type } ) );
187 $repo->{ $type }->{sequence} = $self->new_array if( !CORE::exists( $repo->{ $type }->{sequence} ) );
188 my $results = $self->new_array;
189 $repo->{ $type }->{sequence}->foreach(sub
190 {
191 my $key = shift( @_ );
192 $results->push( $repo->{ $type }->{ $key } ) if( CORE::exists( $repo->{ $type }->{ $key } ) && $self->_is_a( $repo->{ $type }->{ $key } => 'HTML::Object::EventListener' ) );
193 });
194 return( $results );
195 }
196  
197 sub handleEvent
198 {
199 my $self = shift( @_ );
200 my $evt = shift( @_ ) || return( $self->error({
201 message => "No event was provided to handle.",
202 class => 'HTML::Object::SyntaxError',
203 }) );
204 return( $self->error({
205 message => "Event object provided is not an event of class HTML::Object::Event or its descendants.",
206 class => 'HTML::Object::TypeError',
207 }) ) if( !$self->_is_a( $evt => 'HTML::Object::Event' ) );
208 return( $self ) if( $evt->cancelled );
209 my $can_cancel = $evt->cancelable;
210
211 my $repo = $self->{event_listeners};
212 my $type = $evt->type || return( $self->error({
213 message => "No event type was provided.",
214 class => 'HTML::Object::SyntaxError',
215 }) );
216 return( $self ) if( !CORE::exists( $repo->{ $type } ) );
217 return( $self->error({
218 message => "Repository of event listener of type '$type' is not an hash reference!",
219 class => 'HTML::Object::TypeError',
220 }) ) if( ref( $repo->{ $type } ) ne 'HASH' );
221
222 return( $self->error({
223 message => "Could not find the 'sequence' property in the repository of event listeners.",
224 class => 'HTML::Object::SyntaxError',
225 }) ) if( !CORE::exists( $repo->{ $type }->{sequence} ) );
226 return( $self->error({
227 message => "Sequence property of event listeners for type '$type' is not a Module::Generic::Array object",
228 class => 'HTML::Object::TypeError',
229 }) ) if( !$self->_is_a( $repo->{ $type }->{sequence} => 'Module::Generic::Array' ) );
230  
231 $evt->currentTarget( $self );
232 my $eventPhase = $evt->eventPhase;
233 foreach my $key ( @{$repo->{ $type }->{sequence}} )
234 {
235 return( $self->error({
236 message => "Empty key found in sequence repository.",
237 class => 'HTML::Object::SyntaxError',
238 }) ) if( !defined( $key ) || !CORE::length( $key ) );
239 if( !CORE::exists( $repo->{ $type }->{ $key } ) )
240 {
241 return( $self->error({
242 message => "Found an event listener of type '$type' with key '$key', but could not find its associated entry in the event listener repository.",
243 class => 'HTML::Object::SyntaxError',
244 }) );
245 }
246 my $listener = $repo->{ $type }->{ $key };
247 if( !$self->_is_a( $listener => 'HTML::Object::EventListener' ) )
248 {
249 return( $self->error({
250 message => "The event listener of type '$type' found is not an HTML::Object::EventListener object.",
251 class => 'HTML::Object::TypeError',
252 }) );
253 }
254
255 # check we are in the right phase
256 if( ( $eventPhase eq $evt->AT_TARGET && $evt->target ne $self ) ||
257 ( $eventPhase eq $evt->CAPTURING_PHASE && !$listener->capture ) ||
258 ( $eventPhase eq $evt->BUBBLING_PHASE && $listener->capture ) )
259 {
260 next;
261 }
262
263 my $code = $listener->code;
264 if( ref( $code ) ne 'CODE' )
265 {
266 # return( $self->error({
267 # message => "The handler for the event listener of type '$type' is not a code reference.",
268 # class => 'HTML::Object::TypeError',
269 # }) );
270 warn( "Warning only: the handler for the event listener of type '$type' is not a code reference." ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
271 next;
272 }
273 local $_ = $self;
274 # Note: Should we catch a die, or let it die, if that were the case?
275 $code->( $evt );
276 last if( $can_cancel && $evt->cancelled == $evt->CANCEL_IMMEDIATE_PROPAGATION );
277 }
278 return( $self );
279 }
280  
281 sub hasEventListener
282 {
283 my $self = shift( @_ );
284 my $type = shift( @_ );
285 $self->{event_listeners} = {} if( !CORE::exists( $self->{event_listeners} ) );
286 my $repo = $self->{event_listeners};
287 return( $self->new_number(0) ) if( !scalar( keys( %$repo ) ) );
288 if( defined( $type ) && CORE::length( $type ) )
289 {
290 $repo->{ $type } = {} if( !CORE::exists( $repo->{ $type } ) );
291 my $n = scalar( keys( %{$repo->{ $type }} ) );
292 $n-- if( CORE::exists( $repo->{ $type }->{sequence} ) );
293 return( $self->new_number( $n ) );
294 }
295 my $n = 0;
296 foreach my $t ( keys( %$repo ) )
297 {
298 $n += scalar( keys( %{$repo->{ $t }} ) );
299 $n-- if( CORE::exists( $repo->{ $t }->{sequence} ) );
300 }
301 return( $self->new_number( $n ) );
302 }
303  
304 sub on : lvalue
305 {
306 my $self = shift( @_ );
307 my $event = shift( @_ );
308
309 return( $self->_set_get_callback({
310 get => sub
311 {
312 my $self = shift( @_ );
313 return( $self->error( "No event provided to set event handler." ) ) if( !defined( $event ) || !CORE::length( $event ) );
314 my $listeners = $self->getEventListeners( $event ) || return;
315 return( $listeners->first );
316 },
317 set => sub
318 {
319 my $self = shift( @_ );
320 my $arg = shift( @_ );
321 return( $self->error( "No event provided to set event handler." ) ) if( !defined( $event ) || !CORE::length( $event ) );
322 # Argument provided is a code reference
323 if( ref( $arg ) ne 'CODE' )
324 {
325 return( $self->error( "Value provided is not a code reference." ) );
326 }
327 my $eh = $self->addEventListener( $event => $arg ) || return( $self->pass_error );
328 return( $eh );
329 }
330 }, @_ ) );
331 }
332  
333 sub removeEventListener
334 {
335 my $self = shift( @_ );
336 my $type = shift( @_ ) || return( $self->error( "No event listener type was provided." ) );
337 my( $callback, $eh );
338 if( $self->_is_a( $_[0] => 'HTML::Object::EventListener' ) )
339 {
340 $eh = shift( @_ );
341 $callback = $eh->code;
342 }
343 else
344 {
345 $callback = shift( @_ ) || return( $self->error( "No event listener callback was provided." ) );
346 }
347 return( $self->error( "Event listener type \"$type\" contains illegal characters. It should contain only alphanumeric and _ characters." ) ) if( $type !~ /^\w+$/ );
348 if( !ref( $callback ) &&
349 $callback =~ /$PACK_SUB_RE/ )
350 {
351 my( $pack, $sub ) = @+{qw( pack sub )};
352 $pack ||= caller;
353 if( my $ref = $pack->can( $sub ) )
354 {
355 $callback = $ref;
356 }
357 else
358 {
359 return( $self->error( "Unknown subroutine \"$callback\" in package \"$pack\"." ) );
360 }
361 }
362 return( $self->error( "Event listener callback is not a code reference. You can provide either an event listener object (HTML::Object::EventListener, or a reference to a subroutine, or a subroutine name such as MyPackage::my_sub." ) ) if( defined( $callback ) && ref( $callback ) ne 'CODE' );
363 my $opts = $self->_get_args_as_hash( @_ );
364 if( defined( $eh ) && !CORE::exists( $opts->{capture} ) )
365 {
366 $opts->{capture} = $eh->options->{capture};
367 }
368 my @ok_params = qw( capture );
369 my $params = {};
370 @$params{ @ok_params } = CORE::delete( @$opts{ @ok_params } );
371 if( scalar( keys( %$opts ) ) )
372 {
373 warn( "Unrecognised options: '" . join( "', '", sort( keys( %$opts ) ) ) . "'\n" ) if( $self->_is_warnings_enabled( 'HTML::Object' ) );
374 }
375 $params->{capture} //= 0;
376 my $key = join( ';', $type, Scalar::Util::refaddr( $callback ), $params->{capture} );
377 $self->{event_listeners} = {} if( !CORE::exists( $self->{event_listeners} ) );
378 my $repo = $self->{event_listeners};
379 $repo->{ $type } = {} if( !CORE::exists( $repo->{ $type } ) );
380 $eh = CORE::delete( $repo->{ $type }->{ $key } );
381 $repo->{ $type }->{sequence} = $self->new_array if( !CORE::exists( $repo->{ $type }->{sequence} ) );
382 $repo->{ $type }->{sequence}->remove( $key );
383 return( $eh );
384 }
385  
386 sub _signal_remove_listeners
387 {
388 my $sig = shift( @_ ) ||
389 do
390 {
391 warn( "Warning only: no signal was provided in HTML::Object::EventTarget::_signal_remove_listeners\n" ) if( warnings::enabled( 'HTML::Object' ) );
392 return;
393 };
394 my $all = $SIGNALS->{ $sig };
395 if( ref( $all ) eq 'ARRAY' )
396 {
397 $_->remove for( @$all );
398 }
399 }
400  
401 sub _trigger_event_for
402 {
403 my $self = shift( @_ );
404 my $type = shift( @_ );
405 my $class;
406 if( index( $_[0], '::' ) != -1 )
407 {
408 $class = shift( @_ );
409 }
410 my $opts = $self->_get_args_as_hash( @_ );
411 $opts->{class} //= '';
412 $class //= $opts->{class} || 'HTML::Object::Event';
413 $self->_load_class( $class ) || return( $self->pass_error );
414 my $event = $class->new( $type, @_ ) || return( $self->error( $class->error ) );
415 if( CORE::exists( $opts->{callback} ) && ref( $opts->{callback} ) eq 'CODE' )
416 {
417 local $_ = $event;
418 $opts->{callback}->( $event );
419 }
420 $self->dispatchEvent( $event ) || return( $self->pass_error );
421 return( $event );
422 }
423  
424 1;
425 # NOTE: POD
426 __END__
427  
428 =encoding utf-8
429  
430 =head1 NAME
431  
432 HTML::Object::EventTarget - HTML Object Event Target Class
433  
434 =head1 SYNOPSIS
435  
436 use HTML::Object::EventTarget;
437 my $eh = HTML::Object::EventTarget->new(
438
439 ) || die( HTML::Object::EventTarget->error, "\n" );
440  
441 $e->addEventListener( change => sub
442 {
443 my $event = shift( @_ ); # also available as $_
444 # do something with that event (HTML::Object::Event)
445 }, {capture => 0});
446  
447 $e->dispatchEvent( $event );
448  
449 my $event_handlers = $e->getEventListeners( 'click' );
450 say "Found ", $Event_handlers->length, " event handlers";
451  
452 $e->handleEvent( $event );
453  
454 $e->on( click => sub
455 {
456 my $event = shift( @_ );
457 # do something
458 });
459 # or
460 sub onclick : lvalue { return( shift->on( 'click', @_ ) ); }
461 $e->onclick = sub
462 {
463 my $event = shift( @_ );
464 # do something
465 };
466  
467 $e->removeEventListener( $event_listener_object );
468  
469 =head1 VERSION
470  
471 v0.3.0
472  
473 =head1 DESCRIPTION
474  
475 This modules represents an event target and handler. This is implemented by L<HTML::Object::Document> and L<HTML::Object::Element> and its descendants.
476  
477 Of course, being perl, there is only limited support for events.
478  
479 =head1 CONSTRUCTOR
480  
481 =head2 new
482  
483 Creates a new L<HTML::Object::EventTarget> object instance and returns it.
484  
485 =head1 METHODS
486  
487 =head2 addEventListener
488  
489 Provided with a C<type>, a C<callback> and an optional hash or hash reference of C<options> and this will register an event handler (i.e. a callback subroutine) of a specific event type on the L<EventTarget|HTML::Object::Element>.
490  
491 When an event is "fired", the C<callback> is called, and the L<event object|HTML::Object::Event> is passed as it sole argument. Also, C<$_> is set to the current L<element object|HTML::Object::Element> on which the event got triggered.
492  
493 It returns the newly created L<HTML::Object::EventListener> upon success or L<perlfunc/undef> upon error and sets an L<error|Module::Generic/error>
494  
495 Possible options are:
496  
497 =over 4
498  
499 =item I<capture>
500  
501 A boolean value indicating that events of this type will be dispatched to the registered listener before being dispatched to any L<EventTarget|HTML::Object::Element> beneath it in the L<DOM|HTML::Object::Document> tree.
502  
503 Setting the capture flag controls whether an event listener is called in the Capture phase or Bubble phase.
504  
505 For example:
506  
507 <div id="div1">
508 <div id="div2"></div>
509 </div>
510  
511 $div1->addEventListener('click', \&doSomething1, {capture => 1 });
512 $div2->addEventListener('click', \&doSomething2, {capture => 0 });
513  
514 Triggering a C<click> event on C<div2> yields the following[1]:
515  
516 $div2->trigger('click');
517  
518 =over 4
519  
520 =item 1. The C<click> event starts in the capturing phase. The event looks if any ancestor element of element2 has a onclick event handler for the capturing phase.
521  
522 =item 2. The event finds one on C<div1>. C<doSomething1()> is executed.
523  
524 =item 3. The event travels down to the target itself, no more event handlers for the capturing phase are found. The event moves to its bubbling phase and executes C<doSomething2()>, which is registered to C<div2> for the bubbling phase.
525  
526 =item 4. The event travels upwards again and checks if any ancestor element of the target has an event handler for the bubbling phase. This is not the case, so nothing happens.
527  
528 =back
529  
530 The reverse would be:
531  
532 $div1->addEventListener('click', \&doSomething1, {capture => 0 });
533 $div2->addEventListener('click', \&doSomething2, {capture => 0 });
534  
535 =over 4
536  
537 =item 1. The click event starts in the capturing phase. The event looks if any ancestor element of C<div2> has a onclick event handler for the capturing phase and doesn’t find any.
538  
539 =item 2. The event travels down to the target itself. The event moves to its bubbling phase and executes C<doSomething2()>, which is registered to C<div2> for the bubbling phase.
540  
541 =item 3. The event travels upwards again and checks if any ancestor element of the target has an event handler for the bubbling phase.
542  
543 =item 4. The event finds one on C<div1>. Now C<doSomething1()> is executed.
544  
545 =back
546  
547 Setting an event listener like this:
548  
549 $div1->onclick = \&doSomething1;
550  
551 would register it in the bubbling phase, i.e. equivalent to:
552  
553 $div1->addEventListener( click => \&doSomething1, { capture => 0 } );
554  
555 [1] Koch, Peter-Paul "Event order" (Quirkcsmode) L<https://www.quirksmode.org/js/events_order.html>
556  
557 See L<for more information|https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture> and L<this|https://www.quirksmode.org/js/events_order.html>
558  
559 =item I<once>
560  
561 A boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.
562  
563 =item I<passive>
564  
565 This, under perl, does nothing and thus always defaults to false.
566  
567 Under JavaScript, this would be a boolean value that, if true, indicates that the function specified by listener will never call C<preventDefault()>. If a passive listener does call C<preventDefault()>, the user agent will do nothing other than generate a console warning. See Improving scrolling performance with passive listeners to learn more.
568  
569 =item I<post_processing>
570  
571 This is a non-standard addition and is a code reference (i.e. a subroutine reference or an anonymous subroutine) passed that will be called once the event handler has been set. It is passed the newly created L<event listener object|HTML::Object::EventListener>.
572  
573 This is used by L<HTML::Object::DOM::List> for example, to enable event listening on array or scalar only when an event listener is registered. So, upon adding an event listener, this post-processing callback is called and this callback takes the appropriate step to start listening to a specific array or scalar.
574  
575 =item I<signal>
576  
577 A signal, such as C<ALRM>, C<INT>, or C<TERM>. The listener will be removed when the given C<signal> is called.
578  
579 =back
580  
581 Example:
582  
583 <table id="outside">
584 <tr><td id="t1">one</td></tr>
585 <tr><td id="t2">two</td></tr>
586 </table>
587  
588 # Subroutine to change the content of $t2
589 sub modifyText
590 {
591 my $t2 = $doc->getElementById("t2");
592 if( $t2->firstChild->nodeValue eq "three" )
593 {
594 $t2->firstChild->nodeValue = "two";
595 }
596 else
597 {
598 $t2->firstChild->nodeValue = "three";
599 }
600 }
601  
602 # Add event listener to table
603 my $el = $doc->getElementById("outside");
604 $el->addEventListener("click", \&modifyText, { capture => 0 } );
605  
606 Then, do:
607  
608 $el->trigger( 'click' );
609  
610 You can also pass subroutine name that is in your package, or a fully qualified subroutine name. For example:
611  
612 Assuming you are calling from the package My::Module, the following will search for a subroutine C<My::Module::my_callback>
613  
614 $el->addEventListener("click", 'my_callback', { capture => 0 } );
615  
616 Or
617  
618 $el->addEventListener("click", 'My:Module::my_callback', { capture => 0 } );
619  
620 If it does not exists, it will return C<undef> and set an L<error|HTML::Object::Exception>.
621  
622 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener>
623  
624 =head2 dispatchEvent
625  
626 Provided with an L<event|HTML::Object::Event>, and this dispatches the event to this L<EventTarget|HTNL::Object::Element>.
627  
628 It will first call L</composedPath> to get the branch from this current element to the top one, and will start from the top in the C<capture> phase, checking every element from top up to the current one and calls L</handleEvent>, which, in turn, will check if there are any listeners registered in this C<capture> phase, and if there are calls each listener's L<HTML::Object::EventListener/handleEvent>.
629  
630 Then once the C<capture> phase is done, it executes the event listeners on the current L<element|HTML::Object::Element>, if any.
631  
632 Then finally, if the event L<HTML::Object::Event/bubbles> property is true, it calls L</handleEvent> on each of the element starting from the current element's parent to the top one. L</handleEvent>, in turn, will check if there are any event listeners registereed for the element in question for the C<bubbling> phase and call their L<event handler|HTML::Object::EventListener/handleEvent>.
633  
634 If the event property L<HTML::Object::Event/cancelable> is set to true and a handler cancelled it at any point, then this whole process is interrupted.
635  
636 The event L<current element|HTML::Object::Event/currentTarget> is set each time, so you can check that to find out which one has cancelled it.
637  
638 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent>
639  
640 L<See also|https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#bubbling_and_capturing_explained>
641  
642 =head2 event_listeners
643  
644 Sets or gets an hash reference of all the event listeners registered.
645  
646 =head2 getEventListeners
647  
648 Provided with an event type, such as C<click>, and this returns all the L<event listener objects|HTML::Object::EventListener> registere for that event type in their order of registration. It returns an L<array object|Module::Generic::Array>
649  
650 my $listeners = $e->getEventListeners( 'click' );
651 say "Found ", $listeners->length, " event listeners.";
652  
653 =head2 handleEvent
654  
655 Provided with an L<event|HTML::Object::Event> and this will process it via all the registered event listeners in the order they were registered.
656  
657 It returns the current element object upon success, and upon error, it returns C<undef> and sets an L<error|Module::Generic/error>
658  
659 =head2 hasEventListener
660  
661 Provided with an optional event type and this returns the number of event listeners registered for the given type, if provided, or the total number of event listeners registered for all types.
662  
663 =head2 on
664  
665 This is a convenient method to set event listeners. It is to be called by a class, such as:
666  
667 sub onclick : lvalue { return( shift->on( 'click' @_ ) ); }
668  
669 Then, you can set a C<click> event listener for this element:
670  
671 $e->onclick = sub
672 {
673 my $event = shift( @_ ); # Also available with $_
674 # Do some work
675 };
676 # or
677 $e->onclick(sub
678 {
679 my $event = shift( @_ ); # Also available with $_
680 # Do some work
681 });
682  
683 =head2 removeEventListener
684  
685 Provided with a event C<type>, a C<callback> code reference or a subroutine name (possibly including its package like C<MyPackage::my_sub>), or an L<event listener object|HTML::Object::EventListener>, and an hash or hash reference of options and this removes an event listener from the L<EventTarget|HTML::Object::Element>.
686  
687 It returns the L<HTML::Object::EventListener> thus removed upon success or L<perlfunc/undef> upon error and sets an L<error|Module::Generic/error>
688  
689 Possible options, to identify the event handler to remove, are:
690  
691 =over 4
692  
693 =item I<capture>
694  
695 A boolean value indicating that events of this type will be dispatched to the registered listener before being dispatched to any L<EventTarget|HTML::Object::Element> beneath it in the L<DOM|HTML::Object::Document> tree.
696  
697 =back
698  
699 For example:
700  
701 my $eh = $e->addEventListener( click => sub{ # do something }, { capture => 1, once => 1 });
702 $eh->remove;
703 # or
704 $e->removeEventListener( click => $same_code_ref, { capture => 1 });
705  
706 However, if the options provided differ from the ones initially set, it will not uniquely find the event handler. Only the C<capture> option is used to uniquely find the handler. For example:
707  
708 This will fail to remove the handler, because the C<capture> parameter does not have the same value.
709  
710 $e->removeEventListener( click => $same_code, { capture => 0 });
711  
712 This will fail to remove the handler, because the C<callback> value is not the same as the original.
713  
714 $e->removeEventListener( click => $some_other_code_ref, { capture => 1 });
715  
716 See L<for more information|https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener>
717  
718 =head1 AUTHOR
719  
720 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
721  
722 =head1 SEE ALSO
723  
724 L<https://developer.mozilla.org/en-US/docs/Web/API/EventTarget>
725  
726 L<https://developer.mozilla.org/en-US/docs/Web/Events/Event_handlers>
727  
728 L<https://developer.mozilla.org/en-US/docs/Web/API/Event>
729  
730 L<https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events>
731  
732 L<https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers>
733  
734 L<https://domevents.dev/> a very useful interactive playground app that enables learning about the behavior of the DOM Event system through exploration.
735  
736 L<https://www.quirksmode.org/js/events_order.html> discussion of capturing and bubbling - an excellently detailed piece by Peter-Paul Koch.
737  
738 L<https://www.quirksmode.org/js/events_access.html> discussion of the event object - another excellently detailed piece by Peter-Paul Koch.
739  
740 =head1 COPYRIGHT & LICENSE
741  
742 Copyright(c) 2021 DEGUEST Pte. Ltd.
743  
744 All rights reserved
745 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
746  
747 =cut