为变量分配noop

时间:2017-04-29 17:37:46

标签: angular typescript typescript2.0

我正在深入研究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;
}

如果没有这条线并对其进行评论并将其块设置如下,会产生什么影响:

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

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

value = factory(() => NOOP);

并更多地点亮它?我可以看到发生了什么,但我无法理解消除它的影响。

1 个答案:

答案 0 :(得分:4)

resolveViewDefinition函数用于获取视图定义。首先,它尝试从缓存中获取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函数调用它。

但是当我们在模板中执行某些操作时遇到错误时,使用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