Skip to content

Commit dbc2e21

Browse files
committed
refactor(cdk/platform): add utility for backwards-compatible event bindings
Adds a utility that we can use to bind events with options in a backwards-compatible way. It will be removed once we get to v20.
1 parent 06785f2 commit dbc2e21

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import {Renderer2, VERSION, ListenerOptions} from '@angular/core';
10+
11+
// TODO(crisbeto): remove this function when making breaking changes for v20.
12+
/**
13+
* Binds an event listener with specific options in a backwards-compatible way.
14+
* This function is necessary, because `Renderer2.listen` only supports listener options
15+
* after 19.1 and during the v19 period we support any 19.x version.
16+
* @docs-private
17+
*/
18+
export function _bindEventWithOptions(
19+
renderer: Renderer2,
20+
target: EventTarget,
21+
eventName: string,
22+
callback: (event: any) => boolean | void,
23+
options: ListenerOptions,
24+
): () => void {
25+
const major = parseInt(VERSION.major);
26+
const minor = parseInt(VERSION.minor);
27+
28+
// Event options in `listen` are only supported in 19.1 and beyond.
29+
// We also allow 0.0.x, because that indicates a build at HEAD.
30+
if (major > 19 || (major === 19 && minor > 0) || (major === 0 && minor === 0)) {
31+
return renderer.listen(target, eventName, callback, options);
32+
}
33+
34+
target.addEventListener(eventName, callback, options);
35+
36+
return () => {
37+
target.removeEventListener(eventName, callback, options);
38+
};
39+
}

src/cdk/platform/public-api.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@ export * from './features/passive-listeners';
1313
export * from './features/scrolling';
1414
export * from './features/shadow-dom';
1515
export * from './features/test-environment';
16+
export * from './features/backwards-compatibility';

tools/public_api_guard/cdk/platform.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@
55
```ts
66

77
import * as i0 from '@angular/core';
8+
import { ListenerOptions } from '@angular/core';
9+
import { Renderer2 } from '@angular/core';
10+
11+
// @public
12+
export function _bindEventWithOptions(renderer: Renderer2, target: EventTarget, eventName: string, callback: (event: any) => boolean | void, options: ListenerOptions): () => void;
813

914
// @public
1015
export function _getEventTarget<T extends EventTarget>(event: Event): T | null;

0 commit comments

Comments
 (0)