KDBindings
KDBindings copied to clipboard
Handle Cascading Bindings
Often, I have to deal with a Property<T*> p where T itself contains properties. Given the property p is using a pointer type, I cannot binding directly to p->someProperty given p might be null. Therefore I would need to have a way to create a binding to a function that can itself return binding to another property or a value depending on whether p() is null.
// GIVEN
struct TypeA {
Property<float> value { 1.0f };
};
struct TypeB {
Property<TypeA *> a { nullptr };
};
// WHEN
TypeB myB;
// In a perfect world I would do Property<float> v = makeBinding(myB.a->value);
// Except I can't if myB.a is null
// THEN
CHECk(myB.a() == nullptr);
// WHEN
Property<float> v = makeBinding([] (TypeA *a) {
if (a)
return makeBinding(a->value);
return 0.0f; // or a binding to a default property
}, myB.a);
// THEN -> Returns default value
CHECK(v() == 0.0f);
// WHEN
TypeA myA;
myB.a = &myA;
// THEN -> Return bound value
CHECK(v() == 1.0f);