1

What is the meaning of addHorizonLoadEvent(function() {...}) in the following snippet?

addHorizonLoadEvent(function() {
    show_hide_datepickers();
});
corazza
  • 31,222
  • 37
  • 115
  • 186
geeks
  • 2,025
  • 6
  • 31
  • 49
  • 1
    It is an anonymous function – OptimusCrime Jul 20 '15 at 08:53
  • 1
    [addHorizonLoadEvent](https://github.com/openstack/horizon/blob/65db6d33aa40a202cd16ad60e08273f715a67745/horizon/templates/horizon/client_side/_script_loader.html): _" Added so that we can append Horizon scoped JS events to the DOM load events without running in to the "horizon" name-space not currently being defined since we load the scripts at the bottom of the page."_ – Andreas Jul 20 '15 at 08:54
  • 2
    possible duplicate of [Explain JavaScript's encapsulated anonymous function syntax](http://stackoverflow.com/questions/1634268/explain-javascripts-encapsulated-anonymous-function-syntax) – user2864740 Jul 20 '15 at 08:59
  • http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?rq=1 – user2864740 Jul 20 '15 at 09:03
  • @NeelabhSingh Could you accept an answer, please? – corazza Jul 22 '15 at 14:43

3 Answers3

5

addHorizonLoadEvent is a higher-order function -- that means it doesn't expect a non-function value (like a number, or a string) as it's argument, but another function. So the first argument is a new function, that will be called by the original function at some point (often at the end as a callback).

function() {...} is an anonymous function -- a way to express a function without binding it to a name.

corazza
  • 31,222
  • 37
  • 115
  • 186
1

In fact you give a function as parameter of addHorizonLoadEvent.

You could do that :

var fooBar = function() {
   //alert("Alert2");
   show_hide_datepickers();
});

addHorizonLoadEvent(fooBar);

And the function parameter you give to addHorizonLoadEvent will be used only one time, no need to give it a name, so it is an anonymous function, directly declared in ().

nlassaux
  • 2,335
  • 2
  • 21
  • 35
1

This pattern is a called anonymous function.

function_name(function() { 
    // Code
});

Is the same as writing

function my_function() {
    // Code
}
function_name(my_function);

Meaning that my_function is passed as an argument to the function function_name.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96