Aurelia – Refs

Aurelia – Refs ”; Previous Next In this chapter, you will see some simple examples of Aurelia refs. You can use it to create a reference to a particular object. You can create a reference to elements or attributes, as seen in the following table. Reference Table Sr.No Example & Description 1 ref = “myRef” Used for creating a reference to DOM element. 2 attribute-name.ref = “myRef” Used for creating a reference to custom attribute”s view-model. 3 view-model.ref = “myRef Used for creating a reference to custom element”s view-model. 4 view.ref = “myRef” Used for creating a reference to custom elements view instance. 5 rcontroller.ref = “myRef” Used for creating a reference to custom element”s controller instance. In the following example, we will create a reference to the input element. We will use the default class syntax as a view-model. app.js export class App { } We are creating a reference to the input element by adding the ref = “name” attribute. app.html <template> <input type = “text” ref = “name”><br/> <h3>${name.value}</h3> </template> When we run the app, we will see that the text entered into the input field is rendered on the screen. Print Page Previous Next Advertisements ”;

Aurelia – Dialog

Aurelia – Dialog ”; Previous Next Aurelia offers a way to implement dialog (modal) window. In this chapter, we will show you how to use it. Step 1 – Install a Dialog Plugin Dialog plugin can be installed from the command prompt window. C:UsersusernameDesktopaureliaApp>jspm install aurelia-dialog For this plugin to work, we need to use manual bootstrapping. We covered this in the Configuration chapter. Inside main.js file, we need to add the aurelia-dialog plugin. main.js export function configure(aurelia) { aurelia.use .standardConfiguration() .developmentLogging() .plugin(”aurelia-dialog”); aurelia.start().then(() => aurelia.setRoot()); } Step 2 – Create Folders and Files First, we will make a new directory called modal. Let”s place it inside the components folder. Open the command prompt and run the following code. C:UsersusernameDesktopaureliaAppsrccomponents>mkdir modal In this folder, we will create two new files. These files will represent view and view-model for our modal. C:UsersusernameDesktopaureliaAppsrccomponentsmodal>touch my-modal.html C:UsersusernameDesktopaureliaAppsrccomponentsmodal>touch my-modal.js Step 3 – Create a Modal First, let”s add view-model code. We need to import and inject dialog-controller. This controller is used for handling modal specific functionalities. In the following example, we are using it to centralize a modal horizontally. my-modal.js import {inject} from ”aurelia-framework”; import {DialogController} from ”aurelia-dialog”; @inject(DialogController) export class Prompt { constructor(controller) { this.controller = controller; this.answer = null; controller.settings.centerHorizontalOnly = true; } activate(message) { this.message = message; } } The view code will look like this. The buttons when clicked will open or close the modal. my-modal.html <template> <ai-dialog> <ai-dialog-body> <h2>${message}</h2> </ai-dialog-body> <ai-dialog-footer> <button click.trigger = “controller.cancel()”>Cancel</button> <button click.trigger = “controller.ok(message)”>Ok</button> </ai-dialog-footer> </ai-dialog> </template> Step 4 – Trigger a Modal The last step is a function for triggering our modal. We need to import and inject DialogService. This service has method open, where we can pass view-model from my-modal file and model, so we can dynamically bind the data. app.js import {DialogService} from ”aurelia-dialog”; import {inject} from ”aurelia-framework”; import {Prompt} from ”./components/modal/my-modal”; @inject(DialogService) export class App { constructor(dialogService) { this.dialogService = dialogService; } openModal() { this.dialogService.open( {viewModel: Prompt, model: ”Are you sure?” }).then(response => { console.log(response); if (!response.wasCancelled) { console.log(”OK”); } else { console.log(”cancelled”); } console.log(response.output); }); } }; Finally, we will create a button so we can call openModal function. app.html <template> <button click.trigger = “openModal()”>OPEN MODAL</button> <template> If we run the app, we can click the OPEN MODAL button to trigger a new modal window. Print Page Previous Next Advertisements ”;

Aurelia – Configuration

Aurelia – Configuration ”; Previous Next In this chapter, we will show you how to configure Aurelia framework for your needs. Sometimes you will need to set an initial configuration or run some code before the app is rendered to the users. Step 1 – Create main.js Let”s create main.js file inside src folder. Inside this file we will configure Aurelia. You also need to tell Aurelia to load configuration module. You can see the commented part in the following example. index.html <!DOCTYPE html> <html> <head> <title>Aurelia</title> <link rel = “stylesheet” href = “styles/styles.css”> <meta name = “viewport” content = “width=device-width, initial-scale = 1”> </head> <body aurelia-app = “main”> <!–Add “main” value to “aurelia-app” attribute… –> <script src = “jspm_packages/system.js”></script> <script src = “config.js”></script> <script> SystemJS.import(”aurelia-bootstrapper”); </script> </body> </html> Step 2 – Default Configuration The code below shows how to use default configuration. configure function allows to set the configuration manually. We are setting use property to specify what we need. main.js export function configure(aurelia) { aurelia.use .standardConfiguration() .developmentLogging(); aurelia.start().then(() => aurelia.setRoot()); } Step 3 – Advanced Configuration There are lots of configuration options we could use. It is out of the scope of this article to show you all of it so we will explain how the configuration works on the following example. We are basically telling Aurelia to use default data binding language, default resources, development logging, router, history and event aggregator. These are standard set of plugins. export function configure(aurelia) { aurelia.use .defaultBindingLanguage() .defaultResources() .developmentLogging() .router() .history() .eventAggregator(); aurelia.start().then(() => aurelia.setRoot()); } Note − These settings will be explained in detail in the next chapter. Print Page Previous Next Advertisements ”;

Aurelia – Routing

Aurelia – Routing ”; Previous Next Routing is an important part of every application. In this chapter, you will learn how to use the router in Aurelia framework. Step 1 – Create Pages We have already created a components folder in one of the former chapters. If you don”t have it created already, you should place it inside the src folder. C:UsersusernameDesktopaureliaAppsrc>mkdir components Inside this folder, we will create home and about directories. C:UsersusernameDesktopaureliaAppsrccomponents>mkdir home C:UsersusernameDesktopaureliaAppsrccomponents>mkdir about Inside the home folder, we need to create view and view-model files. C:UsersusernameDesktopaureliaAppsrccomponentshome>touch home.js C:UsersusernameDesktopaureliaAppsrccomponentshome>touch home.html We also need view and view-model for about page. C:UsersusernameDesktopaureliaAppsrccomponentsabout>touch about.js C:UsersusernameDesktopaureliaAppsrccomponentsabout>touch about.html Note − You can also create all the above folders manually. Step 2 – Pages Next, we need to add some default code to the files we created. home.html <template> <h1>HOME</h1> </template> home.js export class Home {} about.html <template> <h1>ABOUT</h1> </template> about.js export class About {} Step 3 – Router We will create view-model for router inside app.js file. app.js export class App { configureRouter(config, router) { config.title = ”Aurelia”; config.map([ { route: [””,”home”], name: ”home”, moduleId: ”./components/home/home”, nav: true, title:”Home” }, { route: ”about”, name: ”about”, moduleId: ”./components/about/about”, nav: true, title:”About” } ]); this.router = router; } } Our router view will be placed in app.html. app.html <template> <nav> <ul> <li repeat.for = “row of router.navigation”> <a href.bind = “row.href”>${row.title}</a> </li> </ul> </nav> <router-view></router-view> </template> When we run the app, we will can change the routes by clicking home or about links. Print Page Previous Next Advertisements ”;

Aurelia – Components

Aurelia – Components ”; Previous Next Components are the main building blocks of Aurelia framework. In this chapter, you will learn how to create simple components. Simple Component As already discussed in the previous chapter, each component contains view-model which is written in JavaScript, and view written in HTML. You can see the following view-model definition. It is an ES6 example but you can also use TypeScript. app.js export class MyComponent { header = “This is Header”; content = “This is content”; } We can bind our values to the view as shown in the following example. ${header}syntax will bind the defined header value from MyComponent. The same concept is applied for content. app.html <template> <h1>${header}</h1> <p>${content}</p> </template> The above code will produce the following output. Component Functions If you want to update the header and footer when the user clicks the button, you can use the following example. This time we are defining header and footer inside EC6 class constructor. app.js export class App{ constructor() { this.header = ”This is Header”; this.content = ”This is content”; } updateContent() { this.header = ”This is NEW header…” this.content = ”This is NEW content…”; } } We can add click.delegate() to connect updateContent() function with the button. More on this in one of our subsequent chapters. app.html <template> <h1>${header}</h1> <p>${content}</p> <button click.delegate = “updateContent()”>Update Content</button> </template> When the button is clicked, the header and content will be updated. Print Page Previous Next Advertisements ”;

Aurelia – Data Binding

Aurelia – Data Binding ”; Previous Next Aurelia has its own data-binding system. In this chapter, you will learn how to bind data with Aurelia, and also explain the different binding mechanics. Simple Binding You already saw simple binding in some of our previous chapters. ${…}syntax is used to link veiw-model and view. app.js export class App { constructor() { this.myData = ”Welcome to Aurelia app!”; } } app.html <template> <h3>${myData}</h3> </template> Two-Way Binding The beauty of Aurelia is in its simplicity. The two-way data binding is automatically set, when we bind to input fields app.js export class App { constructor() { this.myData = ”Enter some text!”; } } app.html <template> <input id = “name” type = “text” value.bind = “myData” /> <h3>${myData}</h3> </template> Now, we have our view-model and view linked. Whenever we enter some text inside the input field, the view will be updated. Print Page Previous Next Advertisements ”;

Aurelia – HTTP

Aurelia – HTTP ”; Previous Next In this chapter, you will learn how to work with HTTP requests in Aurelia framework. Step 1 – Create a View Let”s create four buttons that will be used for sending requests to our API. app.html <template> <button click.delegate = “getData()”>GET</button> <button click.delegate = “postData()”>POST</button> <button click.delegate = “updateData()”>PUT</button> <button click.delegate = “deleteData()”>DEL</button> </template> Step 2 – Create a View-model For sending requests to the server, Aurelia recommends fetch client. We are creating functions for every requests we need (GET, POST, PUT and DELETE). import ”fetch”; import {HttpClient, json} from ”aurelia-fetch-client”; let httpClient = new HttpClient(); export class App { getData() { httpClient.fetch(”http://jsonplaceholder.typicode.com/posts/1”) .then(response => response.json()) .then(data => { console.log(data); }); } myPostData = { id: 101 } postData(myPostData) { httpClient.fetch(”http://jsonplaceholder.typicode.com/posts”, { method: “POST”, body: JSON.stringify(myPostData) }) .then(response => response.json()) .then(data => { console.log(data); }); } myUpdateData = { id: 1 } updateData(myUpdateData) { httpClient.fetch(”http://jsonplaceholder.typicode.com/posts/1”, { method: “PUT”, body: JSON.stringify(myUpdateData) }) .then(response => response.json()) .then(data => { console.log(data); }); } deleteData() { httpClient.fetch(”http://jsonplaceholder.typicode.com/posts/1”, { method: “DELETE” }) .then(response => response.json()) .then(data => { console.log(data); }); } } We can run the app and click GET, POST, PUT and DEL buttons, respectively. We can see in the console that every request is successful, and the result is logged. Print Page Previous Next Advertisements ”;

Aurelia – Converters

Aurelia – Converters ”; Previous Next If you need to convert some values in Aurelia 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 library. This is a small library used for manipulating dates. C:UsersusernameDesktopaureliaApp>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:UsersusernameDesktopaureliaApp>touch converters.js converter.js Inside this file, we will import moment library and set DateFormatValueConverter to return only month, day and year values without additional data. Important thing to note is that Aurelia 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 Aurelia is registering DateFormatValueConverter. app.html <template> <require from = “./converters”></require> <h3>${currentDate | dateFormat}</h3> </template> 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 library from the command prompt. C:UsersusernameDesktopaureliaApp>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> Print Page Previous Next Advertisements ”;

Aurelia – Dependency Injections

Aurelia – Dependency Injections ”; Previous Next In this chapter, you will learn how to use Aurelia dependency injection library. First, we need to create new file dependency-test.js inside src folder. In this file, we will create a simple class DependencyTest. This class will be later injected as a dependency. src/dependency-test.js export class DependencyTest { constructor() { this.test = “Test is succesfull!!!”; } } Inject In our app.js file, we are importing inject library and DependencyTest class that we created above. To inject the class we are using @inject() function. Our App class will just log it to the developer console. import {inject} from ”aurelia-framework”; import {DependencyTest} from ”./dependency-test”; @inject(DependencyTest) export class App { constructor(DependencyTest) { console.log(DependencyTest); } } We can check the console to see that the DependencyTest class is injected. There will more examples of Aurelia dependency injection in the next chapters. Print Page Previous Next Advertisements ”;

Aurelia – Binding Behavior

Aurelia – Binding Behavior ”; Previous Next In this chapter, you will learn how to use behaviors. You can think of binding behavior as a filter that can change the binding data and display it in a different format. Throttle This behavior is used to set how often should some binding update take place. We can use throttle to slow down the rate of updating input view-model. Consider the example from the last chapter. The default rate is 200 ms. We can change that to 2 sec by adding & throttle:2000 to our input. app.js export class App { constructor() { this.myData = ”Enter some text!”; } } app.html <template> <input id = “name” type = “text” value.bind = “myData & throttle:2000″ /> <h3>${myData}</h3> </template> Debounce debounce is almost the same as throttle. The difference being, debounce will update the binding after the user has stopped typing. The following example will update the binding if the user stops typing for two seconds. app.js export class App { constructor() { this.myData = ”Enter some text!”; } } app.html <template> <input id = “name” type = “text” value.bind = “myData & debounce:2000″ /> <h3>${myData}</h3> </template> oneTime oneTime is the most efficient behavior performance wise. You should always use it when you know that data should be bound only once. app.js export class App { constructor() { this.myData = ”Enter some text!”; } } app.html <template> <input id = “name” type = “text” value.bind = “myData & oneTime” /> <h3>${myData}</h3> </template> The above example will bind the text to the view. However, if we change the default text, nothing will happen since it is bound only once. Print Page Previous Next Advertisements ”;