Whilst working on a cool little Pokemon focused Aurelia app using the Aurelia CLI I encountered a scenario I didn’t immediately know the answer too. I wanted an object which represents my form elements and their values are bound to this object.
I then had a submit button which I wanted to only enable when all fields on the object had been filled out. At first I tried an @observable
and couldn’t get it to work, then I had an epiphany: what about a computed getter?
The only caveat with this approach is you need to know your object properties up front if you want to avoid dirty-checking. I knew what each input would be bound too, so this wasn’t going to be an issue.
Below is literally the code copied and pasted from my app, this is what I am using:
import {computedFrom} from 'aurelia-framework';
export class MyViewModel {
currentSighting = {
name: null,
cp: null,
latitude: null,
longitude: null
};
@computedFrom('currentSighting.name', 'currentSighting.cp', 'currentSighting.latitude', 'currentSighting.longitude')
get sightingIsSubmittable() {
let currentSighting = this.currentSighting;
return (currentSighting.name && currentSighting.cp && currentSighting.latitude && currentSighting.longitude);
}
}
One thing you’ll notice is all of my input elements are bound to properties on the currentSighting
object. This keeps everything nice and neat, it also allows me to post if off to the server in a JSON request.
Look at the submit button at the bottom of the form, notice the line disabled.bind="!sightingIsSubmittable"
we are binding to our getter and because we are using computeds in the form of computedFrom
we eliminate any dirty checking so it’s only updated when something changes on our object.
Lastly we also inverse the boolean value provided from the better as we want false to enable the button and true to disable it. That is really all there is to it. Now you can make things in your app work off of multiple values and their specific values.
Just try to not abuse computeds. In this instance it makes sense to use a getter and computeds, but in some cases, there might be a better way.