using scala.js method as callback

依然范特西╮ 提交于 2019-12-12 17:41:51

问题


I am loading google map in async way ,

@JSExport("sample")
 object Sample {

  def loadScript = {
    val script = document.createElement("script").asInstanceOf[HTMLScriptElement]
    script.`type` = "text/javascript"
    //case 1
    script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&callback=sample().initialize"
    // case 2
    script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&callback=sample.initialize"
    document.body.appendChild(script)
  }

  @JSExport
  def initialize() :Unit  = {
     println(" map loaded successfully")
  }
}

In case 1 google sending response - 400(bad request)

In case 2 i am getting undefined function ( window.sample.initialize())

i can define a javascript function ,inside that function i can call sample().initialize() , but is there any cleaner way ?


回答1:


I would use Scala.js' dynamic API to create the JavaScript function on the top-level. The advantage over @gzm0's solution is that it's less hacky, and requires less boilerplate.

object Sample {
  def loadScript = {
    val script = document.createElement("script").asInstanceOf[HTMLScriptElement]
    script.`type` = "text/javascript"
    script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&callback=initializeSample"
    document.body.appendChild(script)

    js.Dynamic.global.initializeSample = initialize _
  }

  private def initialize(): Unit =
    println("map loaded successfully")
}



回答2:


This is a hacky answer, but potentially useful as a workaround.

Instead of giving the Google API something corresponding to a Scala.js function, you can give it the module initializer directly:

object Sample {
  def loadScript = {
    val script = document.createElement("script").asInstanceOf[HTMLScriptElement]
    script.`type` = "text/javascript"
    script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&callback=initializeSample"
    document.body.appendChild(script)
  }
}

@JSExport("initializeSample")
object Initializer {
  println(" map loaded successfully")
}


来源:https://stackoverflow.com/questions/27440235/using-scala-js-method-as-callback

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