Backbone Reactive – Adding in Events

This is Part Three of the Backbone Reactive Tutorial. For all sections, please view the Table of Contents.

So far the List page doesn’t do anything apart from list the messages we have. This means that it is less functional than the static html fallback site – at least with that one you could view the message contents. So in this post we are going to build on our simple Backbone app, adding in events so you can actually view the messages.

Luckily adding Events in Backbone is simple. Within the ListRowView all you have to do is add:

  events: {
    "click": "open"
  },
 
  open: function () {
    console.log("clicked: " + this.model.id);
  },

Now when you reload the page and click on a row you should see the console output the ID of the model you clicked on. So now we know we can click on a row, we need to load in the data and display it.

Note: You can find all the source code to this project on GitHub, this chapter has been tagged ch3-events

Let’s tackle this in reverse order and create a new view to display the message contents, we’ll call it MessageView:

var MessageView = Backbone.View.extend({
  id: 'message',
 
  render: function () {
    var date = DateFunctions.getDate(this.model.get('date'));
    var dateNice = DateFunctions.getDateAndTimeNice(date);
 
    var html = '<p><label>From</label> ' + this.model.get('from') + '</p>' +
      '<p><label>Date</label> ' + dateNice + '</p>' +
      '<p><label>Subject</label> ' + this.model.get('subject') + '</p>' +
      '<p>' + this.model.get('body') + '</p>';
    this.$el.html(html);
    // if the message view is not already attached to the page, simply
    // append it into the body
    if (!$("body").children("#" + this.id).length) {
      $('body').append(this.$el);
    }
  }
});

There is nothing too special going on here. All this view currently does is to render a bunch of HTML, using the properties of its model for the values.

You may spot a new object called DateFunctions. This was a simple utility object created as now we are displaying the data in two views (the ListRowView and the MessageView).

The big questions about this view are:
– how does it get the data to display? and
– where is it called from?

When working through this initially I started to initiate and load the MessageView directly in ListRowView when the event was clicked (see /57e9e5f/). However, this lead to the two undesirable outcomes.

Firstly MessageView would have been repeatedly initialised every time someone tries to view a message. This isn’t too big a deal, but it is not efficient when we could initialise once and be done with it.

Secondly, as the MessageView would be initialised every time we want to view the message, when the view renders and injectes itself into the DOM we needed to add logic to stop it adding itself multiple times to the page.

There are a couple of ways to solve this. One method (although I didn’t try it) would possibly be to create a singleton class for the Message viewer, this would have stopped the reinitialisation issue.

The method I went for in the end was to “bubble” the event up, from the List Row to the main List view. As all the ListRowViews would bubble up the event, we would only need to call the MessageView once and then listen for the “view message” event to re-render the message viewer.

We use the Backbone trigger functionality to bubble up the event. (Recall that the open function is called when a row click event is detected).

  open: function () {
    this.trigger("viewMessage", this.model);
  }

Now, in the ListRowView we make two changes. Within the initialize function we initialize MessageView.

  initialize: function () {
    ...
    this.messageView = new MessageView();
  },

And then during the rendering process, when looping through the listItems we add a listener to the ListRowView instance and when a viewMessage event is detected, we instruct the MessageView instance to load the message based on the model passed with the event.

    self.collection.each(function (listItem) {
      var v = new ListRowView({model: listItem});
      v.render();
      // listen for the "viewMessage" event, loading the message whenever it is triggered
      v.on('viewMessage', function (model) {
        self.messageView.loadMessage(model);
      });
 
      self.$el.children("table").append(v.el);
    });

The method to load the message within MessageView is very simple, all it does is to tell the model passed to (re)fetch it’s data and then renders the view.

var MessageView = Backbone.View.extend({
  id: 'message',
 
  loadMessage: function (model) {
    var self = this;
    self.model = model;
    self.model.fetch({success: function () {
      self.render();
    }});
  },
 
  ...
});

Finally, to finish this all off we must update the ListItem model ever so slightly, informing it where it should load in the data, by setting the URL. This is slightly more complicated than the ListCollection URL as we need to specify which message we want to load in, so have to add the model’s ID to the URL.

var ListItem = Backbone.Model.extend({
  url: function () {
    return '/mock-data/message.' + this.id + '.json';
  }
});

An example of the mock data we will load in is:

{
  "id": 1,
  "date": "1357643063000", 
  "subject": "Testing the Backbone Reactive List Page", 
  "from": "Rob" ,
  "body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque ornare, ligula a tincidunt cursus, lorem magna ullamcorper enim, ut interdum nisi quam vel lorem. Aliquam aliquam sem eu ipsum pretium ut bibendum quam blandit. Duis vel blandit nibh. Vestibulum mattis sapien eros, ut iaculis quam. Suspendisse potenti. Ut eleifend massa a libero adipiscing porttitor in ut nunc. Sed lobortis pretium consectetur. Morbi convallis, velit sit amet placerat vehicula, dolor lorem sollicitudin enim, at convallis tortor ipsum vel lectus. Fusce eget tellus sit amet nisl interdum volutpat. Etiam congue nibh id quam scelerisque posuere."
}

Conclusion

We are really starting to get to the meat of Backbone JS now. The ability to automatically get fresh data from the backend (or in our case the mock json data) and then the views to be updated without having to worry about JQuery calls or complex logic is really powerful stuff.

Reminder: you can find all the source code to this project on GitHub, this chapter has been tagged ch3-events.

Overlay a Simple BackboneJS Application

This is Part Two of the Backbone Reactive Tutorial. For all sections, please view the Table of Contents.

Now the static fallback content has been created and is working, we start overlaying a basic Backbone application over the top.

We will leave the homepage for the moment, coming back to that later on in this project. For now we will concentrate on the List page. The functionality of the List page is very simple: all it does is replace the static content on the List page with some dynamically generated content from JSON data retrieved by an Ajax call.

Note: You can find all the source code to this project on GitHub, this chapter has been tagged ch2-simple.

Dependencies

In the list.html page we simply need to load in the required Javascript files for our application. Obviously there is Backbone, but we also need to include its dependencies, underscore and either jQuery or Zepto. In our case we will use jQuery for the time being, as it is the framework most people are familiar with. (As we progress with developing for mobile devices we will be investigating Zepto as a replacement).

<script type="text/javascript" src="/js/jquery-1.8.3.min.js"></script><script type="text/javascript" src="/js/underscore-min.js"></script><script type="text/javascript" src="/js/backbone-min.js"></script>

Once we’ve loaded in our dependencies, we need to load in our actual application file:

<script type="text/javascript" src="/js/app/list.js"></script>

It is this file, list.js that does all the work. There is quite a lot going on in this file, even for a simple app such as this, so let’s brake it down piece by piece.

JSLint

It is a good idea to lint your Javascript code. The main reasons for this is to give all your code a consistency so it is easier to come back to later. It also catches any silly typos or bugs along the way.

For linting this project, I am using the SLint NodeJS module, the lint command used is:

jslint -indent=2 --plusplus --vars ./js/app/list.js

JSLint can be a bit bossy, so you’ll notice that the first few lines in the code are simply there to keep there to keep JSLint happy.

  'use strict';
  var Backbone; // hello jslint
  var $; // hello jslint

Now we have the tedium of keeping code tidy out the way, we can move onto the actual meat and potatoes.

Models

Reading through the rest of the list.js file, you’ll see that it follows a pattern of building up each needed component one at a time.

Firstly a ListItem Model is defined. This very simply extends the base Backbone Model.

var ListItem = Backbone.Model.extend({});

This line is so simple because Backbone Models are so powerful. But why do we need a model in the first place?

The way I think about it, models are the basic units of data within a Backbone application. They are the smallest piece of complete information within context. For example, in our project, the smallest piece of complete information is an item of the list. This item itself has smaller pieces of data, such as a date or subject, but without the wider context of the item itself, these tiny pieces of data make no sense – they are not complete.

Models don’t just contain data, they also have logic handling that data: validation, access control etc as well as events bound to that data. For example, if the UI changes a property of the model, this can trigger an event so other parts of the UI can react. This is why they are so powerful.

However, for our purposes we are going to explore none of that right now. Instead we’ll move onto Collections

Collections

Whilst models provide the individual bits of data, Backbone Collections, as their name suggests, collate these individual bits of data into one group, or collection. The important thing to remember about collection are that the models within them are ordered. This allows us, for example, to load in ordered data and have this order honoured within the collection.

When defining a collection we want to start using dynamic data. Backbone has built in functionality for this, which greatly reduces the amount of code needed to be written for ajax calls etc.

To start using dynamic data in a collection we must specify a URL. This URL is for the ajax request when we call the collection’s fetch() method. (For the purposes of this tutorial we are simply using mock JSON data, not a dynamic backend). As we want the data to load in straight away we call the fetch() method in the initialize function, passing it any callback options.

Backbone has another built in method – parse() – to interpret the data received within the response from the ajax request. In our case, we simply want to return exactly the data that we fetched from the mock JSON file.

var ListCollection = Backbone.Collection.extend({
model: ListItem,
 
initialize: function (models, options) {
this.fetch(options);
},
 
// As we don't really care for the backend in this demo, we have
// hard-coded some JSON data to use in the application
url: '/mock-data/list.getList.json',
 
parse: function (response) {
return response;
}
});

As with the Models, Collections are simple, but powerful.

For reference, the format of the JSON data returned is as follows:

[
{"id": 5, "date": "1357643063000", "subject": "Testing the Backbone Reactive List Page", "from": "Rob" },
{"id": 4, "date": "1357642823000", "subject": "Another exciting subject line", "from": "John" },
{"id": 3, "date": "1357641983000", "subject": "I just love dancing", "from": "Billy" },
{"id": 2, "date": "1357565783000", "subject": "Possible expansion plans", "from": "Wilhelm" },
{"id": 1, "date": "1357563263000", "subject": "Can't think of anything witty", "from": "Susan" }
]

Views

Backbone Views are where the action really gets going.

Now we have defined our data and how it is organised, we need to start using that data. What this means for us is that we need to start displaying this data within the browser.

The way I like to think about views is that they represent individual components or groups of components within the user interface. In our current list page we have broken it down into two views:
- a view for the complete list, in our UI this is a table
- a view for the individual list elements, or table rows in our case

This relates very closely to Collections (for the complete list) and Models (for the individual rows). In fact, Backbone allow us to attach both models and collections directly to views during initialization. something we will look at in a moment.

First we define the view for the table row, or list item:

var ListRowView = Backbone.View.extend({
tagName: "tr",
className: "list-row",
 
....
});

Setting the tagName property to tr means that when inserted into the DOM, this view will be a table row element. We also add a class name, thinking about it I’m not sure why, possibly just because we can.

Right now, this view is a little useless, so we need to implement the render() method:

render: function () {
this.id = this.model.get("id");
 
// I am not spending too much time on the date formatting or
// making it look nice, I just need enough so it works
var date = new Date(parseInt(this.model.get('date'), 10));
var timeNice = this.padTime(date.getHours()) + ':' + this.padTime(date.getMinutes());
var dateNice = date.toLocaleDateString();
 
var subject = this.model.get("subject");
var from = this.model.get("from");
 
// Later I'll be converting this to a template, but for the time
// being it will suffice
var html = '' + timeNice + '' + dateNice + '
 
' +
'' + subject + '' + from + '
 
';
 
this.$el.append(html);
return this;
},

The first thing to notice is that we are associating the ID of this view instance with that of the view’s model. This is important when it comes to triggering and responding to events later.

However, we have neatly glossed over where the model comes from. How does the View contain a model from which it can use it’s ID?

As mentioned above, views can have collections and models attached to them during initialization. Jumping ahead of ourselves slightly, in the ListView view, we can see that when we loop through the collection of items, we initialize the ListRowView passing it a ListItem model instance.

self.collection.each(function (listItem) {
var v = new ListRowView({model: listItem});
...
});

The rest of the render() method is pretty self explanatory (if not incredibly quick and dirty, we will fix this in a later post).

We first clean up some of the model’s properties so they are suitable to be displayed to the general public. Next we build the HTML for the table row and then append this HTML to the table row element the view represents. Finally, we return ourselves as is convention.

So that is the individual table rows sorted. Next we need to look at the complete list as a whole.

As ever, we simply extend the base Backbone View:

var ListView = Backbone.View.extend({
 
});

However, unlike the ListRowView we are going to define an initialize method:

initialize: function () {
var self = this;
self.collection = new ListCollection({}, {
// the success function is used for the fetch callback
success: function () {
self.render();
}
});
},

This is doing three very important things so let’s pay close attention to them.

Firstly it is initializing the ListCollection. As described above, the act of initializing this collection will fetch the data from the mock JSON we have and assigning the results to itself.

Secondly we are assigning this ListCollection to be the current collection for this view. This will allow us to access the Collection data and contained Models far easier later on.

Finally, once the data has been loaded and the view’s collection populated we render the view.

render: function () {
var self = this;
var html = ' [ edited for brevity ] ';
self.$el.html(html);
 
self.collection.each(function (listItem) {
var v = new ListRowView({model: listItem});
v.render();
self.$el.children("table").append(v.el);
});
 
return self;
},

As we have already dealt with the most important part of this render method above, the rest of it should be pretty self-explanatory. However, to quickly summarize we are first creating a bunch of HTML represented by this view (yes yes, I know! We will move it to a template in a later post) and then injecting it into the DOM. Next we loop through each model in the collection, initializing a new view for each model and then appending that to the table element we have just injected into the DOM. Finally, we return the view itself as is convention.

Running the App

Finally, now all the Models, Collections and Views have been defined, we can run the app. This is simply a case of initiating the ListView, applying it to a specific DOM element. In our case it is #content.

That is it. To test it out, fire up the _server.js NodeJS HTTP server and navigate to http://localhost:7777/list.html. You should see a table of list items, which has been entirely populated by your Backbone application.

Congratulations. The first step is complete. On to events.

Reminder: you can find all the source code to this project on GitHub, this chapter has been tagged ch2-simple.

Bank Holiday Reading 6 May 2013

To start of with, we have a great story about a game developer releasing a game about game development and what happens when the pirates were pirated.

As I find myself tumbling down the rabbit hole of Lisp and it’s derivatives, this article was very timely for me. An interesting read and makes me want to roll my sleeves up yet further.

To continue the Lispish theme, this post about Chicken Scheme did not disappoint. A really great read for the weekend. Looks like a very interesting blog to follow.

Just to reinforce the point that the Atomic Object’s Blog was worth following, here is another good post. This time it is about reading code.

Back to the lisp theme. I have had SICP on my bookshelf for a number of years, but never really tackled it. This article by Brian Harvey reminds me that I probably should give it another go.

Finally, if you have had enough reading for the week, watch this 15 minute TedX talk about what we can learn from Linus Torvalds.

Backbone Reactive – Fallback Version

This is Part One of the Backbone Reactive Tutorial. For all sections, please view the Table of Contents.

The first thing we should always do, when building any application that relies heavily on the frontend Javascript is to produce a fallback version. The reasons are pretty straight forward:

  1. If a user visits your application and for whatever reason they don’t happen to Javascript enabled, then they will still be able to get some value out of your site. This will obviously be heavily reduced value, but it is better than nothing, of even worse, a message saying “You Need Javascript”
  2. It is always handy for SEO purposes to have at least some content on the page, not just a link to a Javascript file which will generate the content.

(more…)

Backbone Reactive – Introduction

This is Part Zero of the Backbone Reactive Tutorial. For all sections, please view the Table of Contents.

At the end of 2012 I began playing around with Backbone.js. One of the things I was very keen on was producing a site that used a single codebase but could handle desktop, tablet and mobile version with minimal effort – so called “reactive design”.

This series of posts is the culmination of my experimentation, problems faced, decisions made and lessons learned.

There will be roughly 15 posts in this series (not sure an exact number as they are still being written, tweaked, combined and expanded. I aim to publish one per week, but if I have the time I’ll try I’ll try and up the frequency.

I hope you enjoy.

You can find all the source code for this tutorial in the Git Repo.

Org-Mode, Shared Agenda File List

After watching a chat between Sacha Chau and John Wiegley about Emacs, I’ve gone on an Emacs rampage. I tweaking my init script to use org-mode (probably more on that another day) and generally getting things ticking along quite nicely.

I use three different computers (desktop at office, desktop at home and laptop) and all my Org files are kept in sync via Dropbox. However, one thing that has irritated me with this setup is the facts that whilst the files are shared between the three machines, which of the Org files are considered agenda files is not. On each machine I have to keep on adding files into the agenda list with C-c [. I have a number of different agenda files (one for each project or sub-project I’m working on) so files are added to and removed from the list quite frequently.

It would be great if the lost of agenda files could be sync’d too.

As ever in Emacs, there is a way. In this case it is the variable custom-file.

You can get more information about this variable using the describe-variable command (C-h v then enter custom-file)

So, to change the location of the custom file, all I needed to was to add the below to my init file:

;; Ensure that any custom variables are synced via Dropbox
(setq custom-file "~/Dropbox/emacs/custom.el")
(load custom-file)

Hurray for Emacs!

Testing Org2Blog

This is a very quick test of posting to my WordPress blog using org2blog. As such, it’s probably not going to be very long, but hey, it’s a test.

Heading Level Two

What does this look like. Clearly this is very exciting! Now, how to publish… ah, C-c p.

After Publish Edit

Well, that was surprisingly easy! I could get used to this.

Should we use Frameworks?

Over the past month there have been a number of security issues with the Ruby on Rails framework. These issues have been serious. Whilst there is some debate whether this is an isolated Rails issue or if we can expect more frameworks to start seeing these sorts of vulnerabilities discovered this has left me with a niggling question at the back of my mind.

Should we use frameworks?

Rails is a massive monolithic framework, but (security issues aside) do the benefits of using it outweigh the benefits of not using it? This goes for any framework, in any language. Are we ultimately better developers for using frameworks, or for not using frameworks?

To answer these questions, I have drawn up a (completely non extensive and totally subjective) list of pros and cons.

The main benefit of using frameworks is the lack of having to constantly reinvent the wheel. Every time you start a new project, is it easier to use a framework that comes with ready-made modules for accessing the database, session management, caching etc, or is it easier writing all this stuff from scratch?

The answer simply must be the former. The reason for this is two fold:

Firstly, the time you save not having to reinvent the wheel you can put to actually developing your application. In this respect it will greatly speed up development time.

Secondly, as these utility modules (for want of a better term) are within a framework, you can be sure that the code has had more people looking over it than if you wrote it yourself.

This leads on to my next point. As Eric Raymond dubbed “Linus’s Law”: “given enough eyeballs, all bugs are shallow“. With a popular framework that has a vibrant and engaged community you should be relatively confident that the code has been reviewed a number of times by a number of different authors. Or at least, you should be relative confident.

But what of the vulnerabilities found in Rails? These issues had been lying there for some time. They had certainly been there long enough for the issues to be reported multiple times, but no action was taken. Again, I’m not trying to single out Rails here, but it is the highest profile framework at the moment.

However, there is nothing stopping you from auditing the code on your favourite open source framework and contributing back to the community. In my opinion this is another benefit of using a framework – the community. If you engage with the community, follow the mailing lists, chat in IRC then you can really improve your usage and productivity with the framework, again helping you develop better applications.

But what about the disadvantages of using frameworks?

Firstly it is yet another thing to learn. If you are just starting out with a framework you have to learn it. You must learn it’s foibles and nuances. This takes time, slowing you down. Granted, once you have learned the framework your development time is quicker than without a framework as discussed, but to start off with, development is slower.

As well as learning a frameworks foibles and nuances you must also learn its limitations. There are just some things that some framework will either not let you do, or are harder to do than if you write the code raw. When developing with a framework this is something that must be taken into account.

Ironically, whilst frameworks contain limitations, a lot of them are also bloated. Zend for PHP springs to mind as in fact does Rails. When using frameworks such as these your application is not as optimal as it can be because it is carrying around the huge and for you possibly mostly unneeded weight of the framework.

However, in my mind the biggest disadvantage is the “black box” scenario. People just blindly using the frameworks without delving deep into the code that the framework is made from. There is an element of faith here. Faith that the code is sound and secure. Faith that the code in the framework and the development of that code has been treated seriously, professionally and with respect. This is especially true with Rails, in part due to it’s “cool” tag a lot of newbie programmers are using it. There is nothing wrong with this, Ruby and Rails are great places to start the journey of coding. But if you are just starting out you cannot possibly know of all the implications of taking a codebase on faith.

In this case the users of Rails were badly let down.

So what is the conclusion? Should we use frameworks?

Overall, I think yes. A framework should be used. But what type of framework? that is the more important question.

The framework you use should be small, small enough so you can truly get to understand it. Small enough to only contain the elements that you really need. However, it should have a vibrant and responsive community. Now I don’t mind if the framework you use is an existing one or it is a framework you have developed for yourself. But if you have lovingly hand-crafted your own framework you should open source it. It is imperative that the framework you use must have a community. A community to find and fix bugs, to keep the code clean and optimised. To document and battle-harden.

You must either find a framework that is small and has a great community, or build the framework you need with a community to match.

Sonar GNU/Linux on Indiegogo

In my random trawling through the internet I can across a very worthwhile Indiegogo campaign. It is raising money to help develop the Sonar Project, a GNU/Linux system focusing on accessibility.

This is the thing I particularly love about Linux, and the free software movement in general: the fact that you can take a product and improve it in the way that best suits you. This is a commendable effort for bringing Linux and computing to those with disabilities and should be supported.

Go and support Sonar now.

How to Improve your Programming Skills

As the subtitle of this blog indicates, I am a self taught programmer.

Like most self taught coders, I suffer from the horrible feeling that I am missing something in my programming education. As such I am continually striving for improvement. But how do you achieve improvement? Where do you start? What do you do? Is there any set methodology?

Searching the internet looking for direction yields a bunch of different advice, but it is mostly really common sense: write more code; read more code; learn a new language; do coding exercises; etc.

This is obviously all good advice, but it misses the heart of the problem: focus.

It is all well and good learning a new language, just as it is well and good completing some exercises, but this is ultimately busy work if you don’t know what particular aspects of your coding you want to improve.

Improving your ability to code complex algorithms is very different to improving your ability to code complex front-end user interfaces.

If you are aiming to improve the former, then no amount of learning the latter will help.

Programming is now a vast field, and it is only once you have decided what aspects of programming it is that you want to improve, where to apply your focus, can you truly start to improve.

So, what areas of your coding skills do you want to improve? Define that, then answering the question of how to improve becomes much clearer.