Unable to save state in Scala.js

I am trying to write a simple scala.js application. The problem that I currently have is that I cannot understand why I cannot save the data that I receive from the server / user.

To be more specific, here are the code snippets:

<!-- in my html --> <script> example.RoomFrontend().setName("@name"); </script> 

 // in my scala.js src @JSExport object RoomFrontend extends js.JSApp { var username: Option[String] = None @JSExport def setName(name: String): Unit = { username = Some(name) g.console.debug(s"Got user name: $name") } case object TestUserMessage class Render(ctx: dom.CanvasRenderingContext2D) extends Actor { override def receive: Receive = { case TestUserMessage => g.console.debug(s"user name is $username") } } @JSExport def main(): Unit = { //... // renderer is akka actorRef dom.window.setInterval(() => render ! TestUserMessage, 50) } 

So what happens is the following. I successfully enter a username, for example. Blah, I see a nice message in the js console saying "Got username: Blah", but the problem is that every time the renderer is called, it says the username is None.

I assume that this may be caused by the incorrect assignment of a variable in one thread (in the main thread js, I don’t know, this is the correct definition) and reading this variable from the actors thread ... But the same story happens with variables stored in the actor itself .

I think I don’t understand something basic about how scala.js should be used, as I am new to both scala and js. Please can someone explain this strange behavior?

+5
source share

Source: https://habr.com/ru/post/1261853/


All Articles