Prototypal Inheritance & Extension
Most used pattern in Backbone (in the examples)
Backbone constructors are often called classes, even if there are no classes in JavaScript (until ES6...)
Typical Backbone pattern:
var BookModel = Backbone.Model.extend({...});
var book = new BookModel({
title: "The Long Goodbye",
author: "Raymond Chandler"
})
This is how you crate a "class" in Backbone. In the
extend
method you can pass extra properties not defined in the base Backbone model that will be "inherited" by all instances (terminology here is not correct for JavaScript: these properties will be referenced by new Objects).Then you can further extend these models:
var BiographyModel = BookModel.extend({...})
Constructor vs instances
Constructors describe the "ingredients" of your application before it's being used. These are the core Backbone classes. You can extend them and create new instances of those constructors with the
new
keyword.Constructor/initialise
You can do it on every Backbone class, it's universal
Models, collections, view, router
You can "override" (extend) the constructor
var View = Backbone.View.extend({
initialize: function(){
console.log("hello world");
}
});
var view = new View();
// => "hellow world"
Override a constructor
var CommentModel = Backbone.Model.extend({
constructor: function(){
this.author = new UserModel();
// calling the parent constructor:
Backbone.Model.apply(this, arguments);
}
});
Event system
Present on all Backbone objects
Synchronous event system
Backbone.one("authenticated", function(){
console.log("user logged in");
});
Backbone.trigger("authenticated");
// => "user logged in"
Synchronous: all event handlers will be invoked and run before the next line in the code.Easier with race conditions.
You have to bind the event handlers before the event happens.