Skip to content

Instantly share code, notes, and snippets.

@deathbearbrown
Created June 14, 2013 18:29
Show Gist options
  • Save deathbearbrown/5784139 to your computer and use it in GitHub Desktop.
Save deathbearbrown/5784139 to your computer and use it in GitHub Desktop.
Models and Collections
You might be used to thinking of a model like a prototype.
You know a Person in your DB will have the following attributes: Name, Age, Phone
in backbone you'd make a model for person like this
Person = Backbone.Model.extend({
defaults: {
name:"Billy",
age:"33",
phone:"555-555-5555"
}
});
Then you can get this information from the model like this
NewGuy = new Person();
NewGuy.get('name'); /// will return "Billy" anything you define in defaults will be retrieved with ".get()"
Now in terms of a DB if you were getting JUST Billy you could have:
Person = Backbone.Model.extend({
url:"/people?name=billy"
});
"/people?name=billy" when you hit it returns the following JSON:
{
name:"Billy",
age:"33",
phone:"555-555-5555"
}
You don't actually have to put the defaults in your model, but there might be cases where there are default values that the server doesn't return but you want it in your model.
Person = Backbone.Model.extend({
url:"/people?name=billy",
defaults: {
newguy:true
}
});
^ here if you call fetch on this, you will end up with the following attributes inside your model that you can access using .get():
name, age, phone, newguy
what happens when you fetch is that the model will take whatever json comes back and set it in the model. You can set things in models like this:
Person.set({"name":"Joe"}); <-- will override Billy with Joe
Person.set({"hometown":"Boston"}); <-- will add new attribute hometown with the value boston
Fetch sets all that stuff for you, so you don't actually have to set up defaults if you know your backend will return all the attributes when you fetch.
Now what if your backend returns all the people in your DB and the returned JSON looks like this:
[
{
name:"Billy",
age:"33",
phone:"555-555-5555"
},
{
name:"Sue",
age:"30",
phone:"555-555-5555"
},
{
name:"Ripley",
age:"2",
phone:"555-555-5555"
}
]
Then you need a collection. A collection will take all of that and sort each into it's own model.
People = Backbone.Collection.extend({
model:Person, //set the model you want it to use
url: "/people"
});
Now that everyone is in a collection you can use underscore's fun methods for finding things:
Var mypeople = new People();
mypeople.fetch();
mypeople.where({name: "Ripley"});
or you can interate over each
mypeople.each(foobar());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment