Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Backbone Models Singletons?

I'm not a JavaScript expert so I might be doing something wrong here.

I have a simple Foo Backbone model with a default property bars which is an empty array. I create two instances of the model. I add "a" and "b" to the first model, "c" and "d" to the second model. When I print out the contents of bars with console.log(), it appears that both instances are the same object.

JsFiddle: http://jsfiddle.net/P7qsz/

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 foo2 = new Foo();
foo2.get("bars").push("c");
foo2.get("bars").push("d");
console.log(foo2.get("bars"));

In the console I see:

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

What am I doing wrong?

like image 465
Richard Knop Avatar asked May 20 '26 15:05

Richard Knop


2 Answers

In javascript, Arrays (and objects) are passed as references.

Here, you assigned the same array reference to each models.

To fix it, you'll need to assign a new Array each time.

Backbone.Model.extend({
  initialize: function() {
    this.set("bars", []); // Here we set a new array
  }
});
like image 97
Simon Boudrias Avatar answered May 22 '26 03:05

Simon Boudrias


They are not singletons.

console.log(foo === foo2) //false

What happens is that both instances shares the default object, and it has a refenrece to an array. So in the end all instances of this model have the same array.

Arrays and objets should never be declared in the default object, it should be in the constructor.

var Foo = Backbone.Model.extend({
    initialize: function () {
        this.set("bars", []);
    },
    defaults: {
        bars: null
    }
});
like image 33
Kaizo Avatar answered May 22 '26 03:05

Kaizo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!