I believe, there is a shorter way (one line) to write this using lodash:
_.forEach(eventListeners, function(callback) {
callback(event);
})
... but can't find yet
Lodash is a popular javascript based library which provides 200+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on.
The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])
get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.
last() method is used to get the last element of the array i.e. (n-1)th element. Parameters: This function accepts single parameter i.e. the array. Return Value: It returns the last element of the array.
Lodash provides a utility function called _.over
that returns a function that you can then call to pass some arguments to all of the functions you provided to _.over
Official documentation for _.over
var funs = [
function(e) { console.log(e) },
function(e) { console.log(e*2) },
function(e) { console.log(e*3) }
];
_.over(funs)(10);
This will call all of the functions in the funs
array with 10
as their argument, so in this case you should see in your console:
10
20
30
In your case specifically:
_.over(eventListeners)(event);
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