Backbone is a lightweight library for structuring JS code. It operates under the MVC design framework.
MVC promotes separation of concerns to create easily extendible and loosely couple application while keeping code maintainable code
- Backbone Components:
-
- Events: Ability for an object to pub/sub events
-
- Models: Application state
-
- Collections: A set of Models
-
- Views: Render models and listen for DOM/model events
-
- Routers: To create SPAs
Models:
- Containers for application data
- JS objects with changing tracking mechanism and pub/sub and ajax request to server
person.save({ success: () => {}})
- When a model is created
new Model() Backbone automatically calls model.initialize() method
- Backbone Models are hash maps.
- Must use
.set when setting Model attributes
- Read with
.get
- Delete with
.unset
- Delete all with
.clear
- Get a JSON with
.toJSON
- Check for attribute existence with
.has
- When instantiating the model can use
.defaults object to set default value for attributes
.validate() method called whenever attributes are set on a model ... must return undefined or string if not valid; method is passed model.attrs as a parameter
var Song = Backbone.Model.extend({
validate: function (attrs) {
if (!attrs.title) {
return "Title is required";
}
},
});
Inheritance from a Parent model can be done via the var Child = Parent.extend() method on the Parent class