2

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 ?

invariant
  • 8,758
  • 9
  • 47
  • 61
  • IMHO case 1 should be right. Are you sure this is not just a URL encoding problem? – gzm0 Dec 12 '14 at 09:45
  • no URL encoding issues,:host:maps.googleapis.com :method:GET :path:/maps/api/js?v=3.exp&callback=sample().initialize – invariant Dec 12 '14 at 09:52
  • 1
    Thanks for bringing this up. FYI I filed an issue for this: https://github.com/scala-js/scala-js/issues/1381 – gzm0 Dec 12 '14 at 09:56

2 Answers2

4

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")
}
sjrd
  • 21,805
  • 2
  • 61
  • 91
  • thanks a ton man it solved my other issue too :) ,btw what is that _ ? – invariant Dec 12 '14 at 12:33
  • 1
    It converts the method into a Function. See for example http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala – sjrd Dec 12 '14 at 17:19
1

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")
}
gzm0
  • 14,752
  • 1
  • 36
  • 64