web analytics
Paste your Google Webmaster Tools verification code here

Working with Bindings in Aurelia

article2_fig1

 

Introduction

In the last tutorial we talked about how to set up a project in Aurelia through the provided skeletons and also how to architect routing in your Aurelia project.  In this article, we’ll introduce how to do binding in Aurelia.  By using a form as an example, we’ll show how easy it is to bind the form to our Aurelia ViewModel and extract the data from it. We’ll also talk about using the Aurelia fetch service to bind all the states for our State dropdown.

Simple html Binding

Most binding can be accomplished in Aurelia by using the ${myClassProperty}  syntax.  For example, in order to bind the picture above, I can set up an html image as follows:

<img width=100 src=”${imageUrl}” id=”profileImage”></img>

 

In my view model, I can just set the image property on the corresponding view model

export class Application{constructor(stateService)  {this.imageUrl =  ‘http://www.linkedin/myprofilepicture’;

 

this.address = ”;

this.city = ”;

this.selectedState = null;

this.zip = ”;

}

}

 

If the address I assigned imageUrl is valid, then my template will display the image scaled to 100 width.

 

Simple Input Binding

I really like the way you do binding in Aurelia.  All you need to remember is to stick the suffix .bind onto the attribute you want to bind to.  For example to bind the value of the input box for the city field above to the city property in the viewmodel, you simply do the following.

<input type=”text” id=”city” value.bind=”city”>

 

Our corresponding view model contains the city property and looks like this

import {computedFrom} from ‘aurelia-framework’;export class Application{constructor()  {

    this.city = ”;

}

}

 

By default this is a two-way binding since it’s an input field.  Two-way binding means, that if you type the city Austin in the city field, it will set the value of the city property in the viewmodel to ‘Austin’.  And on the flip-side, if you set the value of the city property in the view model to ‘Houston’, Houston will appear in the city field in the browser.  This is what it means to have two-way binding, the field is bound both ways from view to viewmodel.

Binding to a CheckBox

Another two-way binding component is the checkbox.  Just as we bound the input dialog through its value, a checkbox is bound through the checked property by adding .bind to it.

<div ><span>I am over the age of 18.</span><input type=”checkbox” id=”consent” checked.bind=”isLegal”></div>

 

Checking or unchecking the checkbox will change the Boolean state of the isLegal property in the viewmodel:

import {computedFrom} from ‘aurelia-framework’;export class Application{constructor()  {

    this.isLegal = false;

}

}

 

 

Binding a selection drop down

To bind options, such as the state dropdown shown above, you can use the model attribute which allows you to bind an object to each option.

  <select value.bind=”selectedState” ><option model.bind=”null”>Choose…</option><option style=”width:50px” repeat.for=”state of states” model.bind=”state”>${state.name}</option></select>

 

Our corresponding view model looks like this:

import {computedFrom} from ‘aurelia-framework’;export class Application{constructor()  {

this.city = ”;

this.selectedState = null;

this.states = getStates();

}

}

 

In the markup above, the model.bind binds one-to-one with a state.  All the states are iterated over (through the repeat.for) and each state in the view is bound to the model corresponding to the state object in the list of states in the viewmodel.  The state is displayed through the name property coming back in the state model using ${state.name}

When we select a state, the dropdown will be bound to the selectedState in the viewmodel through the value.bind.  We’ll see how we obtain the list of states later in this article.

Binding a button click to an Action

Binding button clicks to actions is as simple as binding input boxes.  You simply add .delegate onto the event in order to call a method in your view model:

<button type=”button” click.delegate=”submitForm()”>Apply</button>

 

Above when we click the Apply button in the form it calls submitForm in the viewmodel.  In our example below, we simply spit the bound results to the console in the browser, but we could have just as well submitted the results to a service which persisted the data in a database.

import {computedFrom} from ‘aurelia-framework’;export class Application{constructor()  {

this.city = ”;

this.selectedState = null;

this.states = getStates();

}

 

submitForm(){

console.log(`fullname is ${this.fullname}, state is ${this.selectedState.name}, and zip is ${this.zip}.`);

 

}

 

}

 

 

Getting the State Data for the State DropDown

So you want to know how we can retrieve all the state data for the dropdown dialog?  Turns out, it’s easier than you might think.  There is a REST service that returns all the state information for a particular country.  We simply used Aurelia’s http fetch capability to retrieve the data from this service.  The code for the Aurelia service utilizing the REST service is shown below:

import ‘fetch’;import {HttpClient} from ‘aurelia-fetch-client’;export class StateService {getStates() {

let httpClient = new HttpClient();

 

return httpClient.fetch(‘http://services.groupkt.com/state/get/USA/all’)

.then(response => response.json())

.then(data => {

this.states  =  data.RestResponse.result;

});

}

}

 

The Aurelia HttpClient calls fetch on the REST API at http://services.groupkt.com.  The fetch method returns a promise, which we can use to resolve when we receive the response later.  Promises are cool objects that help us wrap asynchronous behavior into one object.  The promise is resolved once the http response comes back and it’s resolved inside of the .then method of the promise itself.  Since we are returning the full promise in the getStates method of our StateService, we will need to resolve the promise in our Application view model to pull the data saved on the states property of our StateService.

 

import {StateService} from ‘../services/state-service’;@inject(StateService)

 

export class Application{

 

constructor(stateService)  {

this.stateService = stateService;

 

    this.stateService.getStates().then(

      data => {

        this.states = this.stateService.states;

    });

}

 

Conclusion

Handling data binding with Aurelia is exceedingly straightforward and you will be binding your data properly in no time.  You may notice in the listing above, we did some magic to get the stateService instance passed to our constructor.  In our next article we’ll discuss dependency injection in Aurelia and how we go about injecting services[MD1]  into our viewmodel, specifically to persist data.


 [MD1]od


Mike is a software engineer with a love for tinkering with smart phone devices. He spends a lot of time moving pictures to his SD card, because the Android keeps running out of memory. In his spare time, he travels to different parts of the world and takes one of his Android devices with him.

Share

Share This Post

Recent Articles

Leave a Reply

*

© 2016 ToDroid. All rights reserved.
Disclaimer: The content on this site is copyrighted. Do not copy the content. The content on this site must not be reproduced anywhere else.