hey guys this might have been answered before but ...
# javascript
n
hey guys this might have been answered before but since there’s not that much history i apologize in advance is there a kotlin equivalent to a top-level anonymous function:
Copy code
(function() {
  // My code here
})();
k
No. Why do you need this?
n
to execute the code when the script is read to attach listeners to the dom elements
k
Why can't you pass lambdas to event listeners?
n
i can but this anonymous function also contains other functions so that they don’t pollute the top namespace
k
Functions in Kotlin do not pollute top namespace 🙂
n
what do you mean? can i just declare them in my file? and because of the package declaration, they will land in a dedicated namespace?
k
You can declare a private top-level function and it won't pollute anything
Lambdas don't pollute anything as well
Local functions don't pollute any namespaces
n
ok, thanks back to the event listener stuff how (where) should i attach them?
myElem.addEventListener("click") { println(clicked) }
n
sorry, that was not my question in which scope should i attach them? because i have to declare a function to do that but who will call it? that was the goal of the anonymous function automatic script execution
k
I don't understand your question
n
ok, here’s a sample html file:
Copy code
<html>
<body>
<span id="foo"></span>
<script>
(function() {
  document.getElementById("foo").innerHTML = "Foo";
})();
</script>
</body>
when i load this HTML, there’s no calling of anything the anonymous function is executed and the document updated accordingly
k
Ah, I see. There's no way to do that. Currently, Kotlin/JS will define variable with the name of the module
n
so i’ve to call it explicitly?
k
Yes
n
ok, thanks
k
Or, if you have a main function and add
-main call
option, it will be called automatically as module gets loaded
Another option is to compile to CommonJS and try to set up WebPack to generate non-polluting JS
n
wow, i’ll stick to the simple way i’m not a javascript developer just hacked something and want to re-write in kotlin thanks for your time
l
Did you tried using document events?
Copy code
<html>
<body>
<span id="foo"></span>
<script>
document.onload = () => {
  document.getElementById("foo").innerHTML = "Foo";
}
</script>
</body>
n
no 🙂 but my html sits in my main project and my kotlinjs in another