SAP Spartacus unit detail 页面显示后自动 focus 设置的原理

网友投稿 625 2022-05-29

这个自动 focus 设置的效果是:我们从 Spartacus Unit list 页面,随便选择一行,进入明细页面之后:

键盘 focus 会自动停留在 detail 页面(下图右边红色矩形框内)第一个 focusable 的元素上:

敲回车试试:

发现 (i) icon 是 unit 明细页面第一个 focusable 的元素。

这个功能的实现原理:在 unit 明细页面,即 unit-details.component.html 里,将 cx-org-card 元素里施加 cxFocus, 自动刷新(refreshFocus)的条件为:当 model 发生变化时。

cxFocus 的实现是很 clean 的,因为自动 focus,从语义上来说,还是应该让 auto focus Directive 来负责实现。

和增强之前的 autofocus 相比,refresh autofocus 的增强主要在于 ngOnChanges hook 的实现:

页面第一个 fosuable 的元素,打印在控制台如下:

window-ref.ts 里的 isBrowser API,封装的是 Angular 标准 API,isPlatformBrowser:

来自 @angular/common:

isBrowser(): boolean { // TODO(#11133): Remove condition when platformId will be always provided return this.platformId ? isPlatformBrowser(this.platformId) : typeof window !== 'undefined'; }

SAP Spartacus unit detail 页面显示后自动 focus 设置的原理

这是 @angular/common 里标准的 api:

https://angular.io/api/common/isPlatformBrowser

然后单击进去之后,看不到具体的实现代码:

@publicApi

export declare function, 其用法解释:

Declare vs. var

var creates a new variable. declare is used to tell TypeScript that the variable has been created elsewhere. If you use declare, nothing is added to the JavaScript that is generated - it is simply a hint to the compiler.

For example, if you use an external script that defines var externalModule, you would use declare var externalModule to hint to the TypeScript compiler that externalModule has already been set up

export declare class Action{ ... }

The class’s real implementation is probably in somewhere else - maybe a .js file.

declare 提示了 Action 的实际实现一定在另一个位置,很可能是某个 .js 文件里。

TypeScript 帮助文档里对 declare 关键字的解释:

The TypeScript declare keyword is used to declare variables that may not have originated from a TypeScript file.

TypeScript 的 declare 关键字,用于声明一个变量,其原始定义可能并不是来自一个 TypeScript 文件。

For example, lets imagine that we have a library called myLibrary that doesn’t have a TypeScript declaration file and have a namespace called myLibrary in the global namespace. If you want to use that library in your TypeScript code, you can use the following code:

declare var myLibrary;

The type that the TypeScript runtime will give to myLibrary variable is the any type. The problem here is that you won’t have Intellisense for that variable in design time but you will be able to use the library in your code.

Another option to have the same behavior without using the declare keyword is just using a variable with the any type:

var myLibrary: any;

Both of the code examples will result in the same JavaScript output but the declare example is more readable and expresses an ambient declaration.

报错:uncaught referenceError: myLibrary is not defined

JavaScript TypeScript web前端

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:【愚公系列】2022年05月 Docker容器 Windows11上Redis的安装
下一篇:Yarn快速系列入门(1) | 基本架构与四大组件
相关文章