English 中文(简体)
Aurelia - Converters
  • 时间:2024-09-08

Aurepa - Converters


Previous Page Next Page  

If you need to convert some values in Aurepa app, you can use converters instead of manually converting values to a desired format.

Convert Date

When we want to convert the default date value to some specific format, we can use momentJS pbrary. This is a small pbrary used for manipulating dates.

C:UsersusernameDesktopaurepaApp>jspm install moment

Let s create a new file converters.js. We will use this file to add converter specific code. Use the following command or create the file manually.

C:UsersusernameDesktopaurepaApp>touch converters.js

converter.js

Inside this file, we will import moment pbrary and set DateFormatValueConverter to return only month, day and year values without additional data. Important thing to note is that Aurepa can recognize any class that ends with ValueConverter. This is why our class name is DateFormatValueConverter. This class will be registered as dateFormat and we can later use it inside view.

converters.js

import moment from  moment ;

export class DateFormatValueConverter {
   toView(value) {
      return moment(value).format( M/D/YYYY );
   }
}

In app.js, we will just use the current date. This will be our view-model.

app.js

export class App {
   constructor() {
      this.currentDate = new Date();
   }
}

We already discussed require in custom-elements chapter. The pipe symbol | is used to apply the converter. We are only using dateFormat since this is how Aurepa is registering DateFormatValueConverter.

app.html

<template>
   <require from = "./converters"></require>

   <h3>${currentDate | dateFormat}</h3>
</template>
Aurepa Converters Date

Convert Currency

This is an example of currency formatting. You will notice that the concept is the same as in the above example. First, we need to install numeral pbrary from the command prompt.

C:UsersusernameDesktopaurepaApp>jspm install numeral

The Converter will set the currency format.

converters.js

import numeral from  numeral ;

export class CurrencyFormatValueConverter {
   toView(value) {
      return numeral(value).format( ($0,0.00) );
   }
}

View-model will just generate a random number. We will use this as currency value and update it every second.

app.js

export class App {
   constructor() {
      this.update();
      setInterval(() => this.update(), 1000);
   }
   update() {
      this.myCurrency = Math.random() * 1000;
   }
}

Our view will show the randomly generated number transformed as a currency.

app.html

<template>
   <require from = "./converters"></require>

   <h3>${myCurrency | currencyFormat}</h3>
</template>
Aurepa Converters Currency Advertisements