Showing posts with label Backbone JS. Show all posts
Showing posts with label Backbone JS. Show all posts

Sunday, 27 November 2016

Communication between Backbone Views

There are few ways to communicate between two backbone views and model.
Consider an application contains Menu view and you want to update the application area based on the menu selection.
For example, consider an e-commerce application which contains the following views.
1. MenuView
2. Recharge View
3. Shopping View
4. Book Ticket View

For this the very basic approach or the easiest way is that creating the object for all other three views in MenuView. But by doing this, all views are tightly coupled with one another.
To overcome this we’re going to use Event aggregator pattern. 
Backbone provides Router concept for event aggregator.

In index.html we’ve included all the html templates.

index.html


 


After that, related Backbone view files are created with the basic information.

MenuView.js

var MenuView = Backbone.View.extend({
 
 model : new MenuModel(),
 initialize : function(){
  
 },
 events : {
  
 },
 render : function(){
  var menuTemplate = _.template($('#menu-template').html());
  this.$el.html(menuTemplate(this.model.toJSON()));
  return this;
 }
});


RCView.js

var RCView = Backbone.View.extend({
 el: '#contentArea',
 initialize : function(){
  
 },
 
 events : {
  'click #rcSubmitButton':'doOnRCSubmitButton'
 },
 render : function(){
  var rcTemplate = _.template($('#recharge-template').html());
  this.$el.html(rcTemplate(null));
  return this;
 },
 
 doOnRCSubmitButton : function(){
  alert("RC click!!");
 }
});
As of now, views are containing only the render part which renders the corresponding template into the application area.

We’ve defined three links in the index.html menu area. For every menu item, there are independent actions. The event should be passed to corresponding views without any dependency. For this purpose we’ve created the router in the main.js file. Once the routes and its functions are defined, for all the menu selection it’ll redirected to its route.

main.js

$(document).ready(function(){
 var menuView = new MenuView();
 menuView.setElement($('#menuArea'));
 menuView.render();
 new MyRouter();
 Backbone.history.start();
});

var MyRouter = Backbone.Router.extend({
 routes : {
  "recharge":"onRecharge",
  "bookticket" : "onBookTicket",
  "shop":"whileShopping"
 },

 viewFactory : function(){
  return{
   rcView : typeof rcView == 'undefined' ? new RCView() : rcView,
   ticketView : typeof ticketView == 'undefined' ? new TicketView() : ticketView,
   shopView : typeof shopView == 'undefined' ? new ShopView() : shopView
  };
  
 },
 onRecharge : function(){
  this.viewFactory().rcView.render();
 },
 
 onBookTicket : function(){
  this.viewFactory().ticketView.render();
 },
 
 whileShopping : function(){
  this.viewFactory().shopView.render();
 }
});



You can download this working sample in this Github URL.

Reference for event aggregator pattern :  http://martinfowler.com/eaaDev/EventAggregator.html

Wednesday, 19 October 2016

Backbone JS Simple Application

BackboneJS is a light weight JavaScript library that allows to develop and structure client side applications that run in a web browser. It offers MVC framework which abstracts data into models, DOM into views and bind these two using events.

This example illustrates the Simple Backbone JS application.

The main components of Backbone JS we’ve used here are :
1. Backbone View
2. Backbone Model

At first, we need to include the scripts needed for Backbone JS in the Html file. Underscore JS is the only hard dependency for the Backbone JS.

We can include any other JS libraries if it is necessary. Here we’ve included JQuery which is common.
Let’s look at the "index.html" file. It’s a very basic well known div element with username and password.
As of now, we’ve not separated HTML View part in a different file.

index.html

 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
 <title>Backbone Tutorial ONE</title>  
 <script src="js/libs/jquery.js"></script>  
 <script src="js/libs/underscore.js"></script>  
 <script src="js/libs/backbone.js"></script>  
 <script src="js/UserView.js"></script>  
 <script src="js/UserModel.js"></script>  
 <script src="js/main.js"></script>  
 <div id="appArea">  
 <label for="userNameText">Enter User Name :</label><input type="text" id="userNameText">  
 <label for="passwordText">Enter Password :</label><input type="password" id="passwordText">  
 <button id="submitButton">Submit</button>  
 </div>  

Now, create a Backbone View named “UserView.js” for this screen. In the UserView.js file, we’ve added the events and we do have initialize method. Blur event listener added for userNameText field.

UserView.js

 var UserView = Backbone.View.extend({  
  events : {  
  'blur #userNameText':'onUserNameBlur',  
  'click #submitButton':'onSubmit'  
  },  
  onUserNameBlur : function(e){  
  var value = $(e.currentTarget).val().trim();  
  $(e.currentTarget).val(value);  
  },  
  render : function(){  
  //Empty implementation  
  },  
  onSubmit : function(){  
  var userModel = new UserModel();  
  userModel.set("userName",$('#userNameText').val());  
  userModel.set("password",$('#password').val());  
  userModel.save({  
   success : function(response){  
   alert("Success");  
   },  
   error : function(response){  
   alert("Error");  
   }  
  });  
  }  
 });  

In the "UserModel.js" file, just simply added two parameters with userName and password.

UserModel.js

 var UserModel = Backbone.Model.extend({  
  initialize : function(){  
  },  
  defaults : {  
  userName : '',  
  password : ''  
  },  
  url : 'http://localhost:8080/backbone/login'  
 });  

So now we’ve a html file, a Backbone View file and a Backbone Model file. Now we need to execute the methods in UserView.js. In Backbone, events will bind for the elements only in the “el” element.
There are two ways to set el element. Either we can set el : “elementId" or else we can set the element by calling the setElement method. In this example, setElement method is used.

main.js

 $(document).ready(function(){  
  var userView = new UserView();  
  userView.setElement($('#appArea'));  
 });  

Now the el element is set to appArea. So events are binded with those elements.
If Submit button is clicked, onSubmit function will be triggered and Backbone Model will be triggered.

You can download this sample in the following URL. Github