user3871
user3871

Reputation: 12718

Pass in parameters for javascript click event

I want to run a function within an object on click. In the object's init method, I bind a click to "runBFS".

I use bind(this) to traversal so I can pass in the context of the object and not lose it to the window.

var api = {},
api.init = function () {
  document.getElementById("runBFS").addEventListener(
    "click",
    this.traversal.bind(this),
    false
  );
}

I need to pass in a boolean value on click (traverseNodesBool) but don't know how to pass it in when using bind()

api.traversal = function (e, traverseNodesBool) {

How do I do this?

Upvotes: 1

Views: 167

Answers (2)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

.bind(thisArg[, arg1[, arg2[, ...]]]) ,so first parameter is context and rest follows your other parameters, so it would be:

this.traversal.bind(this, yourParamHere);

Upvotes: 1

Mukesh Soni
Mukesh Soni

Reputation: 6668

Pass it as the second param to bind.

document.getElementById("runBFS").addEventListener("click", this.traversal.bind(this, traverseNodesBool);

api.traversal = function(yourBool, e) {}

Upvotes: 1

Related Questions