Posts Tagged ‘backbone.js’


JavaScript Architecture: RequireJS Dependency Management

03.20.2012

Updated Aug 11, 2012 to reflect current library versions.

In JavaScript Architecture: Organization and Quality, we discussed the importance of breaking apps down into very small, decoupled pieces following the single responsibility principle. Small pieces are generally easier to comprehend than a mess of large peices.

Some devs coming from other languages feel like they can only build a few large, spaghetti JavaScript files for their app. I tend to think this may be caused by three reasons:

  • That’s the way JavaScript has been done in the past.
  • Loading many JavaScript files requires many HTTP requests resulting in longer load times.
  • Dependency management is hard in JavaScript.

Don’t stoop to these excuses. We can do better than that and today there are fantastic libraries and standards that can help us out. However, let’s see what the above problems mean. Continue reading »


JavaScript Architecture: Backbone.js Routers

02.29.2012

Updated Aug 11, 2012 to reflect current library versions.

In JavaScript Architecture: Backbone.js Views we discussed how to build dynamic apps that change views on the fly using JavaScript. Because view-switching is done without reloading the page or transferring control to a separate page, these are called single-page applications. Single-page applications pose a few issues we need to address:

  • When users hit their browser’s back button, they will be taken away from the app completely rather than back to a previous view within the app itself.
  • Users are only able to link to or bookmark the app itself–not a specific view within the app.
  • Deep views within the app may not be crawlable by search engines.

We want a great experience for our users. Successful apps behave as users would logically expect and users should feel like they can easily navigate back to where they were previously.

Like the topics we’ve addressed before, these issues aren’t specific to Backbone. It’s an issue that naturally arises in any single-page app. Fortunately, Backbone does a great job at addressing it and has a simple API. Continue reading »


JavaScript Architecture: Backbone.js Views

01.08.2012

Updated Aug 11, 2012 to reflect current library versions.

Tech-agnostic concepts

At this point of the series I really want to emphasize that the core concepts I’ve explained and will explain are not unique to Backbone; they’re unique to apps with state and dynamic views. I’m merely using Backbone as an illustration of a concrete tool that can be used to solve problems common to this type of app in general. The concept of “views” is no different.

What is a view?

If you’re coming from a different language or even a different library, you may be familiar with words like component, widget, or control. You can ask 10 engineers what they think those terms mean and you’ll likely get 10 different answers…or 30 if they think the terms are different from each other. The term view is just another one to throw on the pile and is equally ambiguous. It’s not all that unfortunate. Indeed, its usage can be quite flexible and its granularity disparate.

In the traditional web of requesting a new page for each section of a website, we may consider each page a view. Indeed, it is. In modern apps, it’s more common to have a single page and, as the user interacts with the page, portions of the page change. Those dynamic portions could likewise be called views. Within a dynamic portion of the page, there may be a toolbar that affects a list of customers. The toolbar could be considered a view. The list of customers could be another view. Each customer row inside the list of customers may be its own view. The row may contain a toggle button which is yet another view. The point is, in the Backbone world, the term view doesn’t necessary mean “a section of your website”. It can be, and oftentimes should be, much more granular than that. Continue reading »


JavaScript Architecture: Backbone.js Collections

01.04.2012

Updated Aug 11, 2012 to reflect current library versions.

Collections of items are amazingly pervasive in applications. Gmail deals with collections of emails. Twitter deals with collections of tweets. Facebook deals with collections of friends, updates, and apps. Very often these collections contain living data. The app may be constantly updating with new, changed, or removed items from the server. Maybe users are able to filter, sort, add, edit, or delete items and maybe they can do so from multiple views that need to be synchronized.

Usually when we think of collections of items in software terms with think of an array. Objects can be added and removed from an array easily enough but a native array on its own has no ability to broadcast notice of the change. Why do we care? Let’s say we’re building an RSS reader that shows the user a feed of articles from their subscriptions. The articles come from an array we loaded from the server. Each article contains a remove button next to it that allows the user to remove the article from the feed. Let’s also say in the top-right corner of the screen, separate from the feed of articles, we have a little counter that shows the user how many articles they currently have remaining in the feed. Assume that the feed has a JavaScript object managing it and the counter has a separate JavaScript object managing it.

When the user clicks a remove button to remove an article from the feed, it’s easy enough for us to remove the article from the feed itself and the accompanying array of articles, but how do we update the counter? The most direct approach is to give the feed view a reference to the counter view. That way the feed can just call a function on the counter view to tell it to refresh itself, right? Noooooooooo! Sure, it might function, but that’s a very good way to couple our views and reduce our flexibility. Our views would know more than necessary about each other. In this case, the data should drive the views instead of the views driving each other. Unfortunately, it’s difficult for our data (the array of articles) to drive the view using a native array because the counter can’t “watch” the array for a removal of an article. Native arrays do not broadcast events when items are added or removed.

You’ll notice a great similarity between what I’ve written above regarding native arrays resulting in view coupling and what I wrote in my previous post about native objects resulting in view coupling. Indeed, there are a lot of similarities and they are both resolved by implementing the observer pattern within our data structures. Just as a native object can be wrapped by a Backbone model in order to broadcast attribute changes, an array can be wrapped by a Backbone collection to broadcast additions and removals. Continue reading »


JavaScript Architecture: Backbone.js Models

12.26.2011

Updated Aug 11, 2012 to reflect current library versions.

Models contain the data or state of an application. Examples of a model would be a book, car, or customer. A book model would contain typical attributes of a book: title, author, genre, and publisher. A regular JavaScript object could contain this data like so:

var book = {
	title: 'A Tale of Two Cities',
	author: 'Charles Dickens',
	genre: 'historical',
	publisher: 'Chapman & Hall'
};

But this will soon present a problem. For illustration purposes let’s say you have view A that shows the book information and a separate view B where the user can change the book information. When the information is changed from view B, view A needs to know about it so it can update to show the new info to the user. Because our regular JavaScript object doesn’t have any way to notify view A of the change, view B would need a reference to view A so view B can call a method on view A telling it that the book object has been updated. Better yet, maybe we give view B event triggering powers and view A could just bind to view B’s events. Either way, these options should be frantically waiving red flags in your skull. Your views would now have to be aware of each other in at least one direction and that’s one direction too many. We want to free our views from the necessity of being aware of each other. Continue reading »


JavaScript Architecture: Backbone.js Events

12.23.2011

Updated Aug 11, 2012 to reflect current library versions.

Backbone.js is an MVC framework for JavaScript applications (although some legitimately argue it’s not technically MVC). Its purpose is to provide structure to your application so it can be modular, decoupled, and scalable. If you’re not sure why you may need an application framework, please read JavaScript Architecture: The Basics first. Backbone is not a dom manipulation utility, templating engine, or UI component library.

Backbone.js files and documentation can be found here or you can get involved with the source and community at GitHub. At the time of this writing, the unminified, documented code is only about 1,200 lines long so don’t be afraid to dig in and walk through the code itself. Heck, there’s even an annotated version.

Backbone.Events

At the heart of every RIA is the observer pattern (otherwise known as the publisher/subscriber pattern). The observer pattern is a design pattern that allows an object to be notified when another object has something to say, or in other words, has an event which it wishes to broadcast.

DOM elements (links, buttons, containers, etc.) already have the observer pattern natively baked in which is why you can watch for when a button is clicked without using libraries like Backbone or jQuery. However, there are times where we want our own JavaScript objects to trigger/dispatch events and we would normally have to write the implementation of this pattern ourselves. That’s where Backbone comes in. Backbone has this code for you in Backbone.Events. Continue reading »


JavaScript Architecture: Underscore.js

12.19.2011

Underscore.js, like jQuery, is a toolbox of utilities. Check out the website for a list of functionality it provides, but I’ll split it into two parts:

Array/Object/Function manipulation

As we create software is seems like we come in contact with the same patterns over and over. Usually, we end up re-writing them over and over as well. Take an array of user objects, each with a username property. We need an array of all the usernames from all the objects. So, like many times before, we create a new array to populate, create a for loop, snag the object at the current index, grab the username and push it into the array.

To me, that’s boring. It’s mundane. Underscore makes it fun again. With Underscore, we just use pluck():

var usernames = _.pluck(users, 'username');

Ah…concise, fast, and boilerplate is gone. Want to find all objects within an array that pass a specific test? Use the filter() function. Just want a reference to the first one that passes the test? Use the find() function. Want to retrieve the union of two arrays, that is, retrieve a single array of all unique objects contained within multiple other arrays? Try the union() function. Merge properties of multiple objects into a single object? Use extend().

Once you grasp the power of Underscore you’ll find yourself being more productive with less code while having more fun. Some have called it the bowtie for jQuery’s tux. I concur. Continue reading »