【问题标题】:My input html forms misses focus/empties when a Var changes当 Var 更改时,我的输入 html 表单丢失焦点/空
【发布时间】:2017-08-12 01:04:50
【问题描述】:

我想从 Binding.scala 创建一些 UI。 UI 包含一个文本框。当用户在文本框中输入文本时,我想根据用户输入更改背景颜色。

import com.thoughtworks.binding._, Binding._
import org.scalajs.dom._

@dom def render = {
  val color = Var("")
  val styleText: String = s"background-color: ${color.bind}"

  // <div> and <input> will be recreated once data changes.
  <div style={styleText}>
    <input id="myInput" type="text" oninput={ _: Any => color := myInput.value }/>
  </div>
}

dom.render(document.body, render)

该示例在ScalaFiddle 上运行。

但是,当我在文本框中输入内容时,文本框会失去焦点并且仍然保持空白。

我该如何解决?

【问题讨论】:

    标签: dom data-binding scala.js lost-focus binding.scala


    【解决方案1】:

    也许您在同一个@dom 方法中定义了&lt;input ...&gt;.bind,而&lt;input ...&gt;.bind 之后。尝试将.bind&lt;input ...&gt; 重构为单独的@dom 方法,或者让.bind 表达式嵌套在另一个DOM 中。


    例如,如果myInput写在.bind之前,则不会重新创建:

    import com.thoughtworks.binding._, Binding._
    import org.scalajs.dom._
    
    @dom def render = {
      val color = Var("")
      val myInput = <input id="myInput" type="text" oninput={ _: Any => color := myInput.value }/>
      val styleText: String = s"background-color: ${color.bind}"
    
      // <div> will be recreated once data changes.
      // <input> will not be recreated.
      <div style={styleText}>
        {myInput}
      </div>
    }
    
    dom.render(document.body, render)
    

    上面的例子在ScalaFiddle上运行。


    如果.bind 表达式嵌入在 XHTML 文字中,它不会影响其子代:

    import com.thoughtworks.binding._, Binding._
    import org.scalajs.dom._
    
    @dom def render = {
      val color = Var("")
    
      // <div> and <input> will not be recreated when data changes.
      // Only the class attribute will be changed.
      <div style={s"background-color: ${color.bind}"}>
        <input id="myInput" type="text" oninput={ _: Any => color := myInput.value }/>
      </div>
    }
    
    dom.render(document.body, render)
    

    上面的例子在ScalaFiddle上运行。


    另一种方法是将.bind 表达式包装在@dom val 中:

    import com.thoughtworks.binding._, Binding._
    import org.scalajs.dom._
    
    @dom def render = {
      val color = Var("")
      @dom val styleText: Binding[String] = s"background-color: ${color.bind}"
    
      // <div> and <input> will not be recreated when data changes.
      // Only the class attribute will be changed.
      <div style={styleText.bind}>
        <input id="myInput" type="text" oninput={ _: Any => color := myInput.value }/>
      </div>
    }
    
    dom.render(document.body, render)
    

    上面的例子在ScalaFiddle上运行。

    【讨论】:

    猜你喜欢
    • 2018-07-12
    • 2018-03-03
    • 1970-01-01
    • 2014-07-14
    • 2019-10-21
    • 2015-09-21
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    相关资源
    最近更新 更多