Bind binds the given value to the given [Value] such that the values of the two will be linked and updated appropriately after [events.Change] events and during [WidgetBase.UpdateWidget]. It returns the widget to enable method chaining. It also accepts an optional [reflect.StructTag], which is used
(value any, vw T, tags ...string)
| 46 | // It also accepts an optional [reflect.StructTag], which is used to set properties |
| 47 | // of certain value widgets. |
| 48 | func Bind[T Value](value any, vw T, tags ...string) T { //yaegi:add |
| 49 | // TODO: make tags be reflect.StructTag once yaegi is fixed to work with that |
| 50 | wb := vw.AsWidget() |
| 51 | alreadyBound := wb.ValueUpdate != nil |
| 52 | wb.ValueUpdate = func() { |
| 53 | if vws, ok := any(vw).(ValueSetter); ok { |
| 54 | ErrorSnackbar(vw, vws.SetWidgetValue(value)) |
| 55 | } else { |
| 56 | ErrorSnackbar(vw, reflectx.SetRobust(vw.WidgetValue(), value)) |
| 57 | } |
| 58 | } |
| 59 | wb.ValueOnChange = func() { |
| 60 | ErrorSnackbar(vw, reflectx.SetRobust(value, vw.WidgetValue())) |
| 61 | } |
| 62 | if alreadyBound { |
| 63 | ResetWidgetValue(vw) |
| 64 | } |
| 65 | wb.ValueTitle = labels.FriendlyTypeName(reflectx.NonPointerType(reflect.TypeOf(value))) |
| 66 | if ob, ok := any(vw).(OnBinder); ok { |
| 67 | tag := reflect.StructTag("") |
| 68 | if len(tags) > 0 { |
| 69 | tag = reflect.StructTag(tags[0]) |
| 70 | } |
| 71 | ob.OnBind(value, tag) |
| 72 | } |
| 73 | wb.ValueUpdate() // we update it with the initial value immediately |
| 74 | return vw |
| 75 | } |
| 76 | |
| 77 | // ResetWidgetValue resets the [Value] if it was already bound to another value previously. |
| 78 | // We first need to reset the widget value to zero to avoid any issues with the pointer |