我以异步方式加载谷歌地图,
@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")
}
}
案例1 google发送回复 - 400(错误请求)
在案例2中我得到未定义的函数(window.sample.initialize())
我可以定义一个javascript函数,在该函数中我可以调用sample()。initialize(),但是有没有更清洁的方法?
答案 0 :(得分:4)
我会使用Scala.js的动态API在顶层创建JavaScript函数。相比@ gzm0解决方案的优势在于它不那么笨拙,并且需要更少的样板。
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")
}
答案 1 :(得分:1)
这是一个hacky答案,但可能作为一种解决方法。
您可以直接为其提供模块初始化程序,而不是为Google API提供与Scala.js函数相对应的内容:
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")
}