Skip to content

Instantly share code, notes, and snippets.

@dugasmark
Created November 29, 2013 08:00
Show Gist options
  • Save dugasmark/7702757 to your computer and use it in GitHub Desktop.
Save dugasmark/7702757 to your computer and use it in GitHub Desktop.
Model: Le piège des valeurs par défaut

http://backbonejs.org/#Model-defaults

Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances. Instead, define defaults as a function.

##Problème##

var Human = Backbone.Model.extend({
  defaults : {
    firstName:"John",
    lastName:"Doe",
    friends:[]
  }
});

var bob = new Human({firstName:"Bob", lastName:"Morane"});
var john = new Human()
var jane = new Human({firstName:"Jane"})

bob.get("friends").push(john, jane)

jane.get("friends");  -> wrong number of friends
john.get("friends");  -> wrong number of friends

##Solution##

var Human = Backbone.Model.extend({
  defaults : function() {
    return {
      firstName:"John",
      lastName:"Doe",
      friends:[]
    }
  }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment