What's the point of function
function valueFn(value) {return function() {return value;};}
defined in angular.js.
It's used for ex. in
var lowercaseFilter = valueFn(lowercase);
register('lowercase', lowercaseFilter);
What is different if we used lowercase directly as in
register('lowercase', lowercase);
instead of the previous line.
The same way, in the method
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
}
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
why the last line is not
return directive;
but
return valueFn(directive);
Filters (and some other services) are regular functions, but AngularJS heavily relies on Dependency Injections so those filters (functions) are not exposed to the clients as-is (as instantiated objects), but instead are created by factory functions. This is done so AngularJS DI system can inject dependencies to a factory function (and those dependencies are available in a closure later on).
But there are cases where there is nothing to inject and the whole factory function job boils down to returning a pre-instantiated value. This is the case for the lowercaseFilter
(and many other filters). So instead of repeating the same, almost-do-nothing factory function, the valueFn
was created to avoid code repetition. Without it AngularJS code would have to contain:
var lowercaseFilter = function(){
return lowercase;
};
var uppercaseFilter = function(){
return uppercase;
};
...
It is just more concise to write:
var lowercaseFilter = valueFn(lowercase);
var uppercaseFilter = valueFn(uppercase);
...
In short - I suspect that the reason is DRY.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With