What's the best way to make an external binding fo...
# javascript
s
What's the best way to make an external binding for a javascript function that takes a js object as a parameter?
Copy code
Platform.select({
  ios: 'iOS',
  android: 'android',
});
a
I think this should work:
Copy code
kotlin
external interface Config {
    val ios: String
    val android: String
}

external object Platform {
    fun select(config: Config)
}
s
How would you recommend calling the select function?
would I then have to create a kotlin implementation of the Config interface and use that?
Is there no way to easily create a dynamic js object?
I found a better way. Should I be doing this, or is there maybe a better way?:
Copy code
fun <T> Platform.select(ios: T, android: T): T {
  @Suppress("UnsafeCastFromDynamic")
  return select(
      jsObject {
        this.ios = ios
        this.android = android
      }
  )
}

inline fun jsObject(init: dynamic.() -> Unit): dynamic {
  val o = jsObject()
  init(o)
  return o
}

fun jsObject(): dynamic = js("{}")
g
there is also standard `json`:
Copy code
json(
    "ios" to "something", 
    "android" to "something"
)
s
Could I incorporate parameters into that by name?
g
Not sure what do you mean. You can just keep all the params as map (so can change them, add, remove) and then convert map to json using this function just before passing to js code
a
@spierce7 Congrats with making it work. 😃 Yes, you could create an anonymous instance of
Config
and use that. Yes, that would be suboptimal performace-wise In my opinion a simpler way to remedy that would be creating a factory function, which looks like a constructor:
Copy code
fun Config(ios: String, android: String): Config {
    val res = js("{}")
    res.ios = ios
    res.android = android
    return res.unsafeCast<Config>()
}
Calling select looks like this:
Platform.select(Config("ios", "android"))
. This way you won't need a special extension function for every usage of
Config
.