CompositeBinding双向绑定:同一SimpleForm新建编辑对象的双向绑定实现咨询
Great question! The short answer is yes, you absolutely can set up two-way binding here—the issue with your current code is that it’s a one-way conditional expression: it only pulls values from either som>Id or newModel>Id to display in the input, but your framework has no way of knowing where to push updates when the user types. Let’s walk through a few solid solutions:
1. Use an Intermediate State Variable (Cleanest Approach)
Create a single local state variable to act as the "source of truth" for the input, then sync it with your target models based on the isNew flag:
- Initialize the state: When your component loads, set the variable based on whether you’re in new or edit mode:
// Pseudocode for component initialization let formId = !${/isNew} ? ${som>Id} : ${newModel>Id}; - Bind the input to the intermediate variable: This gives you native two-way binding for the input itself:
<Input value="{= formId}" /> - Sync back to your models: When the user saves/submits the form (or whenever you need to persist changes), update the correct model based on
isNew:if (!${/isNew}) { ${som>Id} = formId; } else { ${newModel>Id} = formId; } - Handle
isNewchanges: If the mode can switch mid-component lifecycle (e.g., from edit to new), add a listener to updateformIdwheneverisNewchanges:// Pseudocode for reacting to isNew changes watch(${/isNew}, (newIsNew) => { formId = newIsNew ? ${newModel>Id} : ${som>Id}; });
2. Manual Two-Way Binding via onChange
If you prefer not to use an intermediate variable, you can manually implement the reverse update logic in the input’s onChange handler:
<Input value="{= !${/isNew} ? ${som>Id} : ${newModel>Id}" onChange="{(event) => { const updatedValue = event.target.value; // Push the new value to the correct model if (!${/isNew}) { ${som>Id} = updatedValue; } else { ${newModel>Id} = updatedValue; } }}" />
This replicates two-way binding by explicitly updating the target model every time the input value changes.
3. Dynamic Binding Path (Framework-Dependent)
Some frameworks let you dynamically switch the binding path based on a condition. If yours supports this, you can use a computed expression to target the correct model directly for two-way binding:
<!-- Syntax varies by framework—example pseudocode --> <Input value="{= ${!${/isNew} ? 'som>Id' : 'newModel>Id'} }" />
Note: This depends on your framework’s ability to parse dynamic binding paths at runtime. Check your framework docs to see if this is supported.
Key Notes
- Ensure
${/isNew}is a reactive/observable value so the binding updates automatically when the mode switches. - Whichever approach you choose, test edge cases (like switching modes mid-edit) to make sure data stays consistent.
内容的提问来源于stack exchange,提问作者Flo

