0

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();
 }
asked Oct 20, 2017 at 12:45

1 Answer 1

2
['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.

answered Oct 20, 2017 at 12:52
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.