Trying to figure out how the below code works and what it does... can someone explain it to me?
From what I can tell is that ['handleEvent'] is just going to instantly execute and run the forEach loop once...
I'm assuming that it's something to do with an event listener which then executes the method referenced by as string? The code below is within the constructor method and isn't assigned to a variable or anything...
class plugin{
constructor(sidebar, options = {}){
this.options = plugin.extend(DEFAULTS, options);
// Bind event handlers for referencability.
['handleEvent'].forEach( (method) => {
this[method] = this[method].bind(this);
});
// Initialize sticky sidebar for first time.
this.initialize();
}
1 Answer 1
['handleEvent'].forEach( (method) => {
this[method] = this[method].bind(this);
});
is exactly equivalent to
this['handleEvent'] = this['handleEvent'].bind(this);
Presumably the author wrote it this way to make it easier to add new strings in the future. The array doesn't need to be assigned if it is a 'use once and throw-away' object.