Disqus and Code Formatting Conflict?

I’ve had reports that the code formatting isn’t working for some of you out there. I haven’t been able to replicate this, after testing on multiple machines and browsers. However I think it is due to a plugin conflict: namely the plugins for the Disqus comments and WPSyntax code formatting.

If you are reading any of my posts and notice that the formatting doesn’t look overly pretty, please could you help me out and see if you are having any JavaScript errors on that page. If so, please let me know so I can try to fix them.

For reference, the code highlighting is looking like this for me:

If you’re not getting the same I’d really appreciate it if you could help me track down why.

Backbone Reactive – Introducing the Dashboard

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

So far we’ve been working on a simple one page application. Now we want to introduce another page – the dashboard.

For simplicity sake for this project, we are going to have the dashboard page display just two items: some user details and the latest message.

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

Return Values and Callbacks

You can see the full code in commit d68d75d. I won’t go into too much detail as most of it is self explanatory and stuff we have already been over. However there is just one slight thing to look out for in the render() method of the main DashboardView.

  render: function () {
    var self = this;
 
    ...
 
    var userDetails = new UserView();
    self.$el.append(userDetails.render());
 
    var messageView = new MessageView();
    messageView.loadMessage(function(el) {
      self.$el.append(el);
    });
  },

The userDetails should be quite straight forward. All it is doing is appending the return value of the UserView‘s render() method to the DashboardView‘s DOM element.

The render() method simply returns the view’s el property.

  render: function () {
    ...
    return this.el;
  },

The loadMessage() method is doing almost exactly the same thing, but because it is having to retrieve some JSON from the server, so instead of returning the el property to passes it as a parameter to a callback:

  loadMessage: function (callback) {
    var self = this;
    self.model.fetch({success: function () {
      self.render();
      callback(self.el);
    }});
  },

Copy/Paste Naughtiness

Look at the code in dashboard.js. Do you see something horrible going on? Yes. Most of it is just copied and pasted from list.js.

This is fantastically bad practice. What if we want to change how the “nice date” is formatted? We’ll have to change it in multiple places.

Nope, this type of coding will not do. We need to turn our attention to reusing components.

Conclusion

OK, so now we have multiple pages within our application. But we have bodged this together and it isn’t very elegant. There is a load of copy and paste nastiness going on which I don’t much like, and this is something we’ll address next time.

But why would we want a multi-page application in the first place?

One reason is that it supports a fallback version much more easily – we could have a simple html website with multiple pages as the fallback version and then layer the multi-page Backbone app over the top.

Another reason is that this sort of html structure also helps with SEO, especially with a well chosen URL structure to match.

Finally, and this is a much more subjective and personal reason, it just makes more sense in my head. If the application has a number of different sections (dashboard, inbox, settings etc) then to me it make more sense to break it down into the distinct sections.

Multi-page or single page, this is your choice.

Reminder: You can find all the source code to this project on GitHub, this chapter has been tagged ch5-dashboard

Listening for Changing Events

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

We now have a simple application that allows us to load data in from a server (mocked in our case), display a list of results and then display specified further information based on a mouse click.

We are explicitly triggering an event, listening for it and carrying out a corresponding action based on the triggered event.

But what about events that we don’t manually trigger? What happens when something changes without our interaction but we still need to respond to it?

This is what listenTo() is for.

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

Data and Template Changes

To demonstrate how the listenTo() method is used we are going to include a new property in the listItem model called isRead. This is a very simple boolean property either false if the message hasn’t been viewed or true if it has.

Before we can include this in the application we first need to make some data and template changes.

Within the mock data for the list we must add the isRead property, for example:

{"id": 5, "date": "1357643063000", "subject": "Testing the Backbone Reactive List Page", "from": "Rob", "isRead": false }

Next we should update the HTML for the list, first the header within the ListView:

    var html = '<h1>Backbone Reactive List (from JSON)</h1>' +
      '<p>This is generated from JSON data. It isn\'t very special but ' +
      'there is enough going on to be a useful demo' +
      '<table border="1"><thead>' +
      '<tr><th>Time</th><th>Date</th><th>Subject</th><th>From</th><th>Read</th></tr>' +
      '</thead><tbody></tbody></table>';

Within the actual ListRowView we need to display a more human readable form of the boolean, so instead of true and false, how about yes and no?

  render: function () {
 
    ...
 
    var isRead = 'No';
    if(this.model.get("isRead")) {
      isRead = 'Yes';
    }
 
    // Later I'll be converting this to a template, but for the time
    // being it will suffice
    var html = '<td>' + timeNice + '</td><td>' + dateNice + '</td>' +
      '<td>' + subject + '</td><td>' + from + '</td><td>' + isRead + '</td>';
    this.$el.append(html);
    return this;
  },

As discussed before including the html directly within the Javascript is very bad practice and we will remedy this in a later chapter, but for now it will suffice.

Updating the Model

When we view the message we want to update the isRead property from false to true. This is very simple using the model’s set() method. Probably the easiest place to change this for us when we load the message, after we have fetched the data.

We should update the loadMessage() function that is called when we want to load the message to display. All we have really done below is add the functionality for setting the isRead property to true for the current ListItem model associated with MessageView.

  loadMessage: function (model) {
    var self = this;
    self.model = model;
    self.model.fetch({success: function () {
      self.model.set('isRead', true);
      self.render();
    }});
  },

Updating of the View

Now we are amending a property within the ListItem model so now we want to be able to listen for this change and update the ListRowView associated with this model accordingly.

This too is simple, all we need to do is when initializing the ListRowView listen for changes to the associate model. If there are any changes, re-render the view.

  initialize: function () {
    this.listenTo(this.model, "change", this.render);
  },

This should have the effect of refreshing the particular row, changing the “Read” column from “No” to “Yes”. However, a mistake earlier means that instead of simply re-rendering and replacing the specific row it re-renders and appends the updated row to the HTML. To change we need to stop appending the row to the DOM and instead just set the HTML

Within ListRowView change:

  render: function () {
 
    ...
 
    this.$el.append(html);
    return this;
  },

to:

  render: function () {
 
    ...
 
    this.$el.html(html);
    return this;
  },

and now it should simply replace the HTML, working as expected.

Conclusion

We are really motoring along with Backbone now and utilising some of its most powerful features. From this chapter we can see that it is relatively simple to layer further functionality over the top of a basic application. This is great for trying things out, but also great for building up an application over a number of iterative sprints.

The listenTo() method allows for disperate components of the application to stay updated on the states of each other and respond accordingly. This in itself cuts down on a lot of foo.on(event) type fluff.

So far we have just been tackling a single page application. Next time we move it up a gear to a multi-page app.

Reminder: You can find all the source code to this project on GitHub, this chapter has been tagged ch4-listen

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.