Ejemplo: JavaScript desde Kotlin

Página web desarrollada con KotlinJS con ejemplos de:
- Cómo utilizar botones HTML para producir acciones (abrir ventanas de alerta, cambios de estilo, actualizar variables).
- Insertar código JavaScript con la función js("...").
- Declarar de forma segura API de JavaScript con la palabra reservada external.
En el navegador aparece así:

A continuación los archivos principales (main.tk, index.html y estilo.css):
// main.kt import org.w3c.dom.HTMLButtonElement import kotlin.browser.document // función de JavaScript que podemos usar como si fuera de Kotlin external fun alert(msg: String) fun main() { var contador1 = 0 var contador2 = 0 var contador3 = 0 val h1 = document.createElement("h1") h1.textContent = "Desarrollo Web con KotlinJS" val p1 = document.createElement("p") p1.textContent = "Página web desarrollada con Kotlin JS con ejemplos de:" val ul1 = document.createElement("ul") val li1 = document.createElement("li") li1.textContent = "Cómo utilizar botones HTML para producir acciones." val li2 = document.createElement("li") li2.textContent = "Insertar código JavaScript con la función js(\"...\")" val li3 = document.createElement("li") li3.textContent = "Declarar de forma segura API de JavaScript con la palabra reservada \"external\"." ul1.append(li1, li2, li3) // BOTÓN 1 val boton1 = document.createElement("button") as HTMLButtonElement boton1.type = "button" boton1.textContent = "Botón 1" boton1.addEventListener("click", { if (contador1 == 0) { boton1.style.background = "#f44336" js("alert(\"Boton 1 pulsado!\")") } contador1 += 1 boton1.textContent = contador1.toString() }) // BOTÓN 2 val boton2 = document.createElement("button") as HTMLButtonElement boton2.type = "button" boton2.textContent = "Botón 2" boton2.addEventListener("click", { if (contador2 == 0) { boton2.style.background = "#555555" val json = js("{}") json.msg = "Botón 2 pulsado!" js("alert(JSON.stringify(json.msg))") } contador2 += 1 boton2.textContent = contador2.toString() }) // BOTÓN 3 val boton3 = document.createElement("button") as HTMLButtonElement boton3.type = "button" boton3.textContent = "Botón 3" boton3.addEventListener("click", { if (contador3 == 0) { boton3.style.background = "#008CBA" alert("Boton 3 pulsado!") // invoca función de JavaScript } contador3 += 1 boton3.textContent = contador3.toString() }) document.body?.append(h1, p1, ul1, boton1, boton2, boton3) }
<!--index.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>alertJS</title> <link rel="stylesheet" href="estilo.css"> </head> <body> <script src="out/production/alertJS/lib/kotlin.js"></script> <script src="out/production/alertJS/alertJS.js"></script> </body> </html>
/* estilo.css */ button { background-color: #4CAF50; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: block; font-size: 20px; width:200px; }
Comentarios
Publicar un comentario