Creating custom DOM events with scalajs

為{幸葍}努か 提交于 2019-12-02 02:46:20

问题


I can't find a way to create custom events with scala-js. For instance, with js you can create a custom event like the following (taken from here):

  var event = new CustomEvent('build', { 'detail': elem.dataset.time });

However, there is no constructor for CustomerEvent or Event in scala-js that accept arguments. Also, subclassing either such as:

  class DrawEvent extends Event {
    override def `type` = "draw"
  }

leads to

Uncaught TypeError: undefined is not a function

when trying to construct via new DrawEvent()

Any ideas?


回答1:


To instantiate javascript classes in ScalaJs you have to use js.Dynamic.newInstance:

This should work for your use case:

val event = js.Dynamic.newInstance(js.Dynamic.global.CustomEvent)("build", js.Dynamic.literal(detail = elem.dataset.time)).asInstanceOf[js.dom.CustomEvent]

There is more info available at the remarks portion (all the way at the bottom) of: http://www.scala-js.org/doc/calling-javascript.html

Here is the same solution using some imports to make it shorter

import js.Dynamic.{ global => g, newInstance => jsnew, literal => lit }
val event = jsnew(g.CustomEvent)("build", lit(detail = elem.dataset.time)).asInstanceOf[js.dom.CustomEvent]



回答2:


If you want to stay in the typed DOM (assuming you are talking about the scala-js-dom library), you can do:

new CustomEvent().initCustomEvent('build', false, false, elem.dataset.time)

The constructor you are using is actually only specified in DOM 4 (see MDN).



来源:https://stackoverflow.com/questions/24619945/creating-custom-dom-events-with-scalajs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!