Model railroads: Part 3

There’s a few other methods I’d like to show you that you can use with models, particularly ones that can track changes in your model’s properties. As before, I’ve got examples of these snippets that you can play with at JS Bin.


if (railroad.has('conductor')) {
  console.log('Whew! This railroad has ' + railroad.get('conductor') + ' as the conductor.');

The had method is useful to see if a model has a property. In this case, we’re using it to check if the railroad has a conductor. Since conductor is one of the default properties for the Railroad model, it should return true.


console.log('Does the railroad have a owner? ' + railroad.has('owner'));

You can use unset to remove a property from a model. In this case, owner was one of the default properties for the Railroad model, but after unsetting it, it’s removed and therefore when we use the has method later, it returns false.


  console.log('Does the railroad have a conductor? ' + railroad.has('conductor'));

Clear unsets all the properties so you’re left with an empty model with no properties.

hasChanged and previous

var railroad = new Railroad();
railroad.set('destination', 'Quarry');
console.log('Has the destination changed? ' + railroad.hasChanged('destination'));

railroad.set('destination', 'Brendam Docks');
console.log('Previous destination: ' + railroad.previous('destination'));
console.log('Has the owner changed? ' + railroad.hasChanged('owner'));

These two methods are handy with tracking changes in your model, which is one of the reasons I started using Backbone.js. The hasChanged method will let you know if a property has changed.

The previous method will give you the previous value of the property you specify. This will work even if the property was never set, or if you have unset a property.

There are other methods for models as well, but many of these deal with interacting with a server, which we’re not going to cover yet until we get through other major components of Backbone, such as Collections, Views and Routers.

Similar Posts