MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Backbone.js: View

In this article, we are going to learn about backbone view, one component which is responsible for how and what to display from our app. We will learn how to create our first app interface and see how a user can interact to our app using event delegation

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Introduction

We will use the same scenario in the previous article “Backbone.js: Getting Deeper into Model”. Assume we’re gonna build an image gallery app that using image as model, remember how to create model? sSimply create it by extending from “Backbone.Model”. Let’s refresh a bit.

Listing 1: Create Model

//create the model
	var ImageModel = Backbone.Model.extend({
		defaults: {
			title : ‘untitled’,
			description : ‘no description available’,
			owner: ‘Muhammad Azamuddin’,
			date: ’29 March 2013’
		}
});
//create a new single image
	var firstImage = new ImageModel();

Okay, we now have a single image based on the ‘ImageModel’. ‘firstImage’ will have all the defaults properties supplied by the model. That’s great, but this is just a data, There’s no way a user can see it because we haven’t created the app interface. This is when we need a backbone view to display those data in the model. how do we do that? See listing below.

Listing 2: Create View for Our Model

//create the model class
	var ImageModel = Backbone.Model.extend({
		defaults: {
			title : ‘untitled’,
			description : ‘no description available’,
			owner: ‘Muhammad Azamuddin’,
			date: ’29 March 2013’
		}
});
//create a new single image
	var firstImage = new ImageModel();
//create a view class
var ImageView = Backbone.View.extend({
	el: 'div#img', 
	initialize: function () {
		this.render();
	},
	render: function () {
		this.$el.html( this.model.get('title') ) ;
		return this;
	}
});
// create new view 
var firstView = new ImageView({model: firstImage});

After we define the model and create one instance, then we declare Backbone View class. We give name our view class as ImageView, inside it we have three properties, they are 'el', 'initialize', and 'render'. First and last property are View specific property which means you don't use it in Backbone Model nor Collection. While 'initialize' is just common method to call some function upon intantiation like we did beforehand on Model or Collection. So what do those properties defined actually do there? Let me explain it.

View.el

View.el tells the view, which element to use as the view referrence, wether they have been already created or not. In our example we refer to 'div' with id 'img'. If we want to create new element from non-existing we can use 'tagName' instead of 'el'. this.el is created from the view's tagName, className, id and attributes properties, if specified. If not, 'el' is an empty div.

View.initialize

A method that run upon instantiation of View. In our example we put render function inside it, so that the view automatically render once we create new instance.

$el

A cached jQuery object for the view's element. A handy reference instead of re-wrapping the DOM element all the time.

View.render

Backbone View provide render method for us to handle how and what to display in our view. Usually used together with template, but for the sake of this tutorial we only use straight-forward way of rendering. In our code, we simply place the title of the model inside view element (view.el) using jQuery API html(). Please keep in mind, we must always return this to enable chainning.

To use our view with model, we create new model based on ImageModel that is firstImage. Then we create our view instance, and pass firstImage as model like this, firstView = new ImageView({model : firstImage}). Passing model upon instantiation means we tell the view that it can use data from that model. That's why in our render methods (see again) we have “this.model.get('title')”. It's a way to retrieve title attribute from current model being used by view.

More Example

We have known the very basic of Backbone View, in our first code example we have covered 'View.el', 'View.initialize', as well as 'View.render'. Like I said instead of using 'el' we can use 'tagName'. So now let's see how we use it alongside another properties we might want to use.

Listing 3: More Backboe View Example

// Create Backbone View
var ImageView = Backbone.View.extend({
	tagName: 'li',
	className: 'img-item',
	events: {
		'click' : clicked,
		'dblclick' : edit,
		'click .hide' : hide
	},
	intialize: function () {
		this.render();
		this.listenTo(this.model, 'change', this.modify, this);
	},
	render: function () {
		this.$el.html( this.model.get('title') );
		return this;
	},
	clicked: function () {
		alert('you just clicked me');
	},
	edit: function (){
		alert('lets do edit');
	}
	hide: function () {
		alert('Im hidden, you are not supposed to see me now');
	},
	modify: function () {
	alert('the model has been modified');
	}
});

In above example we don't see 'el' anymore, we replace it by 'tagName'. Specify element you want to use as the value, the element doesn't necessarilly to be exist since backbone view will create it for us. And we use 'li' element in our example. The next property is 'className' which tells view to add class to the view element. From our example we give value of this property to 'img-item', so later our view when rendered will return list element with class of img-item like this '<li class=”img-item”>'. Please note, that 'View.el' or 'View.tagName' both available as this.$el, so in our render code we preserve the this.$el.

The next thing is event delegation, let's pick the event part from code above.

Listing 4: Event Delegation

events: {
	'click' : clicked,
	'dblclick' : edit,
	'click .hide' : hide
}

When talking about event in Backbone View you must understand this. You can delegate event in the scope of View element. Taking our example, we can only bind element inside our view.el that is <li class=”img-item”> and we can't reach outside element. See above code again, we have click .hide, that is when user clicking on element with class hide, then call the hide method. But, this only works to any element with class hide which is children or our view.el and not outside it. See below.

Listing 5: Event's scope

//index.html
....
<li class=”img-item”>Our first Image <span class=”hide”>hide</span></li>

<span class=”hide”>hide</span>
....

Using code above to better visualize what we are talking now, the first line of code is the result of our Backbone View. So if we click the 'span.hide' the Events delegation will work. But if we click 'span.hide' outside the scope of our view which is in the next line, the events will not get triggered.

Please see again the event delegation example, in the first two delegation we only write 'click' and 'dblclick' without providing further element to bind. If we do that, it the event will bound to the view element itself, in our example is 'li.img-item'. To handle what happen when certain event happens, we create the respective view mehtods like view.clicked, view.edit, view.hide in our example code.

We have also defined intialize function, but now in addition of this.render we also put another line of code to listen to an event outside the view. This line:

this.listenTo(this.model, 'change', this.modify, this);

That line will make our view listening for change event in its model then call modify method defined in the view and give the context of this view.

View.$(selector)

If jQuery is included on the page, each view has a $ function that runs queries scoped within the view's element. If you use this scoped jQuery function, you don't have to use model ids as part of your query to pull out specific elements in a list, and can rely much more on HTML class attributes. It's equivalent to running:

Listing 6: View Selector

view.$el.find(selector)
ui.Chapter = Backbone.View.extend({
  serialize : function() {
    return {
      title: this.$(".title").text(),
      start: this.$(".start-page").text(),
      end:   this.$(".end-page").text()
    };
  }
});

setElement

If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one.

Okay, That's a simple glance to Backbone view to help you get started, we will talk about using template engine later. Thanks for reading and see you later.



A passionate and visionary web developer who falls in love with web technologies. Always excited to learn more, just like you.

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login