• Skip to content
  • Skip to primary sidebar

Developers Tips & Tricks

You are here: Home / BackBone JS / Setting up Working Environment for Backbone.js

Setting up Working Environment for Backbone.js

17 marzo, 2016 by MPezzolano

BackboneJS has a hard dependency on Underscore.js and a soft dependency on Jquery. So, the following components are required to start working with BackboneJS:

  1. Backbone.js
  2. Underscore.js (>=1.4.3)
  3. Jquery (>=1.7.0)

So, after having all these prerequisites we will test if it has been set up properly by writing our first BackboneJSDemo.html file such as below:

<html>
<head>
 <meta charset="utf-8">
 <title>BackboneJS Tutorial</title>
 </head>
<body>
<script src="underscore.js"></script>
 <script src="jquery.js"></script>
 <script src="backbone.js"></script>
<body>
<html>

Understanding BackboneJS

Like many other libraries, Backbone is also one of the most prominent JavaScript libraries. It provides proper structuring to web applications with its most robust components. BackboneJS is gaining special attention due to the following attributes:

  • It is simple and easy to use
  • It is a light weight framework
  • It is of object oriented Nature
  • It provides structure to JavaScript that makes it easy to understand

Major Components of BackboneJS:

BackboneJS consists of different components that we will be discussing in detail below. The major components of BackboneJS are:

  1. Views
  2. Events
  3. Models
  4. Collections
  5. Routers

BackboneJS Views:

BackboneJS Views are used to reflect how our application model data will look like. They are also used to listen for different types on events based upon JavaScript selectors and act accordingly based upon the type of event fired. The sample code below describes how we can use views to render application’s model data:

var BackbonejsView= Backbone.View.extend({

el: $('body'), // attaches `this.el` to an existing element.

//The initialize function is always called when instantiating a Backbone View.
 initialize: function(){
 _.bindAll(this, 'render'); // every function that uses 'this' as the current object should be in here
 this.render();
 },

render: function(){
 $(this.el).append("<ul> <li>Welcome to backboneJS JavaScript Library</li> </ul>");
 }

 });

//Instantiating Application View
var listView = new BackbonejsView();

So, the above example simply shows that how the BackboneJS Views are used. For more details regarding BackboneJS Views please refer: BackboneJS Views in Detail

BackboneJS Models:

Models are the heart of any JavaScript application. BackboneJS Model is basically a Java Script object, i.e. key-value pairs used to represent our application data which can be created, validated with respect to specified constraints, saved to the server and destroyed. Models provide basic set of functionality to handle event triggering, persistence, etc. The following example elaborates on how we can use models in our application:

var Employee = Backbone.Model.extend({
defaults: {
name: 'John',
address: 'Street 5'
 }
});

BackboneJS Collections:

BackboneJS Collections can be simply defined as a container which maintains the list of BackboneJS Models in an organized way.

var EmployeesList = Backbone.Collection.extend({
//Specifying the model class that the collection contains. Employee model has already been created in BackboneJS Model Section.
model: Employee
 });
//Initializing Collection
this.collection = new ExployeesList();
//Adding Object in Collection
this.collection.add(employee);
//Iterating Whole Collections
 _(this.collection.models).each(function(employee){
    //Processing fetched object from collection
 }, this);

BackboneJS Routers:

Not heard about word routers before? Well, Routers were previously called controllers, before they got a change of name in BackboneJS version 0.5. So, Routers are basically a mechanism to route client side pages and connect them to events and actions through URLs. So if you want to make reference to certain state or location of a web application you need it. Consider the following example to understand how we can use them:

var Workspace = Backbone.Router.extend({
 routes: {
 "help": "help", // #help
 "search/:query": "search", // #search/kiwis
 "search/:query/p:page": "search" // #search/kiwis/p7
 },
 help: function() {
 ...
 },
 search: function(query, page) {
 ...
 }
});

BackboneJS Events:

Events are one of the strong component of BackboneJS. Events are used to create a relationship between your application and browser features. Furthermore, It gives the ability to perform some action on happening something to object.

We will be understanding Events by discussing its usages in different scenarios with examples.

BackboneJS DOM Events

All jQuery Events are valid for BackboneJS to bind. To use BackboneJS Events you need to define an attribute named “events” into your views with the following syntax:

“event css-selector” : “function”

Where event is the kind of Event that you want to handle/listen, then you need to add a blank space and use a css selector (as you do with jQuery), but remember that the scope of the bind will include only those elements that belongs to your View. function is a name of a method of your view, and must be passed as string.

Let’s Consider an example to understand this thoroughly:

var EmployeeView= Backbone.View.extend({

el: $('body'), // el attaches to existing element

//So, Here we are binding events on adding each employee. Whenever DOM object with id 'addEmployee' will be clicked a new employee record will be added and 'emplyeeAdded method will be called.

events: {

click #addEmployee: 'employeeAdded'
},

initialize: function(){
 _.bindAll(this, 'render', 'empoyeeAdded');

this.counter = 0; // total number of employee added so far
 this.render();
 },

//render() now introduces a button to add a new employee on which we have binded an event above

render: function(){
 $(this.el).append("<button id='addEmployee'>Add list item</button>");
 $(this.el).append("<ul></ul>");
 },

//Function that will be called each time a new employee will be added
empoyeeAdded: function(){
 this.counter++;
 $('ul', this.el).append("<li>Employee Added with id: "+this.counter+"</li>");
 },

});

var employeeView= new EmployeeView();


Here you can have All Possible Events Categories for detailed understanding of Events Usages.

We can also bind events on objects level as well, such as:

events: {
'click' : 'confirmation'
 }

confirmation: function(){
 alert("Employee Added Successfully...!!!");
}

Model Binding Events

Usually a view tracks a model, and when the data in the model changes the view is updated to represent the changes. But our views did not track models and were not updated when the model changed. So, we will have to track changes to the models so that we may change our models too accordingly. Hence here the role of bindings events to our models comes into play. So, we will be attaching events with change of our models which will invoke methods to change our view as well accordingly.

Let’s consider an example about how can we bind events to model and change the views accordingly whenever there is any change in the model:

 

//Here we have Employee Model
var Employee = Backbone.Model.extend({
 defaults: {
name: 'BAY',
gender: 'male'
 }
 });

//Collection of Employees
var EmployeeList = Backbone.Collection.extend({
 model: Employee
 });

//In our initialize method we will bind events to change in models
initialize: function(){

 _.bindAll(this, 'render', 'unrender'); // every function that uses 'this' as the current object should be in here

//Binding for events whenever any model object will be changed, to change view also
this.model.bind('change', this.render);

//Binding for events whenever any model object will be removed, to change view also
 this.model.bind('remove', this.unrender);
 }

//This method will update the view when model object will  be removed
 unrender: function(){
 $(this.el).remove();
 }

//To update the view when model object will be changed to show the updated values
 render: function(){

 $(this.el).html('<span style="color:black;">'+this.model.get('name')+' '+this.model.get('gender')+'</span>');
 return this; // for chainable calls, like .render().el
 },

 



Filed Under: BackBone JS, HTML5, JQUERY Tagged With: collections, events, javascript, models, routes

Primary Sidebar

Categorías

  • Angular JS (10)
  • BackBone JS (6)
  • Ember JS (2)
  • Express JS (4)
  • EXTJS (1)
  • General (7)
  • GIT (3)
  • Grunt JS (2)
  • HTML5 (8)
  • JAVA (5)
  • JavaScript (14)
  • JQUERY (15)
  • JSON (1)
  • JSP (1)
  • Knockout JS (2)
  • LARAVEL (13)
  • Linux (2)
  • Mobile Angular UI (1)
  • Modulus.io (1)
  • MongoDB (5)
  • MySQL (3)
  • NodeJS (11)
  • PHP (1)
  • Polymer (3)
  • PostgreSQL (1)
  • Prism.JS (1)
  • PYTHON (10)
  • QOOXDOO (1)
  • React JS (7)
  • Redis (2)
  • Sin categoría (6)
  • SQL (1)
  • TWIG (4)
  • UnderScore (1)
  • Web Services. (2)
  • Wordpress (1)

Cloud Tags

Angular JS BackBone JS Ember JS Express JS EXTJS General GIT Grunt JS HTML5 JAVA JavaScript JQUERY JSON JSP Knockout JS LARAVEL Linux Mobile Angular UI Modulus.io MongoDB MySQL NodeJS PHP Polymer PostgreSQL Prism.JS PYTHON QOOXDOO React JS Redis Sin categoría SQL TWIG UnderScore Web Services. Wordpress

Copyright © 2023 · Genesis Sample Theme on Genesis Framework · WordPress · Log in