Models Flashcards
How do you set an attribute on a model?
model.set(‘title’);
How do you get an attribute on a model?
model.get(‘title’);
How do you get a JSON representation of a model?
model.toJSON();
How do you clear all attributes on a model?
model.clear();
How do you unset an attribute on a model?
model.unset();
How do you see if a model has an attribute?
model.has(‘title’);
How to create a model?
var Model = Backbone.Model.extend();
How do you instantiate a model?
var model = new Model;
How do you set values to be a default when coding a model?
var Song = Backbone.Model.extend({ defaults: { title: "default value" } });
How do you use validation on model attributes?
- You need to implement the validation method in your model
- validate is called anytime the attributes are initially set.
- Validate
- attrs is a json object representing the models given attributes
- You can check if said attribute is set, etc.
validate: function(attrs) {
if (!attrs.title)
return ‘The song requires a title’;
}
How can you check if a model is valid? Which checks validate
model.isValid() // function returns true || false
If you call isValid on a model how do you get the last validation error message?
You call model.validationError on a model after you have called isValid that will be available
true or false - You can use inheritance to extend your custom models?
true
How do you extend you custom models?
Animal.extend() just like extend Backbone.Model
true or false - You cannot override a parent method on an extended class?
false
How do you override a parent method in an extend object?
Use the same method name and write new code.
How can you call the parent class method from a sub class?
Javascript doesn’t provide an easy way, but you can do…
ClassName.prototype.methodyouwantocall.apply(this)
What are the 3 persistence operators a backbone model has?
fetch() - GET
save() - POST/PUT - new POST, update PUT
destroy() - DELETE
How does Backbone know if it’s a PUT or a POST?
If it’s been fetched from the server before it’s a PUT, and if it hasn’t before then Backbone thinks it’s a new item and does a POST
What property do you use to tell models where to look on the server?
urlRoot: ‘/api/tasks’
What property is used to fetch a model from the database?
id: 1 when instantiating the model. var song = new Song({ id: 1 }) results in /api/songs/1 etc
true/false Backbone routes are restful by default?
TRUE
how would you do a PUT request to the server?
var song = new Song({ id: 1 }); song.fetch();
song. set(‘Title’: ‘Hello world’);
song. save();
api/songs/1 PUT request;
How would you create a new model and persist it?
var song = new Song();
song. set(‘Title’, ‘Hello world’);
song. save();
api/songs POST request persisting a new item.