Ben
Ben

Reputation: 353

Javascript object. How to create a button that calls a function inside same object

I have a JS object called 'avatar' with a create function that generates a button on an HTML page and sets a few attributes.

I want to set an onmouseover on the button that calls a function within the avatar object so I have written:

this.create = function(){
    this.button = document.createElement("BUTTON");
    this.text = document.createTextNode(this.name);
    this.button.appendChild(this.text);
    document.body.appendChild(this.button);
    this.button.style.background=this.color;
    this.button.addEventListener("mouseover", this.randomMove());
}

However, the function randomMove is executed immediately and does not wait for the button to be mouseovered. Subsequent mouseovers do nothing.

Upvotes: 1

Views: 228

Answers (3)

Ben
Ben

Reputation: 353

Thanks for your help.

As it turns out what I was really looking for was bind.

this.button.addEventListener("mouseover",this.randomMove.bind(this));

This bound the function call to a method belonging to this object. So even though the HTML generated lives outside the scope of the object instance, the function call remembers which instance it should make the call to.

Thanks again

Ben

Upvotes: 0

Shomz
Shomz

Reputation: 37701

You need to pass it a function body, not what the function returns. In your case, the code evaluates this.randomMove() and assigns the returned result to the mouseover event handler. This is how it should look:

this.button.addEventListener("mouseover", this.randomMove);

See this simple example to easily understand what's going on: http://jsfiddle.net/f8tm4jq3/

Upvotes: 1

bobjones
bobjones

Reputation: 503

Like Andy mentioned, you need to pass the function reference (without parenthesis), not function expression (with parenthesis) as the argument to addEventListener.

Upvotes: 0

Related Questions