问题
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