也许您在同一个@dom 方法中定义了<input ...> 和.bind,而<input ...> 在.bind 之后。尝试将.bind 和<input ...> 重构为单独的@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上运行。