gpt4 book ai didi

angular - 将 noop 分配给变量

转载 作者:搜寻专家 更新时间:2023-10-30 21:23:47 24 4
gpt4 key购买 nike

我正在深入研究 Angular utils源代码,刚好遇到下面一行:

export const NOOP: any = () => {};

嗯,以上是显而易见的。声明一个不做任何操作的变量。现在在同一个库中,我有以下方法:

export function resolveViewDefinition(factory: ViewDefinitionFactory): ViewDefinition {
let value: ViewDefinition = VIEW_DEFINITION_CACHE.get(factory) !;
if (!value) {
value = factory(() => NOOP);
value.factory = factory;
VIEW_DEFINITION_CACHE.set(factory, value);
}
return value;
}

如果不使用该行并将其注释掉并按如下方式设置该 block 会产生什么影响:

  if (!value) {
// value = factory(() => NOOP);
value.factory = factory;
VIEW_DEFINITION_CACHE.set(factory, value);
}

有人可以详细说明这一行吗:

value = factory(() => NOOP);

并对其进行更多照明?我可以看到发生了什么,但我无法理解消除它的影响。

最佳答案

resolveViewDefinition 函数用于获取 View 定义。首先,它会尝试从缓存中获取 value,如果没有缓存值,则它会调用 ViewDefinitionFactory

ViewDefinitionFactory 将函数作为参数。为什么?

/**
* Factory for ViewDefinitions.
* We use a function so we can reexecute it in case an error happens and use the given logger
* function to log the error from the definition of the node, which is shown in all browser
* logs.
*/
export interface ViewDefinitionFactory { (logger: NodeLogger): ViewDefinition; }

当我们刚刚获得 ViewDefinition 时,我们不需要记录错误,所以它是用 NOOP 函数调用的。

但是当我们在模板中执行某些操作时出错时,angular 正在使用 NodeLogger 运行这个工厂以确定哪个节点导致了错误。

让我们看例子 Plunker

@Component({
selector: 'my-app',
template: `<h2 (click)="x()">Hello</h2>`
})
export class App {}

这里是工厂

function View_App_0(l) {
return jit_viewDef1(0,[
(l()(),jit_elementDef2(0,null,null,1,'h2',[],null,[[
null,
'click'
]
],function(v,en,$event) {
var ad = true;
var co = v.component;
if (('click' === en)) {
var pd_0 = (co.x() !== false);
ad = (pd_0 && ad);
}
return ad;
},null,null)),
(l()(),jit_textDef3(null,['Hello']))
]
,null,null);
}

1) 运行应用

function resolveViewDefinition(factory) {
var value = ((VIEW_DEFINITION_CACHE.get(factory))); // we haven't cached it yet
if (!value) { // value is undefined
value = factory(function () { return NOOP; }); //get ViewDefinition but do not log errors
value.factory = factory; // save link to the factory so it can be used later
VIEW_DEFINITION_CACHE.set(factory, value); // store factory
}
return value;
}

2) 点击Hello

((logViewDef.factory))(nodeLogger); // use saved link to call factory with logger

enter image description here

关于angular - 将 noop 分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43698647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com