Build Powerful Web Apps with Simple Javascript

0
36
Build Powerful Web Apps with Simple Javascript


Have you been searching for a Javascript framework that gets your work done as efficiently and simply as possible? Do you consider performance, speed, and simplicity while choosing the best framework for your project? If so, hang on for the next ten minutes. In this tutorial, you’ll learn how to build a powerful web application with simple JavaScript using Aurelia.

What is Aurelia?

Aurelia is a set of contemporary JavaScript modules that, when combined, offer a powerful platform for developing browser, desktop, and mobile apps, all of which are open source and based on open web standards. The end goal of Aurelia is to create rich, engaging experiences for your customers, meeting or exceeding what is found in modern native applications.

Why use Aurelia?

Aurelia has many benefits that make it a good tool for your web application. They include:

  • It offers an all-in-one solution: Aurelia provides core capabilities like dependency injection, templating, routing, and pub/sub, so you don’t have to piece together a bunch of libraries to build an application. On top of this rich core, Aurelia also provides several additional plugins for internationalization, validation, modal dialogs, and UI virtualization.
  • It offers great rendering speed and memory efficiency: Aurelia implements batch rendering and observable object pooling, which allows it to render faster than any other framework. Aurelia also utilizes less memory and causes less GC churn than other frameworks.
  • Aurelia ensures that there are no breaking changes in its core API due to upgrades.
  • Aurelia allows you to build your app components with plain, vanilla JavaScript or Typescript.
  • Because of its simplicity and consistent design structure, Aurelia is much easier to learn than other frameworks.
  • Because of the extensible design of Aurelia and its strict adherence to web standards, it’s easy to integrate Aurelia with any 3rd party library or framework, like jQuery, React, Polymer, Bootstrap, MaterializeCSS, etc.
  • It is sourced under the MIT license and doesn’t add or remove special clauses or conditions to the license.

And lots more that you can find out from the documentation.

What are we building?

To demonstrate how powerful and simple Aurelia is, we’d build a Todo application, as shown in the screenshot below:

Basic

Getting started with Aurelia

Before starting this tutorial, I assume you have Nodejs version 10 or above installed. With Nodejs installed, install the Aurelia CLI with the command below:

1npm install -g aurelia-cli

Grab a cup of coffee while npm installs the required packages to run your application. Once the installation is completed, it’s time to create a project.

Create an Aurelia Project

With the Aurelia CLI installed on your computer, create a new Aurelia project with the command below:

The above command will prompt you to enter your project name and the default setup for your project. For demonstration sake, we’d name the project “task-todos”, select “Default TypeScript App”, and choose “npm” as the package manager to install all the dependencies to run the application. Once the installation is completed, change the directory to the project folder, and start the application with the commands below:

1cd task-todo

2au run --open

The application will be open on your browser once it starts running on port 8080. If you have had issues running the application on the default port, you can modify the default port in aurelia_project/aurelia.json.

Creating the App Class

At this point, the application is up and running. Aurelia has a similar folder structure to React.js. All the projects are located in the src folder. There should be an HTML file for every component you create in Aurelia to render the contents. Now update the code in the app.ts a file with the code snippet below:

1export class Todo {

2 public todos;

3 public name = "";

4

5 constructor() {}

6}

Then update the app.html file with the code below to render the Todo view.

1<template>

2 <div class="container">

3 <div class="main">

4 <div class="todo-header">

5 <h4>My Task</h4>

6 </div>

7 <div class="todo-body">

8 <form>

9 <input type="text" class="task">

10 <button type="submit" class="add">Add</button>

11 </form>

12 <ul>

13 <div class="todo-list">

14 <input type="checkbox"/>

15 <li>Write some code</li>

16 <span>X</span>

17 </div>

18 </ul>

19 </div>

20 </div>

21 </div>

22</template>

In the above code snippet, we created the Todo view. We created an input form to add a new todo, and an unordered list to display the todos. At this point, our app has no styling; let’s go ahead and add some styling to make things look better.

Adding Custom Styles

With the app view created, create a style.css file in the src folder and add the styles below:

1* {

2 padding: 0px;

3 margin: 0px;

4 box-sizing: border-box;

5 font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;

6}

7

8body {

9 background-color: rgb(204, 211, 218);

10 width: 100%;

11}

12

13.container {

14 display: flex;

15 justify-content: center;

16 flex-direction: column;

17 align-items: center;

18}

19

20.header {

21 display: flex;

22 justify-content: space-between;

23 width: 500px;

24 margin: 10px;

25 align-items: center;

26}

27

28.header h4 {

29 color: rgb(175, 98, 158);

30}

31

32.add {

33 background-color: rgb(12, 127, 204);

34 border: 0px;

35 padding: 6px;

36 color: white

37}

38

39.main {

40 width: 500px;

41 margin-top: 12px;

42}

43

44.main .todo-header {

45 background-color: rgb(175, 98, 158);

46 color: white;

47 text-align: center;

48 padding: 10px;

49 margin-bottom: 10px;

50 font-size: 20px;

51}

52

53.main .todo-body {

54 background-color: white;

55 padding: 10px;

56}

57

58.main .todo-body .task {

59 padding: 10px;

60 border: 0px;

61 outline: none;

62 border-bottom: 1px solid rgb(175, 98, 158);

63 width: 90%;

64 margin-bottom: 20px;

65}

66

67.main .todo-body ul {

68 list-style: none;

69}

70

71.main .todo-body ul div {

72 display: flex;

73 align-items: center;

74 margin-bottom: 10px;

75 width: 100%;

76}

77

78.main .todo-body ul div input {

79 margin-right: 5px;

80}

81

82.main .todo-body ul div span {

83 color: rgb(204, 77, 77);

84 position: relative;

85 left: 20em;

86 display: none;

87 cursor: pointer;

88}

89

90.main .todo-body ul div:hover span {

91 display: flex;

92}

93

94.completed {

95 text-decoration: line-through;

96}

Now let’s import the style.css file in our app view using the require element, which allows you to import resources into your views. Add the code snippet below to the app.html file.

1<template>

2 <require from="./style.css"></require>

3 ...

The application should look more appealing now. Feel free to modify the styles!

Open Source Session Replay

OpenReplay is an open-source alternative to FullStory and LogRocket. It gives you full observability by replaying everything your users do on your app and showing how your stack behaves for every issue. OpenReplay is self-hosted for full control over your data.

replayer.png

Happy debugging, for modern frontend teams – start monitoring your web app for free.

Loading custom data

At this point, we only have one todo, which we hardcoded by ourselves. Let’s load some todos from an external file. In a full-stack application, this data is supposed to be from a backend API. For demonstration’s sake, we’d create dummy data for that. Create an **api/index.js** folder in the src directory and add the code snippet below:

1interface Todo {

2 id: number;

3 name: string;

4 completed: boolean;

5 dateCreated: number;

6}

7

8export class API {

9 id = 0;

10

11 Todos: Todo[] = [

12 {

13 id: ++this.id,

14 name: "Sleep",

15 completed: false,

16 dateCreated: Date.now(),

17 },

18 {

19 id: ++this.id,

20 name: "Excercise",

21 completed: false,

22 dateCreated: Date.now(),

23 },

24 {

25 id: ++this.id,

26 name: "Eat",

27 completed: false,

28 dateCreated: Date.now(),

29 },

30 {

31 id: ++this.id,

32 name: "Code",

33 completed: false,

34 dateCreated: Date.now(),

35 },

36 {

37 id: ++this.id,

38 name: "Sleep",

39 completed: false,

40 dateCreated: Date.now(),

41 },

42 ];

43

44 getTodos() {

45 return new Promise((resolve) => {

46 const results = this.Todos.map((todo) => {

47 return {

48 id: todo.id,

49 name: todo.name,

50 completed: todo.completed,

51 dateCreated: todo.dateCreated,

52 };

53 });

54 resolve(results);

55 });

56 }

57}

In the above code snippet, we created an API class with some todos and a method to return the todos.
Now import and use the API class in your app.ts file. Before that, you need to import the API class with the inject function from “aurelia-framework”. Aurelia has its dependency injection container, which it uses to instantiate classes in your app.

1import { inject } from "aurelia-framework";

2import { API } from "./api";

Now let’s create an interface for our Todo class and bind the API class to it. Update your app.ts file with the code snippet below:

1import { inject } from "aurelia-framework";

2import { API } from "./api";

3

4interface todoInterface {

5 id: number;

6 name: string;

7 completed: boolean;

8 dateCreated: number;

9}

10

11@inject(API)

12export class Todo {

13 public todos;

14 public name = "";

15

16 constructor(private api: API) {}

17}

Creating the App Methods

Now let’s add methods to our Todo class to read, create updates and delete todos. To read the todos in our API, we’ll call the getTodos method inside a created hook, which gets called after both the view-model and the view are created. Then, store the todos in the todos variable in our Todo class. Add the code snippet below in your app.ts file.

1created() {

2 this.api.getTodos().then((todos) => (this.todos = todos));

3}

Now add the following method to create, update and delete a todo.

1

2 async createTodo() {

3 if (this.name) {

4 const todoObj: todoInterface = {

5 id: this.todos.length + 1,

6 name: this.name,

7 completed: false,

8 dateCreated: Date.now(),

9 };

10 this.todos.push(todoObj);

11 this.name = "";

12 }

13 }

14

15 updateTodo(id: number) {

16 this.todos.map((todo) => {

17 if (todo.id == id) {

18 todo.completed = !todo.completed;

19 }

20 });

21 }

22

23 deleteTodo(id) {

24 this.todos.splice(

25 this.todos.findIndex((todo) => todo.id == id),

26 1

27 );

28 }

29

30

Finally, update the app.html file with the code snippet below:

1<template>

2 <require from="./style.css"></require>

3 <div class="container">

4 <div class="main">

5 <div class="todo-header">

6 <h4>My Task</h4>

7 </div>

8 <div class="todo-body">

9 <form submit.trigger="createTodo()">

10 <input type="text" class="task" value.bind="name">

11 <button type="submit" disabled.bind="!name" class="add">Add</button>

12 </form>

13 <ul repeat.for="todo of todos">

14 <div class="todo-list" click.trigger="updateTodo(todo.id)">

15 <input type="checkbox" checked.bind="todo.completed"/>

16 <li class="text-decoration: ${todo.completed ? 'completed' : 'none'}">${todo.name}</li>

17 <span click.trigger="deleteTodo(todo.id)">X</span>

18 </div>

19 </ul>

20 </div>

21 </div>

22 </div>

23</template>

In the above code snippet, we added the following events and bindings to our app view:

  • submit.trigger=“createTodo():” This event gets called when the user clicks the submit button.
  • click.trigger=“updateTodo(todo.id)” and click.trigger=“deleteTodo(todo.id)“: The events get called when the user click the delete carret or clicks on the todo, which will either delete or update the compeleted properties of that todo.
  • value.bind=“name”: This allows us to bind the users’ input to the input field. Learn more about Aurelia binding here.
  • disabled.bind=“!name”: This binding enables us to disable the submit button when the input field is empty.
  • checked.bind=“todo.completed”: This binding checks the input box when a todo is completed.

Test the application

At this point, your Aurelia application is completed. Go ahead and test it out by adding, updating, and deleting a todo.

Conclusion

Wow, you made it here at last. In this tutorial, you’ve learned how to build a powerful web component using Aurelia. You’ve had an overview of what Aurelia is and why you should use it. Then you created a todo application for the demonstration. If you have any questions, please reach out on Twitter.





Source link

Leave a reply

Please enter your comment!
Please enter your name here