Janie
Janie

Reputation: 646

Event is losing when passing parameters to bind()

I'm trying to bind a callback with event but it lost the event when passing the callback. Here is my codes

HTML:

<button id="click">click</button>

JavaScript:

<script>
    class T {
        handler (e, c) {
            console.log(e)
            console.log(typeof c)
            //c(e)
        }

        run () {
            document.getElementById('click').addEventListener('click', this.handler.bind(this, e => {
                console.log(e)
            }))
        }
    }

    (new T).run()
</script>

When I don't pass the callback the event is logged correctly. Codes here

handler (e) {
   console.log(e)
}

run () {
  document.getElementById('click').addEventListener('click', this.handler.bind(this))
}

Now, how can I pass both event and callback to the handler?

Upvotes: 0

Views: 133

Answers (3)

Pankaj Shukla
Pankaj Shukla

Reputation: 2672

You are getting both the callbacks and event. Modify your code like this and you would see that your callback is called. Your first argument is the callback and second is event.

class T {
        listener (e, c) {
            console.log(e);
            console.log(typeof c);
			e();
            //c(e)
        }

        run () {
            document.getElementById('click').addEventListener('click', this.listener.bind(this, e => {
                console.log('I am called');
            }));
        }
    }

    (new T).run();
<button id="click">click</button>

You will see that callback is called and you see 'I am called'. You should however modify the arguments to name them properly. e, the first param doesn't look like a callback and similarly the second param.

Upvotes: 1

jank
jank

Reputation: 860

function handleClickListener(e, callback) {
  console.log('clicked');
  callback(e);
}

function startListener() {
  document.addEventListener('click', e => handleClickListener(e, (e) => console.log(e)));
}

startListener()

Upvotes: 0

Elias
Elias

Reputation: 4122

I would not bind a function and instead do: [..].addEventListener('click', event => this.listener(event, cb))

See why here: Event Listener in Class Context

Upvotes: 0

Related Questions