In Kotlin/JS Multiplatform. trying to call `window...
# getting-started
r
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
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
ahk thanks
d
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
@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
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() {}