Reputation: 916
I have a component with two buttons, save and cancel. Inside this component there is a slot. And inside this slot, I put my form with some bindable fields.
my-app.ts
<section-component>
<form>
<input name="testA" value.bind="varA">
<input name="testB" value.bind="varB">
</form>
</section-component>
Imagine that user change fields values but decide to cancel this edition. When he clicks in Cancel, it should call a function to "erase" new data (not saved) and the data in these fields come back to the his original form (old data).
I was thinking that the best option would be make a refresh of this specific component, binding old data again. But I'm not sure that this is the best option or how to do it. Someone can help giving a insight or a solution, please?
Upvotes: 3
Views: 338
Reputation: 4946
There might be several strategies to tackle this problem. What matters here most is, what you want to do after the user clicks "Cancel". For example, if you want to make a redirect then you don't have to do anything for restoring the values. This makes sense from a usability perspective.
However, if the context of the view demands the same view with old values, the straightforward way is to restore a snapshot. Let's say the model you are binding with the view has following schema.
model: { varA: anyType, varB: anyType }
And you are binding it as follows.
<input name="testA" value.bind="model.varA">
<input name="testB" value.bind="model.varB">
Then you can simply save a snapshot of the original model and restore it later as follows.
//save the snapshot
this.snapshot = JSON.parse(JSON.stringify(this.model))
//....
// restore the snapshot when user clicks cancel
this.model = this.snapshot
And the rest should be taken care of by the bindings, already in place. Note that the assumption here is that the model
is just a raw container of data, and offers no functionality (not an instance of any user-defined class that offers additional methods etc.; in that case you need to restore the prototype as well).
In case you want "undo" action rather than "cancel", and if you are using aurelia-store
already, then check here.
Hope it helps.
Upvotes: 2