Tungsten

Binding

Type-safe binding

Let's go
import { StatefulComponent, BindableInput } from 'tungsten'
import { InputKeyboardEvent } from 'tungsten/types/jsx/html.events.js'
type State = {
name: string
age: number | undefined
}
export class Binding extends StatefulComponent<object, State> {
state: State = {
name: '',
age: undefined
}
numberize = (newValue: string, event: InputKeyboardEvent) => { // filter the value to a number or undefined
let n: number | undefined = parseFloat(newValue)
if (isNaN(n)) n = undefined
return n // return the filtered value, which eventually will be set to this.state.age
}
content = () => (
<>
<form>
<BindableInput placeholder="name" bind={[this.state, 'name']} /><br />
<BindableInput placeholder="age" bind={[this.state, 'age']} filter={this.numberize} />
</form>
<div>Name: {this.state.name}</div>
<div>Age: {this.state.age}</div>
</>
)
}
Which gives us:
(note: this is using the vanilla OnChange event, so will require clicking out to update. work on events to come.)

Name:
Age:

Binding isn't limited to state values

'bind='' takes a tuple of [object, string]. The object can be any object. In order to bind to the current component we can provide 'this' - however in this specific case TypeScript requires an additional type annotation

class MyComponent {
val: 'foo'
content = () => <BindableInput bind={[this as MyComponent, 'val']} />
// or
content = () => <BindableInput<ty bind={[this as MyComponent, 'val']} />
}