DEV Community

JJohnson45
JJohnson45

Posted on

BackBone Js

Let's assume you're a skilled JavaScript front-end developer or just diving into the world of frameworks, you've definitely heard of Backbone.js. Backbone.js is a outdated but still useful and unique framework. This blog post is here to give you an insight on Backbone.js. After reading this guide, you should learn what this framework is, it's features and how to get started.

Backbone.js, often referred to as Backbone, is an open-source JavaScript library aimed to provide a structure to client-side web applications based on the Model-View-Controller (MVC) design pattern. This allows for communication between the client and server to be carried out through restful API's.

Web applications used to be static HTML pages and required programmers to change the HTML, CSS and JS code just to make its changes in the content. But with advancement of server-side programming languages, these static HTML pages have became dynamic. Therefore, most web applications use this approach today.

However, there is a main problem with this approach. It's the heavy use of JavaScript, that makes the application code extremely difficult to organize and maintain. That’s where Backbone.js fixes the problem. It provides developers a more organized approach to build JavaScript-heavy web applications.

Backbone models contain data for an application as well as the logic around this data. Models can be created by extending Backbone.Model

The initialize() method is called when a new instance of a model is created.

Model.get() provides easy access to a model’s attributes.

Model.set() sets a hash containing one or more attributes on the model. When any of these attributes alter the state of the model, a “change” event is triggered on it.

Backbone views are used to reflect what your applications' data models look like. They are also used to listen to events and react accordingly.
Views in Backbone don’t contain the HTML for your application.
Instead, they contain the logic behind the presentation of the data to the user. A view’s render() method can be bound to a model’s change() event. Allowing for the view to instantly reflect model changes without requiring a full page refresh.

Controller.extend() can be used to do class inheritance. So your controllers(collections) are able to share functionality from their parent controller(collections).

Collections have many methods suchAs:
add (model, collection, options)
remove (model, collection, options)
reset (collection, options)
sort (collection, options)

Backbone collections are simply an ordered set of models. Such that it can be used in situations such as;

Model: Student, Collection: ClassStudents
Model: Todo Item, Collection: Todo List
Model: Animal, Collection: Zoo
Typically your collection will only use one type of model but models themselves are not limited to a type of collection;

Model: Student, Collection: Gym Class
Model: Student, Collection: Art Class
Model: Student, Collection: English Class

Normally, when creating a collection you’ll want to define a property specifying the type of model that your collection will contain, along with any instance properties required.
Creating a backbone collection is similar to creating a model. We just need to extend the backbone’s collection class to create our own collection.
var HorseCollection = Backbone.Collection.extend({});

This collection will hold the Horse model we have created in our previous articles.

Specifying the model for a collection.

To specify which model this collection should hold, we need to specify/override the model property of the collection class.

var HorseCollection = Backbone.Collection.extend({
model: Horse,
});

Once we specify the model property of a collection what will happen internally is that whenever we create this collection, internally it will create an array of the specified models. Then all the operations on this collection object will result in the actual operations on that array.

Instantiating a collection.

A collection can be instantiated by using the new keyword. We can create an empty collection and then add the model objects to it later or we can pass a few model objects in the collection while creating it.

var collection1 = new HorseCollection();
//pre-populated collection
var Horse1 = new Horse({ color: Black, HorseName: "Tony" });
var Horse2 = new Horse({ color: Tan, HorseName: "Ralph" });
var collection2 = new HorseCollection([Horse1, Horse2]);

Adding items to the collection.

To add an item to a collection, we can use the add method on the collection.

var Horse3 = new Horse({ color: white, HorseName: "Ally" });
collection2.add(Horse3);
Now there might be a scenario where we actually want to update an existing added model in a collection. If that is the case, then we need to pass the {merge: true} option in the add function.

var horse3_changed = new Horse({ color: brown, HorseName: "Changed Horse"});

collection2.add(horse3_changed, { merge: true });

Also, if we want to add multiple models, we can do that by passing the model array in the add method.

var horse4 = new Horse({ color: black, HorseName: "Christina" });
var horse5 = new Horse({ color: brown, HorseName: "Meg" });
collection2.add([horse4, horse5]);

It is also possible to add the model at a specific index in the collection. To do this we need to pass the {at: location} in the add options.

var horse6 = new Horse({ color: white, HorseName: "riq" });
collection2.add(horse6, {at:0});

Removing models from collection
To remove the model from the collection, we just need to call the remove method on the collection. The remove method simply removes this model from the collection.
collection2.remove(Horse6);

Also, if we want to empty the model, we can call the reset method on the collection.

collection1.reset();
It is also possible to reset a collection and populate it with new models by passing an array of models in the reset function.

collection2.reset([horse4, horse5]); // this will reset the collection //and add horse4 and horse5 into it
pop and shift function can also be used to remove model from collection.

Finding the number of items in collection

The total number of items in a collection can be found using the length property.
var collection2 = new HorseCollection([horse1, horse2]);
console.log(collection2.length); // prints 2

Retrieving models from collection
To retrieve a model from a specific location, we can use the at function by passing a 0 based index.

var horseRecieved = collection2.at(3);
Alternatively, to get the index of a known model in the collection, we can use the indexOf method.

var index = collection2.indexOf(horseRecieved);
We can also retreive a model from a collection if we know its color or name. this can be done by using the get function.

var HorseFetchedbyColor = collection2.get(brown); // get the horse with color=brown
If we want to iterate through all the models in a collection, we can simply use the classic for loop or the each function provided by collections which is very similar to the foreach loop of underscore.js.

for (var i = 0; i < collection2.length; ++i) {
console.log(collection2.at(i).get("HorseName"));
}
collection2.each(function (item, index, all) {
console.log(item.get("HorseName"));
});

Oldest comments (1)

Collapse
 
piperymary profile image
Mary • Edited

Hey, thanks for sharing! If you're working as a backbone developer, you should know what the most common mistakes a backbone developer makes are.