ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Ajax 호출하기
    web/laminar 2022. 1. 8. 23:05

    코드

    import com.raquo.airstream.web.AjaxEventStream
    import com.raquo.laminar.api.L._
    import org.scalajs.dom
    
    object Main {
      def main(args: Array[String]): Unit = {
        val urlVar       = Var("https://api.zippopotam.us/us/90210")
        val otherButton  = button("other url", onClick.mapTo("https://jsonplaceholder.typicode.com/todos/2") --> urlVar)
        val submitButton = button("submit")
    
        // EventStream.fromFuture(Ajax.get(url = urlVar.now()).map(_.responseText))
        val responseOnClick: EventStream[String] =
          submitButton.events(onClick).flatMap(_ => AjaxEventStream.get(url = urlVar.now()).map(_.responseText))
    
        val content = div(
          input(
            typ := "text",
            width := "300px",
            controlled(value <-- urlVar.signal, onInput.mapToValue --> urlVar)
          ),
          otherButton,
          submitButton,
          br(),
          label("response: "),
          child.text <-- responseOnClick
        )
    
        val containerNode = dom.document.getElementById("main_content")
        render(containerNode, content)
      }
    }

     

    혹은 EventBus 를 사용해 아래처럼 구현할 수도 있다.

    import com.raquo.laminar.api.L._
    import org.scalajs.dom
    import org.scalajs.dom.ext.Ajax
    
    import scala.concurrent.ExecutionContext.Implicits.global
    
    object Main {
      def main(args: Array[String]): Unit = {
        val urlVar      = Var("https://api.zippopotam.us/us/90210")
        val otherButton = button("other url", onClick.mapTo("https://jsonplaceholder.typicode.com/todos/2") --> urlVar)
    
    
    //    val (responseOnClick, callback)  = EventStream.withCallback[String]
    //    val submitButton                      =
    //      button("submit", onClick --> (_ => Ajax.get(url = urlVar.now()).map(x => callback(x.responseText))))
    
        val responseOnClick: EventBus[String] = new EventBus
        val submitButton                      =
          button("submit", onClick --> (_ => Ajax.get(url = urlVar.now()).map(x => responseOnClick.emit(x.responseText))))
    
        val content = div(
          input(
            typ := "text",
            width := "300px",
            controlled(value <-- urlVar.signal, onInput.mapToValue --> urlVar)
          ),
          otherButton,
          submitButton,
          br(),
          label("response: "),
          child.text <-- responseOnClick
        )
    
        val containerNode = dom.document.getElementById("main_content")
        render(containerNode, content)
      }
    }

     

    결과

    설명

    laminext fetch 를 활용하는 것도 좋을 것 같다.

    'web > laminar' 카테고리의 다른 글

    Component - Checkbox  (0) 2022.01.09
    Component - Dropdown  (0) 2022.01.09
    Var.updater() 사용하기  (0) 2022.01.08
    javascript(plotly.js) 호출하기  (0) 2022.01.08
    Laminar 소개  (0) 2022.01.05

    댓글

Designed by Tistory.