Skip to content

Commit

Permalink
Provides a short access to document elements by ID via delegated
Browse files Browse the repository at this point in the history
property syntax. Received element is not cached and received
directly from the [Document] by calling [Document.getElementById]
function on every property access. Throws an exception if element
is not found or has different type
To access an element with theId ID use the following property declaration

```
val theID by document.gettingElementById
```

To access an element of specific type, just add it to the property declaration

```
val theID : HTMLImageElement by document.gettingElementById
```

see for more details:
https://youtrack.jetbrains.com/issue/KT-32552
  • Loading branch information
jonnyzzz authored and e5l committed Jan 19, 2024
1 parent 9656670 commit 56694cf
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/jsMain/kotlin/dom-js.kt
Expand Up @@ -153,3 +153,41 @@ private val Node.ownerDocumentExt: Document
this is Document -> this
else -> ownerDocument ?: throw IllegalStateException("Node has no ownerDocument")
}


/**
* Provides a short access to document elements by ID via delegated
* property syntax. Received element is not cached and received
* directly from the [Document] by calling [Document.getElementById]
* function on every property access. Throws an exception if element
* is not found or has different type
*
* To access an element with `theId` ID use the following property declaration
* ```
* val theId by document.gettingElementById
* ```
*
* To access an element of specific type, just add it to the property declaration
* ```
* val theId: HTMLImageElement by document.gettingElementById
* ```
*/
inline val Document.gettingElementById get() = DocumentGettingElementById(this)

/**
* Implementation details of [Document.gettingElementById]
* @see Document.gettingElementById
*/
inline class DocumentGettingElementById(val document: Document) {
/**
* Implementation details of [Document.gettingElementById]. Delegated property
* @see Document.gettingElementById
*/
inline operator fun <reified T : Element> getValue(x: Any?, kProperty: KProperty<*>): T {
val id = kProperty.name
val element = document.getElementById(id) ?: throw NullPointerException("Element $id is not found")
return element as? T ?: throw ClassCastException(
"Element $id has type ${element::class.simpleName} which does not implement ${T::class.simpleName}"
)
}
}

0 comments on commit 56694cf

Please sign in to comment.