Model railroading with Backbone.js

All aboard! We’re building a model railroad using Backbone.js.

Now as I’ve mentioned in earlier posts, I’m not a JavaScript expert nor claim to be one, so I might not use some of the terminology more experienced programmers use. I will try my best to be accurate, but I might give more analogies than terms like “methods” and “instantiation”. However, if I do say something in error, please kindly let me know.

Why use Backbone.js for building a model railroad?

At first, it might seem silly to use a JavaScript library to create a model railroad, when I can just write something like this:

var railroad = {
  name:'Gold Country Express',
  destination:'Folsom'
};

Then to see the destination of my railroad, I could just write:

console.log(railroad.destination);

Easy enough. Then if I wanted to change the destination, I could just do this:

railroad.destination = 'Placerville';

Even easier! But what if I wanted to go back and remember what I had as my previous destination. Oops, that information is gone I’m afraid.

That’s where Backbone models comes in handy. There’s more that we can do than just saving previous data, which I plan to cover later.

What’s a Backbone model?

Backbone.Model is a class that you use to create your own model classes. It works by using extend to create your own specific class with it’s properties.

Sounds like a lot of work? Well, yes it’s more work up front, but it saves you time and effort later down the road.

Backbone model vs. standard JavaScript “model”

Okay, so we created a railroad object earlier. If we were going to do it in Backbone, we might write something like this:

var Railroad = Backbone.Model.extend();
var railroad = new Railroad({
  name:'Gold Country Express',
  destination:'Folsom'
});
console.log(railroad.get('destination'));

To change the railroad’s destination, you’d do this:

railroad.set('destination', 'Placerville');
console.log(railroad.get('destination'));

Okay, now you might be thinking, “Okay, but how does help me? Both versions do exactly the same thing.”

Unfortunately,  we’ll have to cover that tomorrow, when I plan to go more in depth with what you can do with Backbone models.


Discover more from AaronTweeton.com

Subscribe to get the latest posts sent to your email.