https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

Ray Rahke

03/15/2024, 4:17 PM
In Kotlin/JS Multiplatform. trying to call
window.onload()
Copy code
window.onload { 
  val canvas = document.getElementById("canvas")
}
getting error
Copy code
Task :compileKotlinJs FAILED
e: Reference has a nullable type '((Event) -> dynamic)?', use explicit '?.invoke()' to make a function-like call instead
e: Type mismatch: inferred type is () -> Unit but Event was expected
What is the syntax for this? I tried
window?.invoke().onload {
and that also got an error
r

Ruckus

03/15/2024, 4:24 PM
I think you need
window.onload?.invoke { ... }
It's
onload
that's nullable, not
window
. https://kotlinlang.org/api/latest/jvm/stdlib/org.w3c.dom/-global-event-handlers/
r

Ray Rahke

03/15/2024, 4:43 PM
ahk thanks
d

Darryl Miles

03/15/2024, 7:20 PM
Hmm I just debugged an issue that needed to check:
Copy code
fun windowOnLoadOrTimeout(function: ((Event?) -> Unit)) {
  if(document.body != null) {  // late we missed "load" event
    window.setTimeout({
      function.invoke(null)
      null  // lambda return is fussy here
    }, 0)
  } else {
    window.addEventListener("load") { event ->  // early need to wait for "load" event
      function.invoke(event)
    }
  }
}

windowOnLoadOrTimeout() {
   // my work here
}
The purpose of this, is that it will always run, even when it missed the window "load" event
r

Ray Rahke

03/16/2024, 9:01 AM
@Ruckus I do that now, but I am getting an error
Type mismatch: inferred type is () -> Unit but Event was expected
Copy code
window.onload.invoke() { 
  ...
}
d

Darryl Miles

03/16/2024, 5:56 PM
if you can debug the reason
setTimeout()
does not work https://pl.kotl.in/Dx8U87Xhk then my original code more or less runs
Your playground code does not use
window.onload.invoke() {}