Quantcast
Viewing all articles
Browse latest Browse all 20

Are Backbone Models Singletons?

I have been using Backbone (plus couple of other JavaScript libraries) for my last project. One of the first problems I encountered was this simple code:

var Foo = Backbone.Model.extend({
    defaults: {
        bars: []
    }
});

var foo = new Foo();
foo.get("bars").push("a");
foo.get("bars").push("b");
console.log(foo.get("bars"));

var foo = new Foo();
foo.get("bars").push("c");
foo.get("bars").push("d");
console.log(foo.get("bars"));

A simple model with array as a property, seems pretty straightforward. But when I created two instances of the model, this was logged in the console:

["a", "b", "c", "d"]
["a", "b", "c", "d"]

JSFiddle

Well, the problem was that the property declared in defaults is a global one. In order to avoid this rookie mistake, init all arrays or dictionaries in initialize method:

var Foo = Backbone.Model.extend({
    initialize: function() {
        this.set("bars", []);
    }
});

Here is my related StackOverflow question: Are Backbone Models Singletons?


Viewing all articles
Browse latest Browse all 20

Trending Articles