Stefan Ledin

Weird issue with defaults in Backbone models

I’ve been doing a lot of Backbone work lately and I stumbled across some interesting behavior. It took me quite a while to figure out where it came from, so I might as well share it with the internet.

I was working on a new feature for Responsify WP 1.9. It’s a UI for creating custom media queries and I’m using Backbone.js for it.
I created a model which had an empty array as a default attribute. The problem was that when I added things to the array, it was added to all models!

var model = Backbone.Model.extend({defaults: {mediaQueries: []}})
var m1 = new model()
var m2 = new model()
m1.get('mediaQueries').push('value');
m1.get('mediaQueries'); // Equals ["value"]
m2.get('mediaQueries'); // Also equals ["value"]

Well, this is odd right? But if I did it this way instead, it worked as expected!

var model = Backbone.Model.extend()
var m1 = new model()
var m2 = new model()

m1.set('mediaQueries', []);
m1.get('mediaQueries').push('value');

m1.get('mediaQueries'); // Equals ["value"]
m2.get('mediaQueries'); // Undefined

That’s it! Okey, I guess this isn’t useful for anyone reading this, but I felt that I had to write it down since it took me many days to find the issue.