Creating custom DOM events with scalajs

前端 未结 2 1403
天涯浪人
天涯浪人 2021-01-22 18:23

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          


        
相关标签:
2条回答
  • 2021-01-22 18:44

    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]
    
    0 讨论(0)
  • 2021-01-22 18:44

    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).

    0 讨论(0)
提交回复
热议问题