binpress

Learn AbsurdJS: Building a To-Do List App

You’ve probably heard about the ToDoMVC project. It’s takes a basic to-do list application and replicates it with different frameworks. It’s interesting to see how the same problem is solved by different programmers following different concepts. In this article, we’ll make the standard ToDoMVC application with AbsurdJS, a framework that can convert JavaScript (or JSON) to valid CSS and HTML.

AbsurdJS introduction

AbsurdJS started as a CSS preprocessor, which I distributed as Node.js module. In the process of development it transformed into an HTML preprocessor, and very soon after that it was translated for client side usage. At the moment, it’s roughly 80 KB and can convert JavaScript to CSS and HTML.

The client-side version of AbsurdJS — the one that we’re going to use — covers most of a modern frameworks’ capabilities.

  • Component driven
  • Data binding
  • DOM event handling
  • Dependency injection
  • Template engine
  • Built-in router, AJAX wrapper and DOM helper

However, there is something fundamentally different. The framework can convert JavaScript (or JSON) to valid CSS and HTML. Moreover, when we talk about client-side development, we know that we have to write a lot of CSS and HTML. AbsurdJS gives us the power to write in one language – JavaScript. As we will see in the next sections, we will write everything into JavaScript files. Including the CSS styling.

Project setup

The idea of the ToDoMVC project is that every developer starts with same assets. There’s a template and CSS that we have to use. Our project looks like that:

  1. /absurd
  2. /bower_components
  3.     /todomvc-common
  4. /css
  5.     /app.css
  6. /js
  7.     /model
  8.         /model.js
  9.     /views
  10.         /footer.js
  11.         /header.js
  12.         /main.js
  13.     /app.js
  14. /index.html

The absurd directory contains the absurd.min.js (the library itself) and absurd.organic.min.js, which is a collection of CSS mixins. bower_components folder delivers the default look of the application, the basic CSS styling and images that we mentioned above. The app.css file is where we have to add our custom stylesheets. However, we’re going to use JavaScript for the styling, so in the end the file will be almost empty. The js directory contains our logic.

Development with AbsurdJS is close to Backbone development. Thew View plays the role of the controller. We could make another comparison and say that the framework is similar to Facebook’s React. Everything in AbsurdJS is a component.

Here’s the skeleton of our ToDoMVC app:

  1. <!doctype html>
  2. <html lang="en">
  3.     <head>
  4.         <meta charset="utf-8">
  5.         <title>Template • TodoMVC</title>
  6.         <link rel="stylesheet" href="bower_components/todomvc-common/base.css">
  7.         <link rel="stylesheet" href="css/app.css">
  8.     </head>
  9.     <body>
  10.         <script src="absurd/absurd.organic.min.js"></script>
  11.         <script src="absurd/absurd.min.js"></script>
  12.         <script src="js/app.js"></script>
  13.         <script src="js/model/model.js"></script>
  14.         <script src="js/views/header.js"></script>
  15.         <script src="js/views/main.js"></script>
  16.         <script src="js/views/footer.js"></script>
  17.         <script type="text/javascript">if(!NREUMQ.f){NREUMQ.f=function(){NREUMQ.push(["load",new Date().getTime()]);var e=document.createElement("script");e.type="text/javascript";e.src=(("http:"===document.location.protocol)?"http:":"https:")+"//"+"js-agent.newrelic.com/nr-100.js";document.body.appendChild(e);if(NREUMQ.a)NREUMQ.a();};NREUMQ.a=window.onload;window.onload=NREUMQ.f;};NREUMQ.push(["nrfj","beacon-1.newrelic.com","7d8608a34f","3053298","YFdVYEsAVxdYAhAICVkddldNCFYKFhQXBBQYRkJAVhNQBVUSSwQCXkY=",0,91,new Date().getTime(),"","","","",""]);</script>
  18.     </body>
  19. </html>

We included the CSS styles at the top of the page and the scripts at the bottom.

The header

Our HTML starts with a simple header

  1. <header id="header">
  2.     <h1>todos</h1>
  3.     <input id="new-todo" placeholder="What needs to be done?" autofocus>
  4. </header>
setup-footer

The main area

Just after that we have an area that contains the list with the ToDo items.

  1. <section id="main">
  2.     <input id="toggle-all" type="checkbox">
  3.     <label for="toggle-all">Mark all as complete</label>
  4.     <ul id="todo-list">
  5.         <li>
  6.             <div class="view">
  7.                 <input class="toggle" type="checkbox">
  8.                 <label>Task 1</label>
  9.                 <button class="destroy"></button>
  10.             </div>
  11.             <input class="edit" value="">
  12.         </li>
  13.     </ul>
  14. </section>
setup-header

Footer

In the end, we have a footer. It contains some informational spots and filtering navigation.

  1. <footer id="footer">
  2.     <span id="todo-count">
  3.         <strong>0</strong> item 0 left
  4.     </span>
  5.     <ul id="filters">
  6.         <li><a class="" href="#/">All</a></li>
  7.         <li><a class="" href="#/active">Active</a></li>
  8.         <li><a class="" href="#/completed">Completed</a></li>
  9.     </ul>
  10.     <button id="clear-completed">Clear completed (0)</button>
  11. </footer>
setup-main

The CSS styles

There is only one thing that we’ll do in css/app.css. We’ll hide the footer and the main section. It’s not because we can’t do that in JavaScript. It’s because the JavaScript needs time to boot, and the user may see something before that. So:

  1. #footer, #main {
  2.     display: none;
  3. }

Defining a namespace

It’s good practice to work in a private namespace. If we expose everything to the global scope, we may have collisions with other frameworks or libraries. Here’s how our js/app.js starts:

  1. (function( window ) {
  2.     'use strict';
  3.  
  4.     window.absurd = Absurd(); // AbsurdJS API
  5.     window.App = {}; // namespace
  6.  
  7. })( window );

use strict puts your code in strict mode. John Resig posted a nice article revealing more information about that. In general:

  • It catches some common coding bloopers, throwing exceptions.
  • It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object).
  • It disables features that are confusing or poorly thought out.

It’s a good way to write a little bit better code.

When we include AbsurdJS in the page, we have access to a global Absurd function that returns the library’s API. We store that in window.absurd. All the other code that we write should be under window.App namespace.

AbsurdJS components and dependency injection

Before we proceed with the actual implementation, we should say a few words about AbsurdJS components and the integrated dependency injection. The typical component looks like this:

  1. var ComponentClass = absurd.component('Name', {
  2.     constructor: function() {
  3.         // ...
  4.     },
  5.     doSomething: function() {
  6.         this.dispatch('some-event', { data: 42 });
  7.     }
  8. });
  9.  
  10. var component = ComponentClass();
  11. component.on('some-event', function(event) {
  12.     console.log('The answer is ' + event.data);
  13. }).doSomething();

The component API returns a function. We could call this function and create as many instances of the component as we need. The syntax is similar to the one used in Backbone.js — we also send our logic as an object. The entry point of the component is the constructor method. By default, every instance is an event dispatcher. In the example above, we’re subscribing to some-event. Just after that we fire the doSomething function, which internally dispatches the event.

Sooner or later, we start thinking about managing dependencies. Different parts of our application need different modules, and it’s ideal if we can elegantly deliver them. To achieve that, AbsurdJS implements AngularJS’s dependency injection. Here’s how it works:

  1. absurd.di.register('mymodule', {
  2.     doSomething: function() {
  3.         console.log('Hi!');
  4.     }
  5. });
  6.  
  7. absurd.component('Name', {
  8.     doSomething: function(mymodule) {
  9.         mymodule.doSomething();
  10.     }
  11. })().doSomething();

We first register our dependency via the absurd.di.register function. It could be anything: a function, object or maybe a string. Afterwards, we just type our module as a parameter. The framework automatically calls the function with the right arguments. It’s very important to keep the same name used in the register method.

Writing the model

In the typical MVC pattern, the model is a class that stores and manages our data. We’ll stick to this idea and write our model in that manner.

We’ll store the ToDos of our application in the local storage of the browser. So, it makes sense to have a wrapper around this functionality. So, we’ll define it as a dependency so we have easy access to it later.

  1. // js/app.js
  2. absurd.di.register('storage', {
  3.     key: 'todos-absurdjs',
  4.     put: function(todos) {
  5.         window.localStorage.setItem(this.key, JSON.stringify(todos));
  6.     },
  7.     get: function() {
  8.         if(window.localStorage) {
  9.             var value = window.localStorage.getItem(this.key);
  10.             return value != null ? JSON.parse(value) : [];
  11.         }
  12.         return [];
  13.     }
  14. });

We have just two methods – put and get. They deal with the window.localStorage. The first one accepts the array containing the ToDos and the second one returns it.

Now, let’s use it as dependency and start filling our model with functions:

  1. // js/model/model.js
  2. App.Model = absurd.component('Model', {
  3.     data: [],
  4.     constructor: function(storage) {
  5.         this.data = storage.get();
  6.     },
  7.     updated: function(storage) {
  8.         storage.put(this.data);
  9.     },
  10.     add: function(text) {
  11.         this.data.push({
  12.             title: text,
  13.             completed: false
  14.         });
  15.         this.dispatch('updated');
  16.     }
  17. });

Once our model is initialized we try to get the data from storage. Notice that we are injecting the storage object. data is a property of our class that holds the ToDos. There is also an add method. We send the text of the ToDo, and the component makes a new entry. Moreover, the same method dispatches an updated event. In AbsurdJS, the component could catch its own events. All we have to do is define a function with the same name.

We will modify the data array in various situations. There are parts of our user interface that are interested in these changes. These parts should be notified, and the Dispatching updated event guarantees that. At the same time, the model itself needs to update the content of the local storage. So, we could simply add an updated method. It will be called once the event with the same name is dispatched.

By definition, the ToDoMVC app needs to do a few other operations. Like, for example, toggling, removing or editing. It should also show some information about how many ToDos are completed or left. Here’s the list of methods that cover these functionalities:

  1. toggle: function(index, completed) {
  2.     this.data[index].completed = completed;
  3.     this.dispatch('updated');
  4. },
  5. changeTitle: function(title, index) {
  6.     if(title === '') {
  7.         this.remove(index);
  8.     } else {
  9.         this.data[index].title = title;    
  10.     }
  11.     this.dispatch('updated');
  12. },
  13. toggleAll: function(completed) {
  14.     for(var i=0; i<this.data.length; i++) {
  15.         this.data[i].completed = completed;
  16.     }
  17.     this.dispatch('updated');
  18. },
  19. remove: function(index) {
  20.     this.data[index] ? this.data.splice(index, 1) : null;
  21.     this.dispatch('updated');
  22. },
  23. all: function() {
  24.     return this.data.length;
  25. },
  26. left: function() {
  27.     return this.todos('active').length;
  28. },
  29. completed: function() {
  30.     return this.todos('completed').length;
  31. },
  32. areAllCompleted: function() {
  33.     return this.todos('completed').length == this.todos().length;
  34. },
  35. todo: function(index) {
  36.     return this.data[index];
  37. },
  38. todos: function(filter) {
  39.     var arr = [];
  40.     switch(filter) {
  41.         case 'active':
  42.             for(var i=0; i<this.data.length; i++) {
  43.                 if(!this.data[i].completed) arr.push(this.data[i])
  44.             }
  45.         break;
  46.         case 'completed':
  47.             for(var i=0; i<this.data.length; i++) {
  48.                 if(this.data[i].completed) arr.push(this.data[i])
  49.             }
  50.         break;
  51.         default: arr = this.data;
  52.     }
  53.     return arr;
  54.  
  55. },
  56. clearCompleted: function() {
  57.     this.data = this.todos('active');
  58.     this.dispatch('updated');
  59. }

We have methods that give us access to the items stored in the data array. In some cases, we need the ToDo presented as a JavaScript object. So, defining methods like todo save us time. Also, the todos function accepts a filter setting and makes the cut.

Bootstrapping the application

In programming, we always have an entry point. In our case it’ll be in the js/app.js file. Let’s create a component that acts as an arbiter. It will create instances from the model, header, main and footer classes.

  1. // js/app.js
  2. absurd.component('Application', {
  3.     ready: function() {
  4.         var model = App.Model();
  5.     }
  6. })();

We define a new component class called Application and immediately create an instance from it. We write code that lives in the browser so, in most of the cases we are interested in running it once the page is fully loaded. Every AbsurdJS component could have ready method. It is, of course, optional but if it’s set the framework calls it when the DOM is ready.

We only have the model defined, so we initialize it. The model variable will be sent to the other parts of the application.

Adding new ToDo items

The HTML markup that is responsible for adding a new ToDo is positioned in the header.

  1. <header id="header">
  2.     <h1>todos</h1>
  3.     <input id="new-todo" placeholder="What needs to be done?" autofocus>
  4. </header>

AbsurdJS works with dynamically created DOM elements. Moreover, it supports fetching elements from the current DOM tree. In this article, we’re not going to use templates defined in JavaScript. More information about that is listed here. We will work with the markup that is already in the page.

Here is the finished version of our Header class:

  1. // js/views/header.js
  2. App.Header = absurd.component('Header', {
  3.     html: '#header',
  4.     onInputChanged: function(e) {
  5.         if(e.keyCode == 13 && e.target.value.toString().trim() != '') {
  6.             this.model.add(e.target.value.trim());
  7.             e.target.value = '';
  8.         }
  9.     },
  10.     constructor: function(model) {
  11.         this.model = model;
  12.         this.populate();
  13.     }
  14. });

Let’s examine it piece-by-piece:

  • html: '#header' tells AbsurdJS that this component works with an element matching #header selector.
  • The constructor of the component accepts the model and calls the internal function populate. It’s the only “magical” function in the framework. It does several things like fetching the right DOM element, parsing it as a template, compiling CSS and adding events’ listeners. After the calling of this method, we have access to this.el property that points to the actual DOM element.
  • onInputChanged – this is an event handler that has to be attached to the input field. It checks if the user presses the Enter key. If yes it calls the add method of the model and clears the field.

The Header class looks ok. However, it does not do anything right now because there is no event attached. To make the things work, we do not have to update our JavaScript. We need to set the data-absurd-event attribute in HTML:

  1. <header id="header">
  2.     <h1>todos</h1>
  3.     <input
  4.         id="new-todo"
  5.         placeholder="What needs to be done?"
  6.         data-absurd-event="keyup:onInputChanged"
  7.         autofocus>
  8. </header>

And of course, we have to create an instance from the class in app.js:

  1. // js/app.js
  2. var model = App.Model(),
  3.     header = App.Header(model);

Displaying ToDos

Let’s say that we have data in our storage. We need to show the ToDos on the screen. Let’s start filling js/views/main.js file:

  1. // js/views/main.js
  2. App.Main = absurd.component('Main', {
  3.     html: '#main',
  4.     filter: 'all',
  5.     todos: [],
  6.     constructor: function(model) {
  7.         this.model = model;
  8.         this.todos = this.model.todos(this.filter);
  9.         this.populate();
  10.     }
  11. });

Still the same pattern. We define the component and set the value to the html property. The model is passed to the constructor. We fetched the current ToDos and call the populate method. The app.js file needs one more line:

  1. var model = App.Model(),
  2.     header = App.Header(model),
  3.     main = App.Main(model);

So far so good. If we open the application now, we won’t see any results. It’s because we did not update our template. In other words, if we want to show something we have to add expressions. By expressions, I mean code that means something to the framework. The current template is as follows:

  1. <section id="main">
  2.     <input id="toggle-all" type="checkbox">
  3.     <label for="toggle-all">Mark all as complete</label>
  4.     <ul id="todo-list">
  5.         <li>
  6.             <div class="view">
  7.                 <input class="toggle" type="checkbox">
  8.                 <label>Task 1</label>
  9.                 <button class="destroy"></button>
  10.             </div>
  11.             <input class="edit" value="">
  12.         </li>
  13.     </ul>
  14. </section>

We’ll change it to:

  1. <section id="main">
  2.     <input id="toggle-all" type="checkbox">
  3.     <label for="toggle-all">Mark all as complete</label>
  4.     <ul id="todo-list">
  5.         <% for(var i=0; todo = todos[i]; i++) { %>
  6.         <li>
  7.             <div class="view">
  8.                 <input class="toggle" type="checkbox">
  9.                 <label>Task 1</label>
  10.                 <button class="destroy"></button>
  11.             </div>
  12.             <input class="edit" value="">
  13.         </li>
  14.         <% } %>
  15.     </ul>
  16. </section>

We wrapped the <li> tag in a for loop. There are two things that we have to mention here:

  • There is no new language or syntax between <% and %>. The expressions are pure JavaScript.
  • The expressions are evaluated in the context of the component. So we have access to every property or method of that component. In our case, we’re using the todos property.

Now let’s add some ToDos and check what’s going on:

todomvc-1

We do not have logic that updates the UI when a new ToDo is added, so we have to refresh the page. What we see is that there are two new <li> tags added, but they are not visible. And they are not visible because we set display: none to the #main container. We did:

  1. // css/app.css
  2. #footer, #main {
  3.     display: none;
  4. }

We need to change that. Here’s the moment where AbsurdJS becomes really handy. Normally, when we’re in such a situation we:

  • Create a new CSS class like .main-visible that has display: block in it.
  • Set the style manually to the element.

With AbsurdJS, it’s a bit different. At the beginning of the article, we said that this is a library that started as CSS preprocessor (i.e. it converts JavaScript to CSS). In the client-side context, this could be used for CSS injection. Let’s change our class so it shows the container if there are any ToDos:

  1. // js/views/main.js
  2. App.Main = absurd.component('Main', {
  3.     html: '#main',
  4.     filter: 'all',
  5.     todos: [],
  6.     css: {
  7.         '#main': {
  8.             display: '<% model.all() == 0 ? "none" : "block" %>'
  9.         }
  10.     },
  11.     constructor: function(model) {
  12.         this.model = model;
  13.         this.todos = this.model.todos(this.filter);
  14.         this.populate();
  15.     }
  16. });

We are able to use expressions in the CSS, too. model.all() returns the number of the ToDos in the list. All we have to do is call this.populate() and the framework will grab the content of the css property, convert it to valid CSS and inject it into the page.

css-injection

We need to subscribe to the updated event of the model so we can update the interface when the model changes. It makes sense to create a separate function:

  1. // js/views/main.js
  2. App.Main = absurd.component('Main', {
  3.     html: '#main',
  4.     filter: 'all',
  5.     todos: [],
  6.     css: {
  7.         '#main': {
  8.             display: '<% model.all() == 0 ? "none" : "block" %>'
  9.         }
  10.     },
  11.     constructor: function(model, router) {
  12.         this.model = model;
  13.         model.on('updated', this.bind(this.update));
  14.         this.update();
  15.     },
  16.     update: function(filter) {
  17.         this.filter = filter || this.filter;
  18.         this.todos = this.model.todos(this.filter);
  19.         this.populate();
  20.     }
  21. });

After this change, we are able to see the newly added entries. However, the label of the ToDo in the browser is still Task 1. So:

  1. <label>Task 1</label>

should be changed to:

  1. <label><% todo.title %></label>

Here is the result so far:

todomvc-2

Removing, editing and toggling ToDos

Our code can add new ToDos. We will continue with the rest of the tasks – removing, editing and toggling.

Deleting an entry

We have a button reserved for the purpose. Its markup is as follows:

  1. <button class="destroy"></button>

And we will change it to:

  1. <button class="destroy" data-absurd-event="click:removeToDo:<% i %>"></button>

Similar to the previous section, we added an event listener. However, this time we are doing something more. We make our function accept an argument, and this is the current index of the ToDo. Here is how removeToDo looks like:

  1. // js/views/main.js
  2. removeToDo: function(e, index) {
  3.     this.model.remove(index);
  4. }

Notice that the event handler receives the usual event object first. Our custom parameter is sent as a second argument. The model does the rest of the task. The UI is automatically updated because we are subscribed to the model’s updated` event.

Toggling the ToDos

The ToDoMVC folks require a completed class to every item that we mark as done. AbsurdJS compares its virtual DOM to the one in the actual tree and makes the necessary changes. So, all we just have to add one conditional statement that checks the completed flag of the ToDo:

  1. <li class="<% todo.completed ? 'completed' : '' %>">

This is enough to update the list. Every time we call populate AbsurdJS updates its virtual DOM element, and it’ll transfer that change to the page if the class property is updated. Here’s the new method for toggling:

  1. // js/views/main.js
  2. toggleToDo: function(e, index) {
  3.     this.model.toggle(index, e.target.checked);
  4. }

We have to update the HTML, so we call toggleToDo when the user clicks on the checkbox.

  1. <input class="toggle" type="checkbox">

Became:

  1. <input class="toggle" type="checkbox" data-absurd-event="click:toggleToDo:<% i %>">

The result looks like this:

todomvc-3

We could add one more function that will toggle all the entries:

  1. toggleAll: function(e) {
  2.     this.model.toggleAll(e.target.checked);
  3. }

And attach it to the element with #toggle-all id:

  1. <input id="toggle-all" type="checkbox" data-absurd-event="click:toggleAll">

Editing

The editing happens when the user double clicks an item in the list. The data-absurd-eventattribute should be set to the <li> tag:

  1. <li
  2.     class="<% todo.completed ? 'completed' : '' %>"
  3.     data-absurd-event="dblclick:edit:<% i %>"
  4. >

We need to make one more modification to show an input field. In that field, the user will type the new value. At the moment we have:

  1. <input class="edit" value="">

We’ll change it to:

  1. <input
  2.     class="edit"
  3.     value=""
  4.     data-absurd-event="keyup:onInputChanged:<% i %>, blur:save:<% i %>"
  5. >

Notice that we’re calling onInputChanged along with another function called save. AbsurdJS accepts multiple event handlers separated by commas. We may add as many as we want. For that particular element, we need to catch the Enter and Esc keys. So we save or discard the changes. When a user leaves the field we should save, too. This is the reason behind the blur event listening.

Here is the logic behind onInputChanged and save:

  1. onInputChanged: function(e, index) {
  2.     if(e.keyCode == 13) {
  3.         this.save(e, index);
  4.     } else if(e.keyCode == 27) {
  5.         e.target.value = this.currentTitle;
  6.         this.save(e, index);
  7.     }
  8. },
  9. save: function(e, index) {
  10.     this.model.changeTitle(e.target.value.trim(), index);
  11. }

Improving UI after population

Imagine that we mark all the ToDos as done with the #toggle-all button. The button itself has a small icon that is changed into a different color. This is all nice but we should make sure that we return the initial color if some of the ToDos are unchecked. We’ll use the populated function:

  1. populated: function() {            
  2.     var checkboxes = this.qsa('.toggle');
  3.     for(var i=0; i<checkboxes.length; i++) {
  4.         checkboxes[i].checked = this.todos[i].completed;
  5.     }
  6.     this.qs('#toggle-all').checked = this.model.areAllCompleted();
  7. }

That function is called when populate method finishes its job. Notice that in this example we are using this.qs and this.qsa that are just shortcuts to document.querySelector and document.querySelectorAll. What we are doing above is just checking if the current entries are all selected. If not, then we update the checked property of the toggle button.

The footer

The footer shows information about the currently selected ToDos and performs filtering. It also has a button for clearing the completed records. We again need some additions to the HTML:

  1. <footer id="footer">
  2.     <span id="todo-count">
  3.         <strong><% this.model.left() %></strong>
  4.         item<% this.model.left() == 1 ? '' : 's' %> left
  5.     </span>
  6.     <ul id="filters">
  7.         <li>
  8.             <a class="<% this.filterIndex === 0 ? 'selected' : '' %>" href="#/">All</a>
  9.         </li>
  10.         <li>
  11.             <a class="<% this.filterIndex === 1 ? 'selected' : '' %>" href="#/active">Active</a>
  12.         </li>
  13.         <li>
  14.             <a class="<% this.filterIndex === 2 ? 'selected' : '' %>" href="#/completed">Completed</a>
  15.         </li>
  16.     </ul>
  17.     <% if(this.model.completed() > 0) { %>
  18.     <button id="clear-completed" data-absurd-event="click:clearCompleted">Clear completed (<% this.model.completed() %>)</button>
  19.     <% } %>
  20. </footer>

At the top of the snippet, we show the remaining ToDos. The unordered list contains three links that show all the entries, only the active ones and only the completed ones. In the end, we conditionally show the button that removes the finished ToDos.

Here’s the code that we have to place in js/views/footer.js:

  1. App.Footer = absurd.component('Footer', {
  2.     html: '#footer',
  3.     filterIndex: 0,
  4.     css: {
  5.         '#footer': {
  6.             display: '<% model.all() == 0 ? "none" : "block" %>'
  7.         }
  8.     },
  9.     constructor: function(model) {
  10.         this.model = model;
  11.         this.model.on('updated', this.bind(this.update));
  12.         this.update();
  13.     },
  14.     update: function(filterIndex) {
  15.         this.filterIndex = typeof filterIndex != 'undefined' ? filterIndex : this.filterIndex;
  16.         this.populate();
  17.     },
  18.     clearCompleted: function() {
  19.         this.model.clearCompleted();
  20.     }
  21. });

It looks a lot like js/views/main.js in the beginning. We again have CSS injection that depends on model.all(). The model is passed to the component, and we subscribe to its updated event. The clearCompleted method simply forwards the task to the model. We should also add one more line to js/app.js so we get our footer class initialized:

  1. footer = App.Footer(model);

Now if we refresh the page we see that everything works perfectly except the filtering. We got #/active and completed in the bar, but nothing happens. It is because we do not have any logic that handles these changes in the URL.

AbsurdJS has a built-in router that works with the good old hash type of navigation but also supports the History API. Let’s change the ready function of js/app.js to the following:

  1. ready: function(router) {
  2.     var model = App.Model(),
  3.         header = App.Header(model),
  4.         main = App.Main(model),
  5.         footer = App.Footer(model);
  6.  
  7.     router
  8.     .add(/active\/?$/, function() {
  9.         main.update('active');
  10.         footer.update(1);
  11.     })
  12.     .add(/completed\/?$/, function() {
  13.         main.update('completed');
  14.         footer.update(2);
  15.     })
  16.     .add(function() {
  17.         main.update('all');
  18.         footer.update(0);
  19.     })
  20.     .listen(10) // listening for route changes
  21.     .check();
  22. }

Because the router is part of AbsurdJS, it is also available for dependency injection. We simply drop it as an argument. The class accepts regular expressions and compares them to the current URL. If some match, it calls a function. The method listen fires the check method every ten milliseconds.

Summary

AbsurdJS is a client-side framework that aims to provide simplicity. It sticks to the JavaScript object literals for defining classes. It has powerful template processing, dependency, and CSS injection.

If you’re interested in using it, check out the official site at http://absurdjs.com/.

Author: Krasimir Tsonev

Scroll to Top