Re-Learning Backbone.js – View Basics

There is probably more confusion with Backbone.js Views than with other features of Backbone. In this post I’m going to describe some basic features of Backbone Views. Also, In this post we will not be rendering any HTML, but I believe the concepts that you will learn will provide the bedrock for understanding Views better.

The end goal of a Backbone View is to represents an object in the DOM. Many times a view will be created that will manipulate an object that represents an element that is not originally assigned to the DOM. At some point the view object will be assigned to the DOM element and displayed.

A view usually builds up an element and adds it to the DOM. Here’s an example of what a view represents.

<div id="”movie1”" class="”movieItem”">
     Title: Happy Gilmore; Rating: PG; Year: 2008
</div>

This element would be built by the Backbone view and then added to the DOM.

It’s important to understand that once a view is added to the DOM, the view is still aware of that element in the DOM and can manage that element. So if events occur on the DOM element, such as click or keyUp, the view can be notified of these changes and take action. Also if a view references a model and the model changes, the view can be automatically updated and in-turn the DOM element will be updated to reflect the changes in the model.

“At a technical level, a Backbone view is simply a JavaScript object that manages a specific DOM element and its descendants.” http://aaronhardy.com/javascript/javascript-architecture-backbone-js-views/

“How does Backbone relate to “traditional” MVC?
Different implementations of the Model-View-Controller pattern tend to disagree about the definition of a controller. If it helps any, in Backbone, the View class can also be thought of as a kind of controller, dispatching events that originate from the UI, with the HTML template serving as the true view. We call it a View because it represents a logical chunk of UI, responsible for the contents of a single DOM element.”
http://backbonejs.org/#FAQ-mvc

I don’t want to overwhelm you with a lot of content, so I’m going to take very small step to explain some core features of Backbone views. Even though it’s our end goal, in these examples we will not assign a view to a DOM element. Everything will be logged to the browser console.


        var MovieView1 = Backbone.View.extend({
            //model: the Model is usually passed in through the initializer
            //tagName: use default - "div"
            //className: is static, dynamic or passed in through initializer - is empty by default
            //el: is static, created based on tagName, or passed in through initializer
            //container: this is a custom property which can be static, dynamic, or passed in through initializer

            initialize: function () {
                console.log("MovieView initialize");
                console.log(this.model);
                console.log(this.tagName);
                console.log(this.className);
                console.log(this.el);
                console.log(this.$el);
            }
        });

        $(function(){
            var movieView1 = new MovieView1();        
        })
</script>



First in this example we create a new class from Backbone.View. We override the initialize function. In the initialize function we log values to the browser console. My goal here is to show you what is available with a standard Backbone View.

We can see when an instance of MovieView1 class is created called movieView1 that the initialize function is called. We are logging model, tagName, className, el and $el to the browser console.

Understanding the term “this” is important. In the current implementation, “this” references the current view.

In this example we are not using a model, so the value will be undefined. Majority of the time, a model will be passed to the view in it’s created. We will see this done later.

The tagName is used to build the view “el” property. The “el” property represents the element that will be added to the DOM. The tagName is defaulted to “div” string.

The className is also used to build the view “el” property. By default the className is undefined.

In the code we can see that “this.el” represents an element with the tag “div”.

It is quite common to use jQuery to manipulate the “el” property. So, Backbone.js includes a property called “$el”. This is a shortcut for “$(this.el)”. Now you have the ability to us “$el” and have all the methods and property that jQuery would provide.

***********************************************************************************************



In this snippet of code, we can see that we assigned default values ot tagName and className. These default values are used to create the “el” property.

***********************************************************************************************

<script type="text/javascript">
        var Movie = Backbone.Model.extend({
            defaults: {
                rating: "NR"
            },

            initialize: function () {
                console.log("Movie Model created");
            }
        });

        var MovieView1 = Backbone.View.extend({
            //model:
            tagName: "span",
            className: "important",
            //el:
            //container:
            //myValue

            initialize: function () {
                console.log("MovieView initialize");
                console.log(this.model.get("title"));
                console.log(this.tagName);
                console.log(this.className);
                console.log(this.el);
                console.log(this.$el);
                console.log(this.myValue);
            },
        });

        $(function () {
            var movie = new Movie({ title: "Lion King" });
            var movieView1 = new MovieView1({ model: movie, tagName: "li", className: "critical", myValue:"Some Value" });
        })



Oh my, there’s a lot here. This is not as complex as it looks.

If you are not aware of how Backbone.js Models works please read my blog posting on Backbone Models. https://bardevblog.wordpress.com/2012/11/15/re-learning-backbone-js-models/

First we create a Movie class based on Backbone model. The Movie class has default values and overrides the initialize function.

Let’s skip to the bottom where the Movie class is instantiated. We instantiate a Movie class called “movie” and passed in the title “Lion King”. Next we create a movie view and provide values for model, tagName, className and myValue.

In the results we can see that the movie model that we passed-in is assigned the to the property “model”. We can also see that tagName and className are also assigned to properties with in the view. But, myValue did not get assigned to the property in the View. Only ‘model’, ‘collection’, ‘el’, ‘id’, ‘attributes’, ‘className’, and ‘tagName’ will automatically be merged to the view. myValue will need to be accessed a different way. We will see this next.

***********************************************************************************************



In this example we added options to the initialize function. Now we can reference custome values that are passed-in during the initialization.

***********************************************************************************************

Let’s pass in a value for “el” during the creation of the view

<div id="container-movie"></div>

        $(function () {
            var movie = new Movie({ title: "Lion King" });
            var movieView1 = new MovieView1({
                model: movie, tagName: "li", className: "critical", myValue: "Some Value",
                el: $("#container-movie")
            });
        })







I added a HTML “div” element to the body. When I created the new movieView1 object, I passed in a reference to the new “div” element that I created. This reference is assigned to the “el” argument.

As we can see, the “el” property of the view was assigned a reference to the “div” that was passed in through the initialization. The tagName and className did not have any effect on the “el” property. Since the “el” was assigned during creation of the movieView1 object, tagName and className was ignored.

In the next post we will start rendering views.

Advertisement
This entry was posted in Backbone.js, JavaScript, Tutorial and tagged . Bookmark the permalink.

4 Responses to Re-Learning Backbone.js – View Basics

  1. Shahriar says:

    Rock on.
    Love the way you describe everything.

  2. mariano says:

    Hi! i’m following this tutorial, but i’m stuck with the following:
    When i try to use console.log(this.$el), it doesn’t find anything (it throws me an “undefined”), however, if i use $(this.el) -which this.$el is a short for-, it works just fine (!!)
    I’m using the backbone library that you use on the “simple example” of this tutorial (version 0.5.3), with jquery 1.7.2 and underscore v. 1.2.3.
    Any ideas? Here’s my code

    var Movie = Backbone.Model.extend();

    var MovieView1 = Backbone.View.extend({
    initialize: function () {
    console.log(“MovieView initialize”);
    },
    render: function () {
    console.log(“MovieView render”);
    // this.$el.append(“Title: ” + this.model.get(“title”));
    $(this.el).append(“Title: ” + this.model.get(“title”));
    $(“#container-movie”).html(this.$el.html());
    return this;
    }
    });

    $(function(){
    var movie = new Movie({ title: “Lion King” });
    var movieView1 = new MovieView1({ model: movie });
    movieView1.render();
    })

  3. Joel Deehr says:

    Thanks for the great explanation. I have been developing in backbone for the last week at work, but mostly just mimicking code from other devs while not knowing what I was doing. This is a great post!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s