Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala.js: Using addEventListener to add events to objects

In JavaScript, the addEventListener() method is used like this:

object.addEventListener("click", myScript);

In Scala.js: I have a canvas, and I want to listen to clicks only on the canvas, not the entire document. In the Scala.js.dom library, addEventListener is defined as:

 def addEventListener(`type`: String, listener: js.Function1[Event, _], useCapture: Boolean = ???): Unit = ???

I'm not sure what "useCapture" refers to. But I tried:

dom.document.getElementById("canvas").addEventListener("click", {
(e:dom.MouseEvent) => { /*do something*/ }
}, false)

And the error message I got:

found   : org.scalajs.dom.MouseEvent => Unit
required: scala.scalajs.js.Function1[org.scalajs.dom.Event, _]

Can someone explain what "useCapture" refers to, and how to correctly use addEventListener in Scala.js?

like image 306
user3025403 Avatar asked Jul 24 '14 14:07

user3025403


People also ask

How do you add an event listener to an object?

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.

Can you add event listener to div?

To add a click event listener on div tag using JavaScript, we can call the addEventListener method on the selected div.

Can I add event listener to all elements of class?

To add an event listener to all elements with class: Use the document. querySelectorAll() method to select the elements by class. Use the forEach() method to iterate over the collection of elements.

Which method is used to add an event listener?

Note: The addEventListener() method is the recommended way to register an event listener.


1 Answers

The error message you get is a perfectly normal type error: addEventListener expects a js.Function1[dom.Event, _], but you're giving it a js.Function1[dom.MouseEvent, _]. Since the first argument is in contravariant position, this does not typecheck.

There are two solutions: either you make your function take a dom.Event, that you then cast to dom.MouseEvent, like this:

canvas.addEventListener("click", { (e0: dom.Event) =>
  val e = e0.asInstanceOf[dom.MouseEvent]
  ...
}, false)

or you use onclick which is more precisely typed:

canvas.onclick = { (e: dom.MouseEvent) =>
  ...
}
like image 103
sjrd Avatar answered Oct 05 '22 08:10

sjrd