Skip to content

Commit

Permalink
refactor(cdk/platform): add utility for backwards-compatible event bi…
Browse files Browse the repository at this point in the history
…ndings

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.
  • Loading branch information
crisbeto committed Dec 17, 2024
1 parent 06785f2 commit dbc2e21
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/cdk/platform/features/backwards-compatibility.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/

import {Renderer2, VERSION, ListenerOptions} from '@angular/core';

// TODO(crisbeto): remove this function when making breaking changes for v20.
/**
* Binds an event listener with specific options in a backwards-compatible way.
* This function is necessary, because `Renderer2.listen` only supports listener options
* after 19.1 and during the v19 period we support any 19.x version.
* @docs-private
*/
export function _bindEventWithOptions(
renderer: Renderer2,
target: EventTarget,
eventName: string,
callback: (event: any) => boolean | void,
options: ListenerOptions,
): () => void {
const major = parseInt(VERSION.major);
const minor = parseInt(VERSION.minor);

// Event options in `listen` are only supported in 19.1 and beyond.
// We also allow 0.0.x, because that indicates a build at HEAD.
if (major > 19 || (major === 19 && minor > 0) || (major === 0 && minor === 0)) {
return renderer.listen(target, eventName, callback, options);
}

target.addEventListener(eventName, callback, options);

return () => {
target.removeEventListener(eventName, callback, options);
};
}
1 change: 1 addition & 0 deletions src/cdk/platform/public-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export * from './features/passive-listeners';
export * from './features/scrolling';
export * from './features/shadow-dom';
export * from './features/test-environment';
export * from './features/backwards-compatibility';
5 changes: 5 additions & 0 deletions tools/public_api_guard/cdk/platform.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@
```ts

import * as i0 from '@angular/core';
import { ListenerOptions } from '@angular/core';
import { Renderer2 } from '@angular/core';

// @public
export function _bindEventWithOptions(renderer: Renderer2, target: EventTarget, eventName: string, callback: (event: any) => boolean | void, options: ListenerOptions): () => void;

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

0 comments on commit dbc2e21

Please sign in to comment.