Re-Learning Backbone.js – Multiple Views

In this post we will learn about how a view can monitor changes or events in other views. A common scenario is to display a list of items. When the user clicks an item from the list, the details of the item is displayed in a different view on the same page. The user can then edit and save the details back to the list.

In this example we will have a list of movies. When the user selects a movie from the list, the data for the movie will be populated in text boxes, which is in a different view. Once the user changes the data and clicks “Change Record” button the changes will be updated back to the list.

The fundamental concept to understand is that the child movie view is not aware of the detail movie view. Neither one of the views are aware of the other. This is important because it decouples the views; it allows us to remove or exchange views without modifying other views.

In a previous post Re-Learning Backbone.js – Events (Pub-Sub) we learned about PubSub in isolation. In this post we will use PubSub to notify the triggering of events when a change occurs in a view.
Continue reading “Re-Learning Backbone.js – Multiple Views”

Re-Learning Backbone.js – Nested Views

Previously in this series we have learned about views and collection. Now lets learn about creating nested views based on a collection.

Most if not all of the concepts learned in the previous Re-Learning Backgone.js tutorials will be used in this blog post. As in previous posts, we will start-off very simple and take very small steps to get to our end goal. The reason to take all these steps is to make sure each addition to our solution works. This will be a 7 part post.

For this post our end goal is to create a very simple list of movies. Each individual movie displayed will be managed by an individual Backbone view. There will be another view that creates and manages the child views. I have bigger plans than this, but first wanted to do something simple.


Continue reading “Re-Learning Backbone.js – Nested Views”

Re-Learning Backbone.js – Events (Pub-Sub)

Since we are here to learn about Backbone.js, we are going to use the built in feature of Backbone called Events. Backbone.js Events is a feature that provides a Pub-Sub. As usually I’m going to attempt to keep this a simple as possible. To provide a basic understanding of Pub-Sub, we will not work with views, models or collections; we will only work with Backbone Event. My goal is to keep this extremely simple, and the concepts that you learn here can assistance you when build more complex, maintainable, extensible, flexible, and plus other bilities websites.

Below is an example of a protypical webpage. In a webpage like this, anytime the user does an action on the webpage, such as login, search, sort and other other action, the page refreshes. One reason we are learning Backbone.js is so that we can provide a better experience to the user by providing single page applications (SPA).

If we created an application like the following with Backbone.js, there could be many views (items in red boxes). In a webpage like this, the developer my define in code that the Search view is aware of the Movie List view, or the Login view is aware of the Recommendation view. For example, if the user logs-in, the Login view will directly notify the Recommendation view of the login. This is fine for simple SPA. But if this is done on a complex website like Trello, which is created with Backbone.js, maintainability and extensibility and other bilities may become an issue.

For example, what happens if management wants to replace the Recommendation view with a new Friends View. Now the developer must change the code in the Login view to update the Friends view. In this example the developer has tightly coupled the Login view to the Recommendation view. Probably not the best decision the developer has made.

Here’s a few quotes:

“Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically” Gang of Four book on Design patterns

“Publishers are loosely coupled to subscribers, and need not even know of their existence. With the topic being the focus, publishers and subscribers are allowed to remain ignorant of system topology. Each can continue to operate normally regardless of the other. In the traditional tightly coupled client–server paradigm, the client cannot post messages to the server while the server process is not running, nor can the server receive messages unless the client is running. Many pub/sub systems decouple not only the locations of the publishers and subscribers, but also decouple them temporally. A common strategy used by middleware analysts with such pub/sub systems is to take down a publisher to allow the subscriber to work through the backlog (a form of bandwidth throttling).” WikiPedia – http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern

“The general idea behind the Observer pattern is the promotion of loose coupling (or decoupling as it’s also referred as). Rather than single objects calling on the methods of other objects, an object instead subscribes to a specific task or activity of another object and is notified when it occurs. Observers are also called Subscribers and we refer to the object being observed as the Publisher (or the subject). Publishers notify subscribers when events occur.” Addy Osmani – http://msdn.microsoft.com/en-us/magazine/hh201955.aspx

This is somewhat techno babble, but once you understand the Pub-Sub or Observer pattern, these definitions make a lot of sense. It doesn’t help out a lot here, but hopefully we get you to the point where these definitions do make sense.

So forget about the example above. We are going to use a simpler example. Lets assume we have a security system. The security system is made-up of 3 key parts: a door (publisher), control panel (hub), and customer service (subscriber). Anytime the door (publisher) opens, the customer service (subscriber) will be notified. But we don’t want to tightly couple these objects together. We needed a mediator that manages the subscribers and the publishers, and this is where the control panel (hub) comes in.
Continue reading “Re-Learning Backbone.js – Events (Pub-Sub)”

Re-Learning Backbone.js – Collections

Backbone.js collections are used to store and manage a group of similar or related objects. If all we wanted to do was store related objects we could use a JavaScript array, but Backbone.js Collection provides an infrastructure that allows us to manage the set of data more effectively and efficiently.

As usual, I will attempt to keep the sample very simple. We will focus on collections, but we will need the assistance of models in this example.

In the following example we are creating 2 models and adding them to a collection.



    
    
   	
	


    
  
Close Bitnami banner

In the first section of the code we declare a Movie model class. There’s nothing special here.
Continue reading “Re-Learning Backbone.js – Collections”

Re-Learning Backbone.js

In 2011 and in early 2012, I did an extensive amount of work with Backbone.js. I believe I was fairly competent with the technology and grew very fond of Backbone.js. During this time I created a blog post on Backbone.js, “Understanding Backbone.js – Simple Example”. Based on comments, this post did help a few individuals. Sometime around March my priorities changed and since then I’ve done very little client side development.

In November I started back doing client side development. I researched the different MV* frameworks and settled on using Backbone.js again. While I understood the concepts of MV* frameworks and Backbone.js, some of the details of the technology I could no longer recalled. Programming is definitely not riding a bike.

Since I was doing this on my own time, I didn’t have any deadlines or anyone I reported to. So I decided to re-learn Backbone.js from scratch.

When I wrote my first blog post on Backbone.js, I had many months of experience with the technology. I tried to create a very simple tutorial, but anyone who has no knowledge of Backbone.js would have a difficult time understanding some of the concepts. It’s amazing how well some authors can convey a concept at a beginner’s level about subjects that they are experts in. I know others that are extremely brilliant, but when they discuss a concept to someone who has little knowledge about the topic, they have a very difficult time explaining it. There are concepts that I know that I take for granted, and trying to explain these concepts at an elementary level is not easy. Many times when explaining something there are multiple concepts that need to be understood, and each concept needs to be understood to understand the other concepts. In the “Understanding Backbone.js – Simple Example” blog post, I took for granted that the readers understood certain concepts. The post I wrote was not short, and if I didn’t make these assumptions about the reader, the post would have been much longer.

Now that I’m re-learning Backbone.js, I thought this would be a great opportunity to provide others the basic concepts of Backbone.js. I have made assumptions that readers do have a basic knowledge of JavaScript and jQuery.

I have already been through the trials and tribulations of working with JavaScript in complex application. I then started to use jQuery. jQuery helped out, but did not solve for many of the complexities of the application. I had experience with MVC frameworks on the server side, and started reading about the different MV* frameworks on the client side. Eventually I decided to use Backbone.js. It would be nice if I could give you all the reasons I decided on Backbone.js, but this was a maturation process that would be very difficult to recall. With that in mind, I also make the assumption that readers have a basic understanding of MV* frameworks and the reasoning to use one and why the reader has decided to use Backbone.js.

Up to this point I have now written 7 posts in regards to re-learning Backbone.js and hopefully there will be more to come. This has been a lot of fun. With writing these posts I have learned much more than I would have otherwise learned. I hope these posts help others to learn Backbone.js and be more proficient.

It’s amazing the number of kind comments that readers provided to the post “Understanding Backbone.js – Simple Example”. Even though I’m not a sentimental person, these comments do provide me great appreciation that others benefited from the post. Please keep the comments coming. I am thankful for them and they keep me writing about topics I enjoy.

Below are my posts on Backbone.js. I plan to keep this list up to date on topics about Backbone.js.

 

 

Please enjoy

Re-Learning Backbone.js – View Events

It is common for Backbone.js views to include elements that the user can interact with. For example, the user can enter text in a text box, hover over a div, or click a button. These types of interaction can trigger events. If a Backbone.js view is bound to these events, then the view can react to these events. Reaction to these events could be validating data, displaying a message box, or saving or updating data in the model.

While we learning about Backbone.js view events, we will keep it very simple. In the following example we will not have templates or models, we will be working with a very simple view. In this example we will bind an input textbox key-up event to a view’s function. Whenever the user presses a key, an event should be triggered and a function should be called to log the value of the textbox to the browser console.



    
    
   	
	


    
Title:
Close Bitnami banner


Continue reading “Re-Learning Backbone.js – View Events”

Re-Learning Backbone.js – Binding Models to Views

In the previous post we learned about Model Binding in isolation. There are many places where model binding can provide benefit. Where we see model binding the most is in relation to using views. Usually we want the view to depict those changes in the model. In this post we will bind a model to a view.

In the following example the view will be updated when the model changes.



    
    
   	
	


    
Close Bitnami banner


Continue reading “Re-Learning Backbone.js – Binding Models to Views”

Re-Learning Backbone.js – 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. In the previous two blog posts we learned about Bakbone.js Views, but our views did not track models and were not update when the model changed.

In this post we will learn the basics about binding models events. I do not want to overly complicate the situation, so we are going to learn about Backbone.js Model Binding Events in isolation. We will not be using views in these examples, but the knowledge we do gain here will be applied in the next blog post about views monitoring changes in models

In this example whenever the model’s data changes, the function movieChanged will be called.



    
    
   	
	


    
  
Close Bitnami banner


Continue reading “Re-Learning Backbone.js – Model Binding Events”

Re-Learning Backbone.js – View Render

In this post we learn about different ways to render HTML using Backbone.js view and Underscore templates.

A Backbone view should include a render function. The render function should have the responsibility of manipulating the view’s el property. The el property is then used to update the DOM.

This post builds on the following posts:
Re-Learning Backbone.js – View Basics
Re-Learning Backbone.js – Templates (Underscore)
Re-Learning Backbone.js – Models
 

Here are a couple of quotes about Backbone.js Views:

“Backbone views are almost more convention than they are code — they don’t determine anything about your HTML or CSS for you, and can be used with any JavaScript templating library. The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page. Instead of digging into a JSON object, looking up an element in the DOM, and updating the HTML by hand, you can bind your view’s render function to the model’s “change” event — and now everywhere that model data is displayed in the UI, it is always immediately up to date.” http://backbonejs.org/#View

“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/

In this first example we are going to add some text to a DOM div element.



    
    
   	
	


    
Close Bitnami banner


Continue reading “Re-Learning Backbone.js – View Render”

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.

Title: Happy Gilmore; Rating: PG; Year: 2008

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();        
        })

Continue reading “Re-Learning Backbone.js – View Basics”