Replies: 1 comment 5 replies
-
Heyo, I'll try to give you a head start but I'm too swamped to update the website right now. It would be nice to have such an example eventually, indeed. So – if you have a component that uses derived vars, you want to get a reference to a suitable case class State(name: String, catchphrase: String)
def renderForm(owner: Owner): HtmlElement = {
val rootVar = Var[State](initialState)
val nameVar = rootVar.zoom(_.name)(newName => state.now().copy(name = newName))
val phraseVar = rootVar.zoom(_.catchphrase)(newPhrase => state.now().copy(catchphrase = newPhrase))
div(
collectEvents(onSubmit.preventDefault)(_.flatMap(_ => AjaxEventStream.post(/* use rootVar.now() here if needed*/)) --> responseObserver/* (or Observer.empty)*/,
input(controlled(onInput.mapToValue --> nameVar, value <-- nameVar)),
input(controlled(onInput.mapToValue --> phraseVar, value <-- phraseVar))
)
}
// Usage:
div(onMountInsert(ctx => renderForm(ctx.owner)) I also threw in controlled inputs and Hope that helps. I'm rushing so there may be small typos. Lemme know if something's unclear. For extra clarity, you don't really need derived vars most of the time. For example, here is similar logic without: div(
collectEvents(onSubmit.preventDefault)(_.flatMap(_ => AjaxEventStream.post(/* use rootVar.now() here if needed*/)) --> responseObserver/* (or Observer.empty)*/,
input(controlled(
onInput.mapToValue --> stateVar.updater((state, newName) => state.copy(name = newName)),
value <-- stateVar.signal.map(_.name)
)),
... // similarly for the catchphrase input
) DerivedVar-s are mostly just for convenience, nothing wrong with that but remember there's no magic to them. |
Beta Was this translation helpful? Give feedback.
-
I read this about derived Vars:
And this:
https://github.com/raquo/Airstream#derived-vars
It will be great to see a full working example in https://laminar.dev/examples. Is it possible to have a functioning example of the derived Vars functionality for/in a form (as stated above) please?
Points of confusion for me:
Beta Was this translation helpful? Give feedback.
All reactions