We're going to use Sinatra in a similar manner to how we used Express in the last chapter. It will power a RESTful API supporting CRUD operations. Together with a MongoDB data store, this will allow us to easily persist data (todo items) whilst ensuring they are stored in a database. If you've read the previous chapter or have gone through any of the Todo examples covered so far, you will find this surprisingly straight-forward.
Remember that the default Todo example included with Backbone.js already persists data, although it does this via a localStorage adapter. Luckily there aren't a great deal of changes needed to switch over to using our Sinatra-based API. Let's briefly review the code that will be powering the CRUD operations for this sections practical, as we go course won't be starting off with a near-complete base for most of our real world applications.
If using OSX or Linux, Ruby may be one of a number of open-source packages that come pre-installed and you can skip over to the next paragraph. In case you would like to check if check if you have Ruby installed, open up the terminal prompt and type:
$ ruby -v
The output of this will either be the version of Ruby installed or an error complaining that Ruby wasn't found.
Should you need to install Ruby manually (e.g for an operating system such as Windows), you can do so by downloading the latest version from http://www.ruby-lang.org/en/downloads/. Alternatively, (RVM)[http://beginrescueend.com/rvm/install/] (Ruby Version Manager) is a command-line tool that allows you to easily install and manage multiple ruby environments with ease.
Next, we will need to install Ruby Gems. Gems are a standard way to package programs or libraries written in Ruby and with Ruby Gems it's possible to install additional dependencies for Ruby applications very easily.
On OSX, Linux or Windows go to http://rubyforge.org/projects/rubygems and download the latest version of Ruby Gems. Once downloaded, open up a terminal, navigate to the folder where this resides and enter:
$> tar xzvf rubygems.tgz
$> cd rubygems
$> sudo ruby setup.rbThere will likely be a version number included in your download and you should make sure to include this when tying the above. Finally, a symlink (symbolic link) to tie everything togther should be fun as follows:
$ sudo ln -s /usr/bin/gem1.8.17 /usr/bin/gem
To check that Ruby Gems has been correctly installed, type the following into your terminal:
$ gem -vWith Ruby Gems setup, we can now easily install Sinatra. For Linux or OSX type this in your terminal:
$ sudo gem install sinatra
and if you're on Windows, enter the following at a command prompt:
c:\\ > gem install sinatra
As with other DSLs and frameworks, Sinatra supports a wide range of different templating engines. ERB is the one most often recommended by the Sinatra camp, however as a part of this chapter, we're going to explore the use of Haml to define our application templates.
Haml stands for HTML Abstractional Markup Language and is a lightweight markup language abstraction that can be used to describe HTML without the need to use traditional markup language semantics (such as opening and closing tags).
Installing Haml can be done in just a line using Ruby Gems as follows:
$ gem install haml
If you haven't already downloaded and installed MongoDB from an earlier chapter, please do so now. With Ruby Gems, Mongo can be installed in just one line:
$ gem install mongodb
We now require two further steps to get everything up and running.
MongoDB stores data in the bin/data/db folder but won't actually create this directory for you. Navigate to where you've downloaded and extracted Mongo and run the following from terminal:
sudo mkdir -p /data/db/
sudo chown `id -u` /data/dbOnce this is done, open up two terminal windows.
In the first, cd to your MongoDB bin directory or type in the complete path to it. You'll need to start mongod.
$ ./bin/mongodFinally, in the second terminal, start the mongo shell which will connect up to localhost by default.
$ ./bin/mongoAs we'll be using the MongoDB Ruby Driver, we'll also require the following gems:
The gem for the driver itself:
$ gem install mongoand the driver's other prerequisite, bson:
$ gem install bson_extThis is basically a collection of extensions used to increase serialization speed.
That's it for our prerequisites!.
To get started, let's get a local copy of the practical application working on our system.
Clone this repository and navigate to /practicals/stacks/option3. Now run the following lines at the terminal:
ruby app.rbFinally, navigate to http://localhost:4567/todo to see the application running successfully.
Note: The Haml layout files for Option 3 can be found in the /views folder.
The directory structure for our practical application is as follows:
--public
----css
----img
----js
-----script.js
----test
--views
app.rb
The public directory contains the scripts and stylesheets for our application and uses HTML5 Boilerplate as a base. You can find the Models, Views and Collections for this section within public/js/scripts.js (however, this can of course be expanded into sub-directories for each component if desired).
scripts.js contains the following Backbone component definitions:
--Models
----Todo
--Collections
----TodoList
--Views
---TodoView
---AppViewapp.rb is the small Sinatra application that powers our backend API.
Lastly, the views directory hosts the Haml source files for our application's index and templates, both of which are compiled to standard HTML markup at runtime.
These can be viewed along with other note-worthy snippets of code from the application below.
In our main application view (AppView), we want to load any previously stored Todo items in our Mongo database when the view initializes. This is done below with the line Todos.fetch() in the initialize() method where we also bind to the relevant events on the Todos collection for when items are added or changed.
// Our overall **AppView** is the top-level piece of UI.
var AppView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: $("#todoapp"),
// Our template for the line of statistics at the bottom of the app.
statsTemplate: _.template($('#stats-template').html()),
// Delegated events for creating new items, and clearing completed ones.
events: {
"keypress #new-todo": "createOnEnter",
"keyup #new-todo": "showTooltip",
"click .todo-clear a": "clearCompleted"
},
// At initialization
initialize: function() {
this.input = this.$("#new-todo");
Todos.on('add', this.addOne, this);
Todos.on('reset', this.addAll, this);
Todos.on('all', this.render, this);
Todos.fetch();
},
// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function() {
this.$('#todo-stats').html(this.statsTemplate({
total: Todos.length,
done:
….In the TodoList collection below, we've set the url property to point to /api/todos to reference the collection's location on the server. When we attempt to access this from our Sinatra-backed API, it should return a list of all the Todo items that have been previously stored in Mongo.
For the sake of thoroughness, our API will also support returning the data for a specific Todo item via /api/todos/itemID. We'll take a look at this again when writing the Ruby code powering our backend.
// Todo Collection
var TodoList = Backbone.Collection.extend({
// Reference to this collection's model.
model: Todo,
// Save all of the todo items under the `"todos"` namespace.
// localStorage: new Store("todos"),
url: '/api/todos',
// Filter down the list of all todo items that are finished.
done: function() {
return this.filter(function(todo){ return todo.get('done'); });
},
// Filter down the list to only todo items that are still not finished.
remaining: function() {
return this.without.apply(this, this.done());
},
// We keep the Todos in sequential order, despite being saved by unordered
// GUID in the database. This generates the next order number for new items.
nextOrder: function() {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
// Todos are sorted by their original insertion order.
comparator: function(todo) {
return todo.get('order');
}
});The model for our Todo application remains largely unchanged from the versions previously covered in this book. It is however worth noting that calling the function model.url() within the below would return the relative URL where a specific Todo item could be located on the server.
// Our basic **Todo** model has `text`, `order`, and `done` attributes.
var Todo = Backbone.Model.extend({
idAttribute: "_id",
// Default attributes for a todo item.
defaults: function() {
return {
done: false,
order: Todos.nextOrder()
};
},
// Toggle the `done` state of this todo item.
toggle: function() {
this.save({done: !this.get("done")});
}
});Now that we've defined our main models, views and collections let's get the CRUD operations required by our Backbone application supported in our Sinatra API.
We want to make sure that for any operations changing underlying data (create, update, delete) that our Mongo data store correctly reflects these.
For app.rb, we first define the dependencies required by our application. These include Sinatra, Ruby Gems, the MongoDB Ruby driver and the JSON gem.
require 'rubygems'
require 'sinatra'
require 'mongo'
require 'json'Next, we create a new connection to Mongo, specifying any custom configuration desired. If running a multi-threaded application, setting the 'pool_size' allows us to specify a maximum pool size and 'timeout' a maximum timeout for waiting for old connections to be released to the pool.
DB = Mongo::Connection.new.db("mydb", :pool_size => 5, :timeout => 5)Finally we define the routes to be supported by our API. Note that in the first two blocks - one for our application root (/) and the other for our todo items route /todo - we're using Haml for template rendering.
class TodoApp < Sinatra::Base
get '/' do
haml :index, :attr_wrapper => '"', :locals => {:title => 'hello'}
end
get '/todo' do
haml :todo, :attr_wrapper => '"', :locals => {:title => 'Our Sinatra Todo app'}
endhaml :index instructs Sinatra to use the views/index.haml for the application index, whilst `attr_wrapper is simply defining the values to be used for any local variables defined inside the template. This similarly applies Todo items with the template `views/todo.haml'.
The rest of our routes make use of the params hash and a number of useful helper methods included with the MongoDB Ruby driver. For more details on these, please read the comments I've made inline below:
get '/api/:thing' do
# query a collection :thing, convert the output to an array, map the _id
# to a string representation of the object's _id and finally output to JSON
DB.collection(params[:thing]).find.to_a.map{|t| from_bson_id(t)}.to_json
end
get '/api/:thing/:id' do
# get the first document with the id :id in the collection :thing as a single document (rather
# than a Cursor, the standard output) using find_one(). Our bson utilities assist with
# ID conversion and the final output returned is also JSON
from_bson_id(DB.collection(params[:thing]).find_one(to_bson_id(params[:id]))).to_json
end
post '/api/:thing' do
# parse the post body of the content being posted, convert to a string, insert into
# the collection #thing and return the ObjectId as a string for reference
oid = DB.collection(params[:thing]).insert(JSON.parse(request.body.read.to_s))
"{\"_id\": \"#{oid.to_s}\"}"
end
delete '/api/:thing/:id' do
# remove the item with id :id from the collection :thing, based on the bson
# representation of the object id
DB.collection(params[:thing]).remove('_id' => to_bson_id(params[:id]))
end
put '/api/:thing/:id' do
# collection.update() when used with $set (as covered earlier) allows us to set single values
# in this case, the put request body is converted to a string, rejecting keys with the name '_id' for security purposes
DB.collection(params[:thing]).update({'_id' => to_bson_id(params[:id])}, {'$set' => JSON.parse(request.body.read.to_s).reject{|k,v| k == '_id'}})
end
# utilities for generating/converting MongoDB ObjectIds
def to_bson_id(id) BSON::ObjectId.from_string(id) end
def from_bson_id(obj) obj.merge({'_id' => obj['_id'].to_s}) end
endThat's it. The above is extremely lean for an entire API, but does allow us to read and write data to support the functionality required by our client-side application.
For more on what MongoDB and the MongoDB Ruby driver are capable of, please do feel free to read their documentation for more information.
If you're a developer wishing to take this example further, why not try to add some additional capabilities to the service:
Finally, we move on to the Haml files that define our application index (layout.haml) and the template for a specific Todo item (todo.haml). Both of these are largely self-explanatory, but it's useful to see the differences between the Jade approach we reviewed in the last chapter vs. using Haml for this implementation.
Note: In our Haml snippets below, the forward slash character is used to indicate a comment. When this character is placed at the beginning of a line, it wraps all of the text after it into a HTML comment. e.g
/ These are templates
compiles to:
<!-- These are templates -->
%head
%meta{'charset' => 'utf-8'}/
%title=title
%meta{'name' => 'description', 'content' => ''}/
%meta{'name' => 'author', 'content' => ''}/
%meta{'name' => 'viewport', 'content' => 'width=device-width,initial-scale=1'}/
/ CSS concatenated and minified via ant build script
%link{'rel' => 'stylesheet', 'href' => 'css/style.css'}/
/ end CSS
%script{'src' => 'js/libs/modernizr.min.js'}
%body
%div#container
%header
%div#main
= yield
%footer
/! end of #container
%script{'src' => 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'}
/ scripts concatenated and minified via ant build script
%script{'src' => 'js/mylibs/underscore.js'}
%script{'src' => 'js/mylibs/backbone.js'}
%script{'defer' => true, 'src' => 'js/plugins.js'}
%script{'defer' => true, 'src' => 'js/script.js'}
/ end scripts%div#todoapp
%div.title
%h1
Todos
%div.content
%div#create-todo
%input#new-todo{"placeholder" => "What needs to be done?", "type" => "text"}/
%span.ui-tooltip-top{"style" => "display:none;"} Press Enter to save this task
%div#todos
%ul#todo-list
%div#todo-stats
/ Templates
%script#item-template{"type" => "text/template"}
<div class="todo <%= done ? 'done' : '' %>">
%div.display
<input class="check" type="checkbox" <%= done ? 'checked="checked"' : '' %> />
%div.todo-text
%span#todo-destroy
%div.edit
%input.todo-input{"type" => "text", "value" =>""}/
</div>
%script#stats-template{"type" => "text/template"}
<% if (total) { %>
%span.todo-count
%span.number <%= remaining %>
%span.word <%= remaining == 1 ? 'item' : 'items' %>
left.
<% } %>
<% if (done) { %>
%span.todo-clear
%a{"href" => "#"}
Clear
%span.number-done <%= done %>
completed
%span.word-done <%= done == 1 ? 'item' : 'items' %>
<% } %>In this chapter, we looked at creating a Backbone application backed by an API powered by Ruby, Sinatra, Haml, MongoDB and the MongoDB driver. I personally found developing APIs with Sinatra a relatively painless experience and one which I felt was on-par with the effort required for the Node/Express implementation of the same application.
This section is by no means the most comprehensive guide on building complex apps using all of the items in this particular stack. I do however hope it was an introduction sufficient enough to help you decide on what stack to try out for your next project.
When we say an application is modular, we generally mean it's composed of a set of highly decoupled, distinct pieces of functionality stored in modules. As you probably know, loose coupling facilitates easier maintainability of apps by removing dependencies where possible. When this is implemented efficiently, its quite easy to see how changes to one part of a system may affect another.
Unlike some more traditional programming languages however, the current iteration of JavaScript (ECMA-262) doesn't provide developers with the means to import such modules of code in a clean, organized manner. It's one of the concerns with specifications that haven't required great thought until more recent years where the need for more organized JavaScript applications became apparent.
Instead, developers at present are left to fall back on variations of the module or object literal patterns. With many of these, module scripts are strung together in the DOM with namespaces being described by a single global object where it's still possible to incur naming collisions in your architecture. There's also no clean way to handle dependency management without some manual effort or third party tools.
Whilst native solutions to these problems will be arriving in ES Harmony, the good news is that writing modular JavaScript has never been easier and you can start doing it today.
In this next part of the book, we're going to look at how to use AMD modules and RequireJS for cleanly wrapping units of code in your application into manageable modules.
In case you haven't used it before, RequireJS is a popular script loader written by James Burke - a developer who has been quite instrumental in helping shape the AMD module format, which we'll discuss more shortly. Some of RequireJS's capabilities include helping to load multiple script files, helping define modules with or without dependencies and loading in non-script dependencies such as text files.
So, why use RequireJS with Backbone? Although Backbone is excellent when it comes to providing a sanitary structure to your applications, there are a few key areas where some additional help could be used:
RequireJS is compatible with the AMD (Asynchronous Module Definition) format, a format which was born from a desire to write something better than the 'write lots of script tags with implicit dependencies and manage them manually' approach to development. In addition to allowing you to clearly declare dependencies, AMD works well in the browser, supports string IDs for dependencies, declaring multiple modules in the same file and gives you easy-to-use tools to avoid polluting the global namespace.
Think about the GMail web-client for a moment. When users initially load up the page on their first visit, Google can simply hide widgets such as the chat module until a user has indicated (by clicking 'expand') that they wish to use it. Through dynamic dependency loading, Google could load up the chat module only then, rather than forcing all users to load it when the page first initializes. This can improve performance and load times and can definitely prove useful when building larger applications.
I've previously written a detailed article covering both AMD and other module formats and script loaders in case you'd like to explore this topic further. The takeaway is that although it's perfectly fine to develop applications without a script loader or clean module format in place, it can be of significant benefit to consider using these tools in your application development.
As discussed above, the overall goal for the AMD format is to provide a solution for modular JavaScript that developers can use today. The two key concepts you need to be aware of when using it with a script-loader are a define() method for facilitating module definition and a require() method for handling dependency loading. define() is used to define named or unnamed modules based on the proposal using the following signature:
define(
module_id /*optional*/,
[dependencies] /*optional*/,
definition function /*function for instantiating the module or object*/
);As you can tell by the inline comments, the module_id is an optional argument which is typically only required when non-AMD concatenation tools are being used (there may be some other edge cases where it's useful too). When this argument is left out, we call the module 'anonymous'. When working with anonymous modules, the idea of a module's identity is DRY, making it trivial to avoid duplication of filenames and code.
Back to the define signature, the dependencies argument represents an array of dependencies which are required by the module you are defining and the third argument ('definition function') is a function that's executed to instantiate your module. A barebone module (compatible with RequireJS) could be defined using define() as follows:
// A module ID has been omitted here to make the module anonymous
define(['foo', 'bar'],
// module definition function
// dependencies (foo and bar) are mapped to function parameters
function ( foo, bar ) {
// return a value that defines the module export
// (i.e the functionality we want to expose for consumption)
// create your module here
var myModule = {
doStuff:function(){
console.log('Yay! Stuff');
}
}
return myModule;
});There is also a sugared version of define() available that allows you to declare your dependencies as local variables using require(). This will feel familiar to anyone who's used node, and can be easier to add or remove dependencies. Here is the previous snippet using the alternate syntax:
// A module ID has been omitted here to make the module anonymous
define(function(require){
// module definition function
// dependencies (foo and bar) are defined as local vars
var foo = require('foo'),
bar = require('bar');
// return a value that defines the module export
// (i.e the functionality we want to expose for consumption)
// create your module here
var myModule = {
doStuff:function(){
console.log('Yay! Stuff');
}
}
return myModule;
});The require() method is typically used to load code in a top-level JavaScript file or within a module should you wish to dynamically fetch dependencies. An example of its usage is:
// Consider 'foo' and 'bar' are two external modules
// In this example, the 'exports' from the two modules loaded are passed as
// function arguments to the callback (foo and bar)
// so that they can similarly be accessed
require(['foo', 'bar'], function ( foo, bar ) {
// rest of your code here
foo.doSomething();
});Wrapping modules, views and other components with AMD
Now that we've taken a look at how to define AMD modules, let's review how to go about wrapping components like views and collections so that they can also be easily loaded as dependencies for any parts of your application that require them. At it's simplest, a Backbone model may just require Backbone and Underscore.js. These are considered it's dependencies and so, to write an AMD model module, we would simply do this:
define(['underscore', 'backbone'], function(_, Backbone) {
var myModel = Backbone.Model.extend({
// Default attributes
defaults: {
content: "hello world",
},
// A dummy initialization method
initialize: function() {
},
clear: function() {
this.destroy();
this.view.remove();
}
});
return myModel;
});Note how we alias Underscore.js's instance to _ and Backbone to just Backbone, making it very trivial to convert non-AMD code over to using this module format. For a view which might require other dependencies such as jQuery, this can similarly be done as follows:
define([
'jquery',
'underscore',
'backbone',
'collections/mycollection',
'views/myview'
], function($, _, Backbone, myCollection, myView){
var AppView = Backbone.View.extend({
...Aliasing to the dollar-sign ($), once again makes it very easy to encapsulate any part of an application you wish using AMD.
Moving your [Underscore/Mustache/Handlebars] templates to external files is actually quite straight-forward. As this application makes use of RequireJS, I'll discuss how to implement external templates using this specific script loader.
RequireJS has a special plugin called text.js which is used to load in text file dependencies. To use the text plugin, simply follow these simple steps:
Download the plugin from http://requirejs.org/docs/download.html#text and place it in either the same directory as your application's main JS file or a suitable sub-directory.
Next, include the text.js plugin in your initial RequireJS configuration options. In the code snippet below, we assume that RequireJS is being included in our page prior to this code snippet being executed. Any of the other scripts being loaded are just there for the sake of example.
require.config( {
paths: {
'backbone': 'libs/AMDbackbone-0.5.3',
'underscore': 'libs/underscore-1.2.2',
'text': 'libs/require/text',
'jquery': 'libs/jQuery-1.7.1',
'json2': 'libs/json2',
'datepicker': 'libs/jQuery.ui.datepicker',
'datepickermobile': 'libs/jquery.ui.datepicker.mobile',
'jquerymobile': 'libs/jquery.mobile-1.0'
},
baseUrl: 'app'
} );text! prefix is used for a dependency, RequireJS will automatically load the text plugin and treat the dependency as a text resource. A typical example of this in action may look like..require(['js/app', 'text!templates/mainView.html'],
function(app, mainView){
// the contents of the mainView file will be
// loaded into mainView for usage.
}
);With Underscore.js's micro-templating (and jQuery) this would typically be:
HTML:
<script type="text/template" id="mainViewTemplate">
<% _.each( person, function( person_item ){ %>
<li><%= person_item.get("name") %></li>
<% }); %>
</script>JS:
var compiled_template = _.template( $('#mainViewTemplate').html() );With RequireJS and the text plugin however, it's as simple as saving your template into an external text file (say, mainView.html) and doing the following:
require(['js/app', 'text!templates/mainView.html'],
function(app, mainView){
var compiled_template = _.template( mainView );
}
);That's it!. You can then go applying your template to a view in Backbone doing something like:
collection.someview.el.html( compiled_template( { results: collection.models } ) );All templating solutions will have their own custom methods for handling template compilation, but if you understand the above, substituting Underscore's micro-templating for any other solution should be fairly trivial.
Note: You may also be interested in looking at Require.js tpl. It's an AMD-compatible version of the Underscore templating system that also includes support for optimization (pre-compiled templates) which can lead to better performance and no evals. I have yet to use it myself, but it comes as a recommended resource.
As experienced developers may know, an essential final step when writing both small and large JavaScript web applications is the build process. The majority of non-trivial apps are likely to consist of more than one or two scripts and so optimizing, minimizing and concatenating your scripts prior to pushing them to production will require your users to download a reduced number (if not just one) script file.
Note: If you haven't looked at build processes before and this is your first time hearing about them, you might find my post and screencast on this topic useful.
With some other structural JavaScript frameworks, my recommendation would normally be to implicitly use YUI Compressor or Google's closure compiler tools, but we have a slightly more elegant method available, when it comes to Backbone if you're using RequireJS. RequireJS has a command line optimization tool called r.js which has a number of capabilities, including:
You'll notice that I mentioned the word 'specific' in the first bullet point. The RequireJS optimizer only concatenates module scripts that have been specified in arrays of string literals passed to top-level (i.e non-local) require and define calls. As clarified by the optimizer docs this means that Backbone modules defined like this:
define(['jquery','backbone','underscore', 'collections/sample','views/test'],
function($,Backbone, _, Sample, Test){
//...
});will combine fine, however inline dependencies such as:
var models = someCondition ? ['models/ab','models/ac'] : ['models/ba','models/bc'];will be ignored. This is by design as it ensures that dynamic dependency/module loading can still take place even after optimization.
Although the RequireJS optimizer works fine in both Node and Java environments, it's strongly recommended to run it under Node as it executes significantly faster there. In my experience, it's a piece of cake to get setup with either environment, so go for whichever you feel most comfortable with.
To get started with r.js, grab it from the RequireJS download page or through NPM. Now, the RequireJS optimizer works absolutely fine for single script and CSS files, but for most cases you'll want to actually optimize an entire Backbone project. You could do this completely from the command-line, but a cleaner option is using build profiles.
Below is an example of a build file taken from the modular jQuery Mobile app referenced later in this book. A build profile (commonly named app.build.js) informs RequireJS to copy all of the content of appDir to a directory defined by dir (in this case ../release). This will apply all of the necessary optimizations inside the release folder. The baseUrl is used to resolve the paths for your modules. It should ideally be relative to appDir.
Near the bottom of this sample file, you'll see an array called modules. This is where you specify the module names you wish to have optimized. In this case we're optimizing the main application called 'app', which maps to appDir/app.js. If we had set the baseUrl to 'scripts', it would be mapped to appDir/scripts/app.js.
({
appDir: "./",
baseUrl: "./",
dir: "../release",
paths: {
'backbone': 'libs/AMDbackbone-0.5.3',
'underscore': 'libs/underscore-1.2.2',
'jquery': 'libs/jQuery-1.7.1',
'json2': 'libs/json2',
'datepicker': 'libs/jQuery.ui.datepicker',
'datepickermobile': 'libs/jquery.ui.datepicker.mobile',
'jquerymobile': 'libs/jquery.mobile-1.0'
},
optimize: "uglify",
modules: [
{
name: "app",
exclude: [
// If you prefer not to include certain libs exclude them here
]
}
]
})The way the build system in r.js works is that it traverses app.js (whatever modules you've passed) and resolved dependencies, concatenating them into the final release(dir) folder. CSS is treated the same way.
The build profile is usually placed inside the 'scripts' or 'js' directory of your project. As per the docs, this file can however exist anywhere you wish, but you'll need to edit the contents of your build profile accordingly.
Finally, to run the build, execute the following command once inside your appDir or appDir/scripts directory:
node ../../r.js -o app.build.jsThat's it. As long as you have UglifyJS/Closure tools setup correctly, r.js should be able to easily optimize your entire Backbone project in just a few key-strokes. If you would like to learn more about build profiles, James Burke has a heavily commented sample file with all the possible options available.
In this chapter, we'll look at our first practical Backbone & RequireJS project - how to build a modular Todo application. The application will allow us to add new todos, edit new todos and clear todo items that have been marked as completed. For a more advanced practical, see the section on mobile Backbone development.
The complete code for the application can can be found in the practicals/modular-todo-app folder of this repo (thanks to Thomas Davis and Jérôme Gravel-Niquet). Alternatively grab a copy of my side-project TodoMVC which contains the sources to both AMD and non-AMD versions.
Note: Thomas may be covering a practical on this exercise in more detail on backbonetutorials.com at some point soon, but for this section I'll be covering what I consider the core concepts.
Writing a 'modular' Backbone application can be a straight-forward process. There are however, some key conceptual differences to be aware of if opting to use AMD as your module format of choice:
Now that we've reviewed the basics, let's take a look at developing our application. For reference, the structure of our app is as follows:
index.html
...js/
main.js
.../models
todo.js
.../views
app.js
todos.js
.../collections
todos.js
.../templates
stats.html
todos.html
../libs
.../backbone
.../jquery
.../underscore
.../require
require.js
text.js
...css/The markup for the application is relatively simple and consists of three primary parts: an input section for entering new todo items (create-todo), a list section to display existing items (which can also be edited in-place) (todo-list) and finally a section summarizing how many items are left to be completed (todo-stats).
<div id="todoapp">
<div class="content">
<div id="create-todo">
<input id="new-todo" placeholder="What needs to be done?" type="text" />
<span class="ui-tooltip-top">Press Enter to save this task</span>
</div>
<div id="todos">
<ul id="todo-list"></ul>
</div>
<div id="todo-stats"></div>
</div>
</div>The rest of the tutorial will now focus on the JavaScript side of the practical.
If you've read the earlier chapter on AMD, you may have noticed that explicitly needing to define each dependency a Backbone module (view, collection or other module) may require with it can get a little tedious. This can however be improved.
In order to simplify referencing common paths the modules in our application may use, we use a RequireJS configuration object, which is typically defined as a top-level script file. Configuration objects have a number of useful capabilities, the most useful being mode name-mapping. Name-maps are basically a key:value pair, where the key defines the alias you wish to use for a path and the value represents the true location of the path.
In the code-sample below, you can see some typical examples of common name-maps which include: backbone, underscore, jquery and depending on your choice, the RequireJS text plugin, which assists with loading text assets like templates.
main.js
require.config({
baseUrl:'../',
paths: {
jquery: 'libs/jquery/jquery-min',
underscore: 'libs/underscore/underscore-min',
backbone: 'libs/backbone/backbone-optamd3-min',
text: 'libs/require/text'
}
});
require(['views/app'], function(AppView){
var app_view = new AppView;
});The require() at the end of our main.js file is simply there so we can load and instantiation the primary view for our application (views/app.js). You'll commonly see both this and the configuration object included the most top-level script file for a project.
In addition to offering name-mapping, the configuration object can be used to define additional properties such as waitSeconds - the number of seconds to wait before script loading times out and locale, should you wish to load up i18n bundles for custom languages. The baseUrl is simply the path to use for module lookups.
For more information on configuration objects, please feel free to check out the excellent guide to them in the RequireJS docs.
Before we dive into AMD-wrapped versions of our Backbone components, let's review a sample of a non-AMD view. The following view listens for changes to its model (a Todo item) and re-renders if a user edits the value of the item.
var TodoView = Backbone.View.extend({
//... is a list tag.
tagName: "li",
// Cache the template function for a single item.
template: _.template($('#item-template').html()),
// The DOM events specific to an item.
events: {
"click .check" : "toggleDone",
"dblclick div.todo-content" : "edit",
"click span.todo-destroy" : "clear",
"keypress .todo-input" : "updateOnEnter"
},
// The TodoView listens for changes to its model, re-rendering. Since there's
// a one-to-one correspondence between a **Todo** and a **TodoView** in this
// app, we set a direct reference on the model for convenience.
initialize: function() {
this.model.bind('change', this.render, this);
this.model.view = this;
},
...Note how for templating the common practice of referencing a script by an ID (or other selector) and obtaining its value is used. This of course requires that the template being accessed is implicitly defined in our markup. The following is the 'embedded' version of our template being referenced above:
<script type="text/template" id="item-template">
<div class="todo <%= done ? 'done' : '' %>">
<div class="display">
<input class="check" type="checkbox" <%= done ? 'checked="checked"' : '' %> />
<div class="todo-content"></div>
<span class="todo-destroy"></span>
</div>
<div class="edit">
<input class="todo-input" type="text" value="" />
</div>
</div>
</script>Whilst there is nothing wrong with the template itself, once we begin to develop larger applications requiring multiple templates, including them all in our markup on page-load can quickly become both unmanageable and come with performance costs. We'll look at solving this problem in a minute.
Let's now take a look at the AMD-version of our view. As discussed earlier, the 'module' is wrapped using AMD's define() which allows us to specify the dependencies our view requires. Using the mapped paths to 'jquery' etc. simplifies referencing common dependencies and instances of dependencies are themselves mapped to local variables that we can access (e.g 'jquery' is mapped to $).
views/todos.js
define([
'jquery',
'underscore',
'backbone',
'text!templates/todos.html'
], function($, _, Backbone, todosTemplate){
var TodoView = Backbone.View.extend({
//... is a list tag.
tagName: "li",
// Cache the template function for a single item.
template: _.template(todosTemplate),
// The DOM events specific to an item.
events: {
"click .check" : "toggleDone",
"dblclick div.todo-content" : "edit",
"click span.todo-destroy" : "clear",
"keypress .todo-input" : "updateOnEnter"
},
// The TodoView listens for changes to its model, re-rendering. Since there's
// a one-to-one correspondence between a **Todo** and a **TodoView** in this
// app, we set a direct reference on the model for convenience.
initialize: function() {
this.model.bind('change', this.render, this);
this.model.view = this;
},
// Re-render the contents of the todo item.
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
this.setContent();
return this;
},
// Use `jQuery.text` to set the contents of the todo item.
setContent: function() {
var content = this.model.get('content');
this.$('.todo-content').text(content);
this.input = this.$('.todo-input');
this.input.bind('blur', this.close);
this.input.val(content);
},
...From a maintenance perspective, there's nothing logically different in this version of our view, except for how we approach templating.
Using the RequireJS text plugin (the dependency marked text), we can actually store all of the contents for the template we looked at earlier in an external file (todos.html).
templates/todos.html
<div class="todo <%= done ? 'done' : '' %>">
<div class="display">
<input class="check" type="checkbox" <%= done ? 'checked="checked"' : '' %> />
<div class="todo-content"></div>
<span class="todo-destroy"></span>
</div>
<div class="edit">
<input class="todo-input" type="text" value="" />
</div>
</div>There's no longer a need to be concerned with IDs for the template as we can map it's contents to a local variable (in this case todosTemplate). We then simply pass this to the Underscore.js templating function _.template() the same way we normally would have the value of our template script.
Next, let's look at how to define models as dependencies which can be pulled into collections. Here's an AMD-compatible model module, which has two default values: a content attribute for the content of a Todo item and a boolean done state, allowing us to trigger whether the item has been completed or not.
models/todo.js
define(['underscore', 'backbone'], function(_, Backbone) {
var TodoModel = Backbone.Model.extend({
// Default attributes for the todo.
defaults: {
// Ensure that each todo created has `content`.
content: "empty todo...",
done: false
},
initialize: function() {
},
// Toggle the `done` state of this todo item.
toggle: function() {
this.save({done: !this.get("done")});
},
// Remove this Todo from *localStorage* and delete its view.
clear: function() {
this.destroy();
this.view.remove();
}
});
return TodoModel;
});As per other types of dependencies, we can easily map our model module to a local variable (in this case Todo) so it can be referenced as the model to use for our TodosCollection. This collection also supports a simple done() filter for narrowing down Todo items that have been completed and a remaining() filter for those that are still outstanding.
collections/todos.js
define([
'underscore',
'backbone',
'libs/backbone/localstorage',
'models/todo'
], function(_, Backbone, Store, Todo){
var TodosCollection = Backbone.Collection.extend({
// Reference to this collection's model.
model: Todo,
// Save all of the todo items under the `"todos"` namespace.
localStorage: new Store("todos"),
// Filter down the list of all todo items that are finished.
done: function() {
return this.filter(function(todo){ return todo.get('done'); });
},
// Filter down the list to only todo items that are still not finished.
remaining: function() {
return this.without.apply(this, this.done());
},
...In addition to allowing users to add new Todo items from views (which we then insert as models in a collection), we ideally also want to be able to display how many items have been completed and how many are remaining. We've already defined filters that can provide us this information in the above collection, so let's use them in our main application view.
views/app.js
define([
'jquery',
'underscore',
'backbone',
'collections/todos',
'views/todos',
'text!templates/stats.html'
], function($, _, Backbone, Todos, TodoView, statsTemplate){
var AppView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: $("#todoapp"),
// Our template for the line of statistics at the bottom of the app.
statsTemplate: _.template(statsTemplate),
// ...events, initialize() etc. can be seen in the complete file
// Re-rendering the App just means refreshing the statistics -- the rest
// of the app doesn't change.
render: function() {
var done = Todos.done().length;
this.$('#todo-stats').html(this.statsTemplate({
total: Todos.length,
done: Todos.done().length,
remaining: Todos.remaining().length
}));
},
...Above, we map the second template for this project, templates/stats.html to statsTemplate which is used for rendering the overall done and remaining states. This works by simply passing our template the length of our overall Todos collection (Todos.length - the number of Todo items created so far) and similarly the length (counts) for items that have been completed (Todos.done().length) or are remaining (Todos.remaining().length).
The contents of our statsTemplate can be seen below. It's nothing too complicated, but does use ternary conditions to evaluate whether we should state there's "1 item" or "2 items" in a particular state.
<% if (total) { %>
<span class="todo-count">
<span class="number"><%= remaining %></span>
<span class="word"><%= remaining == 1 ? 'item' : 'items' %></span> left.
</span>
<% } %>
<% if (done) { %>
<span class="todo-clear">
<a href="#">
Clear <span class="number-done"><%= done %></span>
completed <span class="word-done"><%= done == 1 ? 'item' : 'items' %></span>
</a>
</span>
<% } %>The rest of the source for the Todo app mainly consists of code for handling user and application events, but that rounds up most of the core concepts for this practical.
To see how everything ties together, feel free to grab the source by cloning this repo or browse it online to learn more. I hope you find it helpful!.
Note: While this first practical doesn't use a build profile as outlined in the chapter on using the RequireJS optimizer, we will be using one in the section on building mobile Backbone applications.
In this section we'll discuss applying some of the concepts I cover in my article on Large-scale JavaScript Application development to Backbone.
At a high-level, one architecture that works for such applications is something which is:
This is an architecture which has been implemented by a number of different companies in the past, including Yahoo! (for their modularized homepage - which Nicholas Zakas has spoken about) and AOL for some of our upcoming projects.
The three design patterns that make this architecture possible are the:
Their specific roles in this architecture can be found below.
For ease of reference, I sometimes refer to these three patterns grouped together as Aura (a word that means subtle, luminous light).
For the practical section of this chapter, we'll be extending the well-known Backbone Todo application using the three patterns mentioned above. The complete code for this section can be found here: https://github.com/addyosmani/backbone-aura and should ideally be run on at minimum, a local HTTP server.
The application is broken down into AMD modules that cover everything from Backbone models through to application-level modules. The views publish events of interest to the rest of the application and modules can then subscribe to these event notifications.
All subscriptions from modules go through a facade (or sandbox). What this does is check against the subscriber name and the 'channel/notification' it's attempting to subscribe to. If a channel doesn't have permissions to be subscribed to (something established through permissions.js), the subscription isn't permitted.
Mediator
Found in aura/mediator.js
Below is a very simple AMD-wrapped implementation of the mediator pattern, based on prior work by Ryan Florence. It accepts as it's input an object, to which it attaches publish() and subscribe() methods. In a larger application, the mediator can contain additional utilities, such as handlers for initializing, starting and stopping modules, but for demonstration purposes, these two methods should work fine for our needs.
define([], function(obj){
var channels = {};
if (!obj) obj = {};
obj.subscribe = function (channel, subscription) {
if (!channels[channel]) channels[channel] = [];
channels[channel].push(subscription);
};
obj.publish = function (channel) {
if (!channels[channel]) return;
var args = [].slice.call(arguments, 1);
for (var i = 0, l = channels[channel].length; i < l; i++) {
channels[channel][i].apply(this, args);
}
};
return obj;
});Facade
Found in aura/facade.js
Next, we have an implementation of the facade pattern. Now the classical facade pattern applied to JavaScript would probably look a little like this:
var module = (function() {
var _private = {
i:5,
get : function() {
console.log('current value:' + this.i);
},
set : function( val ) {
this.i = val;
},
run : function() {
console.log('running');
},
jump: function(){
console.log('jumping');
}
};
return {
facade : function( args ) {
_private.set(args.val);
_private.get();
if ( args.run ) {
_private.run();
}
}
}
}());
module.facade({run: true, val:10});
//outputs current value: 10, runningIt's effectively a variation of the module pattern, where instead of simply returning an interface of supported methods, your API can completely hide the true implementation powering it, returning something simpler. This allows the logic being performed in the background to be as complex as necessary, whilst all the end-user experiences is a simplified API they pass options to (note how in our case, a single method abstraction is exposed). This is a beautiful way of providing APIs that can be easily consumed.
That said, to keep things simple, our implementation of an AMD-compatible facade will act a little more like a proxy. Modules will communicate directly through the facade to access the mediator's publish() and subscribe() methods, however, they won't as such touch the mediator directly.This enables the facade to provide application-level validation of any subscriptions and publications made.
It also allows us to implement a simple, but flexible, permissions checker (as seen below) which will validate subscriptions made against a permissions configuration to see whether it's permitted or not.
define([ "../aura/mediator" , "../aura/permissions" ], function (mediator, permissions) {
var facade = facade || {};
facade.subscribe = function(subscriber, channel, callback){
// Note: Handling permissions/security is optional here
// The permissions check can be removed
// to just use the mediator directly.
if(permissions.validate(subscriber, channel)){
mediator.subscribe( channel, callback );
}
}
facade.publish = function(channel){
mediator.publish( channel );
}
return facade;
});Permissions
Found in aura/permissions.js
In our simple permissions configuration, we support checking against subscription requests to establish whether they are allowed to clear. This enforces a flexible security layer for the application.
To visually see how this works, consider changing say, permissions -> renderDone -> todoCounter to be false. This will completely disable the application from from rendering or displaying the counts component for Todo items left (because they aren't allowed to subscribe to that event notification). The rest of the Todo app can still however be used without issue.
It's a very dumbed down example of the potential for application security, but imagine how powerful this might be in a large app with a significant number of visual widgets.
define([], function () {
// Permissions
// A permissions structure can support checking
// against subscriptions prior to allowing them
// to clear. This enforces a flexible security
// layer for your application.
var permissions = {
newContentAvailable: {
contentUpdater:true
},
endContentEditing:{
todoSaver:true
},
beginContentEditing:{
editFocus:true
},
addingNewTodo:{
todoTooltip:true
},
clearContent:{
garbageCollector:true
},
renderDone:{
todoCounter:true //switch to false to see what happens :)
},
destroyContent:{
todoRemover:true
},
createWhenEntered:{
keyboardManager:true
}
};
permissions.validate = function(subscriber, channel){
var test = permissions[channel][subscriber];
return test===undefined? false: test;
};
return permissions;
});Subscribers
Found in subscribers.js
Subscriber 'modules' communicate through the facade back to the mediator and perform actions when a notification event of a particular name is published.
For example, when a user enters in a new piece of text for a Todo item and hits 'enter' the application publishes a notification saying two things: a) a new Todo item is available and b) the text content of the new item is X. It's then left up to the rest of the application to do with this information whatever it wishes.
In order to update your Backbone application to primarily use pub/sub, a lot of the work you may end up doing will be moving logic coupled inside of specific views to modules outside of it which are reactionary.
Take the todoSaver for example - it's responsibility is saving new Todo items to models once the a notificationName called 'newContentAvailable' has fired. If you take a look at the permissions structure in the last code sample, you'll notice that 'newContentAvailable' is present there. If I wanted to prevent subscribers from being able to subscribe to this notification, I simply set it to a boolean value of false.
Again, this is a massive oversimplification of how advanced your permissions structures could get, but it's certainly one way of controlling what parts of your application can or can't be accessed by specific modules at any time.
define(["jquery", "underscore", "aura/facade"],
function ($, _, facade) {
// Subscription 'modules' for our views. These take the
// the form facade.subscribe( subscriberName, notificationName , callBack )
// Update view with latest todo content
// Subscribes to: newContentAvailable
facade.subscribe('contentUpdater', 'newContentAvailable', function (context) {
var content = context.model.get('content');
context.$('.todo-content').text(content);
context.input = context.$('.todo-input');
context.input.bind('blur', context.close);
context.input.val(content);
});
// Save models when a user has finishes editing
// Subscribes to: endContentEditing
facade.subscribe('todoSaver','endContentEditing', function (context) {
try {
context.model.save({
content: context.input.val()
});
$(context.el).removeClass("editing");
} catch (e) {
//console.log(e);
}
});
// Delete a todo when the user no longer needs it
// Subscribes to: destroyContent
facade.subscribe('todoRemover','destroyContent', function (context) {
try {
context.model.clear();
} catch (e) {
//console.log(e);
}
});
// When a user is adding a new entry, display a tooltip
// Subscribes to: addingNewTodo
facade.subscribe('todoTooltip','addingNewTodo', function (context, todo) {
var tooltip = context.$(".ui-tooltip-top");
var val = context.input.val();
tooltip.fadeOut();
if (context.tooltipTimeout) clearTimeout(context.tooltipTimeout);
if (val == '' || val == context.input.attr('placeholder')) return;
var show = function () {
tooltip.show().fadeIn();
};
context.tooltipTimeout = _.delay(show, 1000);
});
// Update editing UI on switching mode to editing content
// Subscribes to: beginContentEditing
facade.subscribe('editFocus','beginContentEditing', function (context) {
$(context.el).addClass("editing");
context.input.focus();
});
// Create a new todo entry
// Subscribes to: createWhenEntered
facade.subscribe('keyboardManager','createWhenEntered', function (context, e, todos) {
if (e.keyCode != 13) return;
todos.create(context.newAttributes());
context.input.val('');
});
// A Todo and remaining entry counter
// Subscribes to: renderDone
facade.subscribe('todoCounter','renderDone', function (context, Todos) {
var done = Todos.done().length;
context.$('#todo-stats').html(context.statsTemplate({
total: Todos.length,
done: Todos.done().length,
remaining: Todos.remaining().length
}));
});
// Clear all completed todos when clearContent is dispatched
// Subscribes to: clearContent
facade.subscribe('garbageCollector','clearContent', function (Todos) {
_.each(Todos.done(), function (todo) {
todo.clear();
});
});
});That's it for this section. If you've been intrigued by some of the concepts covered, I encourage you to consider taking a look at my slides on Large-scale JS from the jQuery Summit or my longer post on the topic here for more information.
Pagination is a ubiquitous problem we often find ourselves needing to solve on the web. Perhaps most predominantly when working with back-end APIs and JavaScript-heavy clients which consume them.
On this topic, we're going to go through a set of **pagination components ** I wrote for Backbone.js, which should hopefully come in useful if you're working on applications which need to tackle this problem. They're part of an extension called Backbone.Paginator.
When working with a structural framework like Backbone.js, the three types of pagination we are most likely to run into are:
**Requests to a service layer (API) **- e.g query for results containing the term 'Brendan' - if 5,000 results are available only display 20 results per page (leaving us with 250 possible result pages that can be navigated to).
This problem actually has quite a great deal more to it, such as maintaining persistence of other URL parameters (e.g sort, query, order) which can change based on a user's search configuration in a UI. One also had to think of a clean way of hooking views up to this pagination so you can easily navigate between pages (e.g First, Last, Next, Previous, 1,2,3), manage the number of results displayed per page and so on.
Further client-side pagination of data returned - e.g we've been returned a JSON esponse containing 100 results. Rather than displaying all 100 to the user, we only display 20 of these results within a navigatable UI in the browser.
Similar to the request problem, client-pagination has its own challenges like navigation once again (Next, Previous, 1,2,3), sorting, order, switching the number of results to display per page and so on.
Infinite results - with services such as Facebook, the concept of numeric pagination is instead replaced with a 'Load More' or 'View More' button. Triggering this normally fetches the next 'page' of N results but rather than replacing the previous set of results loaded entirely, we simply append to them instead.
A request pager which simply appends results in a view rather than replacing on each new fetch is effectively an 'infinite' pager.
Let's now take a look at exactly what we're getting out of the box:
Backbone.Paginator is a set of opinionated components for paginating collections of data using Backbone.js. It aims to provide both solutions for assisting with pagination of requests to a server (e.g an API) as well as pagination of single-loads of data, where we may wish to further paginate a collection of N results into M pages within a view.
Backbone.Paginator supports two main pagination components:
You can either download the raw source code for the project, fork the repository or use one of these links:
Production: production
Development: development version
Examples + Source : zipball
Repositoryhttp://github.com/addyosmani/backbone.paginator)
Live previews of both pagination components using the Netflix API can be found below. Download the tarball or fork the repository to experiment with these examples further.
Demo 1: Backbone.Paginator.requestPager()

Demo 2: Backbone.Paginator.clientPager()

Demo 3: Infinite Pagination (Backbone.Paginator.requestPager())

In this section we're going to walkthrough actually using the requestPager.
First, we define a new Paginated collection using Backbone.Paginator.requestPager() as follows:
var PaginatedCollection = Backbone.Paginator.requestPager.extend({
Within our collection, we then (as normal) specify the model to be used with this collection followed by the URL (or base URL) for the service providing our data (e.g the Netflix API).
model: model,
url: 'http://odata.netflix.com/v2/Catalog/Titles?&',Next, we're going to map the request (URL) parameters supported by your API or backend data service back to attributes that are internally used by Backbone.Paginator.
For example: the NetFlix API refers to it's parameter for stating how many results to skip ahead by as $skip and it's number of items to return per page as $top (amongst others). We determine these by looking at a sample URL pointing at the service:
http://odata.netflix.com/v2/Catalog/Titles?&callback=callback&$top=30&$skip=30&orderBy=ReleaseYear&$inlinecount=allpages&$format=json&$callback=callback&$filter=substringof%28%27the%27,%20Name%29%20eq%20true&_=1332702202090We then simply map these parameters to the relevant Paginator equivalents shown on the left hand side of the next snippets to get everything working:
// @param-name for the query field in the
// request (e.g query/keywords/search)
queryAttribute: '$filter',
// @param-name for number of items to return per request/page
perPageAttribute: '$top',
// @param-name for how many results the request should skip ahead to
skipAttribute: '$skip',
// @param-name for the direction to sort in
sortAttribute: '$sort',
// @param-name for field to sort by
orderAttribute: '$orderBy',
// @param-name for the format of the request
formatAttribute: '$format',
// @param-name for a custom attribute
customAttribute1: '$inlinecount',
// @param-name for another custom attribute
customAttribute2: '$callback',Note: you can define support for new custom attributes in Backbone.Paginator if needed (e.g customAttribute1) for those that may be unique to your service.
Now, let's configure the default values in our collection for these parameters so that as a user navigates through the paginated UI, requests are able to continue querying with the correct field to sort on, the right number of items to return per request etc.
e.g: If we want to request the:
This would look as follows:
// current page to query from the service
page: 5,
// The lowest page index your API allows to be accessed
firstPage: 0, //some begin with 1
// how many results to query from the service (i.e how many to return
// per request)
perPage: 30,
// maximum number of pages that can be queried from
// the server (only here as a default in case your
// service doesn't return the total pages available)
totalPages: 10,
// what field should the results be sorted on?
sortField: 'ReleaseYear',
// what direction should the results be sorted in?
sortDirection: 'asc',
// what would you like to query (search) from the service?
// as Netflix reqires additional parameters around the query
// we simply fill these around our search term
query: "substringof('" + escape('the') + "',Name)",
// what format would you like to request results in?
format: 'json',
// what other custom parameters for the request do
// you require
// for your application?
customParam1: 'allpages',
customParam2: 'callback',As the particular API we're using requires callback and allpages parameters to also be passed, we simply define the values for these as custom parameters which can be mapped back to requestPager as needed.
The last thing we need to do is configure our collection's parse() method. We want to ensure we're returning the correct part of our JSON response containing the data our collection will be populated with, which below is response.d.results (for the Netflix API).
You might also notice that we're setting this.totalPages to the total page count returned by the API. This allows us to define the maximum number of (result) pages available for the current/last request so that we can clearly display this in the UI. It also allows us to infuence whether clicking say, a 'next' button should proceed with a request or not.
parse: function (response) {
// Be sure to change this based on how your results
// are structured (e.g d.results is Netflix specific)
var tags = response.d.results;
//Normally this.totalPages would equal response.d.__count
//but as this particular NetFlix request only returns a
//total count of items for the search, we divide.
this.totalPages = Math.floor(response.d.__count / this.perPage);
return tags;
}
});
});For your convenience, the following methods are made available for use in your views to interact with the requestPager:
The clientPager works similar to the requestPager, except that our configuration values influence the pagination of data already returned at a UI-level. Whilst not shown (yet) there is also a lot more UI logic that ties in with the clientPager. An example of this can be seen in ‘views/clientPagination.js.
As with requestPager, let's first create a new Paginated Backbone.Paginator.clientPager collection, with a model and base URL:
var PaginatedCollection = Backbone.Paginator.clientPager.extend({
model: model,
url: 'http://odata.netflix.com/v2/Catalog/Titles?&',We're similarly going to map request parameter names for your API to those supported in the paginator:
perPageAttribute: '$top',
skipAttribute: '$skip',
orderAttribute: '$orderBy',
customAttribute1: '$inlinecount',
queryAttribute: '$filter',
formatAttribute: '$format',
customAttribute2: '$callback',We then get to configuration for the paginated data in the UI. perPage specifies how many results to return from the server whilst displayPerPage configures how many of the items in returned results to display per 'page' in the UI. e.g If we request 100 results and only display 20 per page, we have 5 sub-pages of results that can be navigated through in the UI.
// M: how many results to query from the service
perPage: 40,
// N: how many results to display per 'page' within the UI
// Effectively M/N = the number of pages the data will be split into.
displayPerPage: 20,We can then configure default values for the rest of our request parameters:
// current page to query from the service
page: 1,
// a default. This should be overridden in the collection's parse()
// sort direction
sortDirection: 'asc',
// sort field
sortField: 'ReleaseYear',
//or year(Instant/AvailableFrom)
// query
query: "substringof('" + escape('the') + "',Name)",
// request format
format: 'json',
// custom parameters for the request that may be specific to your
// application
customParam1: 'allpages',
customParam2: 'callback',And finally we have our parse() method, which in this case isn't concerned with the total number of result pages available on the server as we have our own total count of pages for the paginated data in the UI.
parse: function (response) {
var tags = response.d.results;
return tags;
}
});As mentioned, your views can hook into a number of convenience methods to navigate around UI-paginated data. For clientPager these include:
Although the collection layer is perhaps the most important part of Backbone.Paginator, it would be of little use without views interacting with it. The project zipball comes with three complete examples of using the components with the Netflix API, but here's a sample view and template from the requestPager() example for those interested in learning more:
First, we have a view for a pagination bar in our UI that allows us to navigate around our paginated collection:
(function ( views ) {
views.PaginatedView = Backbone.View.extend({
events: {
'click a.servernext': 'nextResultPage',
'click a.serverprevious': 'previousResultPage',
'click a.orderUpdate': 'updateSortBy',
'click a.serverlast': 'gotoLast',
'click a.page': 'gotoPage',
'click a.serverfirst': 'gotoFirst',
'click a.serverpage': 'gotoPage',
'click .serverhowmany a': 'changeCount'
},
tagName: 'aside',
template: _.template($('#tmpServerPagination').html()),
initialize: function () {
this.collection.on('reset', this.render, this);
this.collection.on('change', this.render, this);
this.$el.appendTo('#pagination');
},
render: function () {
var html = this.template(this.collection.info());
this.$el.html(html);
},
updateSortBy: function (e) {
e.preventDefault();
var currentSort = $('#sortByField').val();
this.collection.updateOrder(currentSort);
},
nextResultPage: function (e) {
e.preventDefault();
this.collection.requestNextPage();
},
previousResultPage: function (e) {
e.preventDefault();
this.collection.requestPreviousPage();
},
gotoFirst: function (e) {
e.preventDefault();
this.collection.goTo(this.collection.information.firstPage);
},
gotoLast: function (e) {
e.preventDefault();
this.collection.goTo(this.collection.information.lastPage);
},
gotoPage: function (e) {
e.preventDefault();
var page = $(e.target).text();
this.collection.goTo(page);
},
changeCount: function (e) {
e.preventDefault();
var per = $(e.target).text();
this.collection.howManyPer(per);
}
});
})( app.views );which we use with a template like this to generate the necessary pagination links (more are shown in the full example):
<span class="divider">/</span>
<% if (page > firstPage) { %>
<a href="#" class="serverprevious">Previous</a>
<% }else{ %>
<span>Previous</span>
<% }%>
<% if (page < totalPages) { %>
<a href="#" class="servernext">Next</a>
<% } %>
<% if (firstPage != page) { %>
<a href="#" class="serverfirst">First</a>
<% } %>
<% if (lastPage != page) { %>
<a href="#" class="serverlast">Last</a>
<% } %>
<span class="divider">/</span>
<span class="cell serverhowmany">
Show
<a href="#" class="selected">3</a>
|
<a href="#" class="">9</a>
|
<a href="#" class="">12</a>
per page
</span>
<span class="divider">/</span>
<span class="cell first records">
Page: <span class="current"><%= page %></span>
of
<span class="total"><%= totalPages %></span>
shown
</span>
<span class="divider">/</span>
<span class="cell sort">
<a href="#" class="orderUpdate btn small">Sort by:</a>
</span>
<select id="sortByField">
<option value="cid">Select a field to sort on</option>
<option value="ReleaseYear">Release year</option>
<option value="ShortName">Alphabetical</option>
</select>
</span> The first major hurdle developers typically run into when building Backbone applications with jQuery Mobile is that both frameworks have their own opinions about how to handle application navigation.
Backbone's routers offer an explicit way to define custom navigation routes through Backbone.Router, whilst jQuery Mobile encourages the use of URL hash fragments to reference separate 'pages' or views in the same document. jQuery Mobile also supports automatically pulling in external content for links through XHR calls meaning that there can be quite a lot of inter-framework confusion about what a link pointing at '#photo/id' should actually be doing.
Some of the solutions that have been previously proposed to work-around this problem included manually patching Backbone or jQuery Mobile. I discourage opting for these techniques as it becomes necessary to manually patch your framework builds when new releases get made upstream.
There's also jQueryMobile router, which tries to solve this problem differently, however I think my proposed solution is both simpler and allows both frameworks to cohabit quite peacefully without the need to extend either. What we're after is a way to prevent one framework from listening to hash changes so that we can fully rely on the other (e.g. Backbone.Router) to handle this for us exclusively.
Using jQuery Mobile this can be done by setting:
$.mobile.hashListeningEnabled = false;prior to initializing any of your other code.
I discovered this method looking through some jQuery Mobile commits that didn't make their way into the official docs, but am happy to see that they are now covered here http://jquerymobile.com/test/docs/api/globalconfig.html in more detail.
The next question that arises is, if we're preventing jQuery Mobile from listening to URL hash changes, how can we still get the benefit of being able to navigate to other sections in a document using the built-in transitions and effects supported? Good question. This can now be solve by simply calling $.mobile.changePage() as follows:
var url = '#about',
effect = 'slideup',
reverse = false,
changeHash = false;
$.mobile.changePage( url , { transition: effect}, reverse, changeHash );In the above sample, url can refer to a URL or a hash identifier to navigate to, effect is simply the transition effect to animate the page in with and the final two parameters decide the direction for the transition (reverse) and whether or not the hash in the address bar should be updated (changeHash). With respect to the latter, I typically set this to false to avoid managing two sources for hash updates, but feel free to set this to true if you're comfortable doing so.
Note: For some parallel work being done to explore how well the jQuery Mobile Router plugin works with Backbone, you may be interested in checking out https://github.com/Filirom1/jquery-mobile-backbone-requirejs.
Note: The code for this practical can be found in practicals/modular-mobile-app.
Once you feel comfortable with the Backbone fundamentals and you've put together a rough wireframe of the app you may wish to build, start to think about your application architecture. Ideally, you'll want to logically separate concerns so that it's as easy as possible to maintain the app in the future.
Namespacing
For this application, I opted for the nested namespacing pattern. Implemented correctly, this enables you to clearly identify if items being referenced in your app are views, other modules and so on. This initial structure is a sane place to also include application defaults (unless you prefer maintaining those in a separate file).
window.mobileSearch = window.mobileSearch || {
views: {
appview: new AppView
},
routers:{
workspace:new Workspace()
},
utils: utils,
defaults:{
resultsPerPage: 16,
safeSearch: 2,
maxDate:'',
minDate:'01/01/1970'
}
}Models
In the Flickly application, there are at least two unique types of data that need to be modeled - search results and individual photos, both of which contain additional meta-data like photo titles. If you simplify this down, search results are actually groups of photos in their own right, so the application only requires:
Views
The views we'll need include an application view, a search results view and a photo view. Static views or pages of the single-page application which do not require a dynamic element to them (e.g an 'about' page) can be easily coded up in your document's markup, independent of Backbone.
Routers
A number of possible routes need to be taken into consideration:
#search/kiwis#search/kiwis/srelevance/p7#photo/93839This tutorial will be expanded shortly to fully cover the demo application. In the mean time, please see the practicals folder for the completed application that demonstrates the router resolution discussed earlier between Backbone and jQuery Mobile.
The majority of jQM apps I've seen in production have been developed for the purpose of providing an optimal experience to users on mobile devices. Given that the framework was developed for this purpose, there's nothing fundamentally wrong with this, but many developers forget that jQM is a UI framework not dissimilar to jQuery UI. It's using the widget factory and is capable of being used for a lot more than we give it credit for.
If you open up Flickly in a desktop browser, you'll get an image search UI that's modeled on Google.com, however, review the components (buttons, text inputs, tabs) on the page for a moment. The desktop UI doesn't look anything like a mobile application yet I'm still using jQM for theming mobile components; the tabs, date-picker, sliders - everything in the desktop UI is re-using what jQM would be providing users on mobile devices. Thanks to some media queries, the desktop UI can make optimal use of whitespace, expanding component blocks out and providing alternative layouts whilst still making use of jQM as a component framework.
The benefit of this is that I don't need to go pulling in jQuery UI separately to be able to take advantage of these features. Thanks to the recent ThemeRoller my components can look pretty much exactly how I would like them to and users of the app can get a jQM UI for lower-resolutions and a jQM-ish UI for everything else.
The takeaway here is just to remember that if you're not (already) going through the hassle of conditional script/style loading based on screen-resolution (using matchMedia.js etc), there are simpler approaches that can be taken to cross-device component theming.