I wonder why there is not builder constructor for dynamic objects in kotlin-js standard library.
I am playing around with calling javascript library from kotlin code and configuration object looks like that:
json(
"width" to "100%",
"height" to "400px",
"controller" to json(
"loadData" to { filter: dynamic ->
println("loading items with filter: $filter")
data.toTypedArray()
},
"insertItem" to { item: dynamic ->
println("inserting item: $item")
val point = DataPoint(
phi1 = item.phi1,
psio = item.psio,
psie = item.psie
)
_data.add(point)
point
},
"updateItem" to { item: dynamic ->
println("updating item: $item")
item as Any
},
"deleteItem" to { item: dynamic ->
println("removing item: $item")
_data.remove(item as DataPoint)
item as Any
}
)
}
It works fine but looks not good at all. but introducing a very simple function:
fun js(builder: dynamic.() -> Unit): dynamic {
val obj = Any().asDynamic()
builder.invoke(obj)
return obj
}
into much cleaner code:
js {
width = "100%"
height = "400px"
controller = js {
loadData = { filter: dynamic ->
println("loading items with filter: $filter")
data.toTypedArray()
}
insertItem = { item: dynamic ->
println("inserting item: $item")
val point = DataPoint(
phi1 = item.phi1,
psio = item.psio,
psie = item.psie
)
_data.add(point)
point
}
updateItem = { item: dynamic ->
println("updating item: $item")
item
}
deleteItem = { item: dynamic ->
println("removing item: $item")
_data.remove(item as DataPoint)
item
}
}
}
Is there a reason why it is not done this way? Or maybe it is already defined somewhere and I just have not found it?