I was digging into the Angular utils source code and just encountered the following line:
export const NOOP: any = () => {};
Well, above is kind of obvious. Declare a variable which doesnt do any operation. Now Inside the same library I have the following method:
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;
}
What would be the effect of just not having that line in place and commenting it out and have the block as follows:
if (!value) {
// value = factory(() => NOOP);
value.factory = factory;
VIEW_DEFINITION_CACHE.set(factory, value);
}
Could someone elaborate more on this line:
value = factory(() => NOOP);
and shed more lights on it? I can see what is happening but I cant understand the effects of eliminating it.
resolveViewDefinition function is used for getting view definition. First it tries to get value from the cache and if there is no cached value then it is calling ViewDefinitionFactory.
ViewDefinitionFactory takes function as parameter. Why?
/**
* 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; }
We do not need to log errors when we are just getting ViewDefinition so it is called with NOOP function.
But when we get error during executing some action within template angular is running this factory with NodeLoggerto determine which node caused the error.
Let's see example Plunker
@Component({
selector: 'my-app',
template: `<h2 (click)="x()">Hello</h2>`
})
export class App {}
Here is factory
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) Running application
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) After clicking on Hello
((logViewDef.factory))(nodeLogger); // use saved link to call factory with logger