0% found this document useful (0 votes)
16 views80 pages

Javascript and Node Fundamentals 1St Edition by Azat Mardan Isbn B00Hdyhkn6 Download

The document provides a list of various JavaScript and Node.js eBooks available for download, including titles like 'JavaScript and Node FUNdamentals' by Azat Mardan and 'JavaScript Data Structures and Algorithms' by Sammie Bae. Each entry includes the book's ISBN and a link for instant download in multiple formats. Additionally, it mentions the Lean Publishing process used for publishing the book 'JavaScript and Node FUNdamentals'.

Uploaded by

phtjkyqroo1694
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views80 pages

Javascript and Node Fundamentals 1St Edition by Azat Mardan Isbn B00Hdyhkn6 Download

The document provides a list of various JavaScript and Node.js eBooks available for download, including titles like 'JavaScript and Node FUNdamentals' by Azat Mardan and 'JavaScript Data Structures and Algorithms' by Sammie Bae. Each entry includes the book's ISBN and a link for instant download in multiple formats. Additionally, it mentions the Lean Publishing process used for publishing the book 'JavaScript and Node FUNdamentals'.

Uploaded by

phtjkyqroo1694
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

JavaScript and Node FUNdamentals 1st Edition by

Azat Mardan ISBN B00HDYHKN6 download

https://ebookball.com/product/javascript-and-node-
fundamentals-1st-edition-by-azat-mardan-isbn-b00hdyhkn6-13414/

Download more ebook instantly today at https://ebookball.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

JavaScript Data Structures and Algorithms An Introduction to


Understanding and Implementing Core Data Structure and Algorithm
Fundamentals 1st Editon by Sammie Bae ISBN 1484239873 9781484239872

https://ebookball.com/product/javascript-data-structures-and-
algorithms-an-introduction-to-understanding-and-implementing-
core-data-structure-and-algorithm-fundamentals-1st-editon-by-
sammie-bae-isbn-1484239873-9781484239872-15798/

Node Up and Running 1st Edition by Tom Hughes Croucher, Mike Wilson
ISBN 9781449336950 1449336957

https://ebookball.com/product/node-up-and-running-1st-edition-by-
tom-hughes-croucher-mike-wilson-
isbn-9781449336950-1449336957-20224/

jQuery and JavaScript Phrasebook 1st Edition by Brad Dayley ISBN


0133410854 9780133410853

https://ebookball.com/product/jquery-and-javascript-
phrasebook-1st-edition-by-brad-dayley-
isbn-0133410854-9780133410853-12804/

JavaScript and Ajax for Dummies 1st Edition by Andy Harris ISBN
0470417994 9780470417997

https://ebookball.com/product/javascript-and-ajax-for-
dummies-1st-edition-by-andy-harris-
isbn-0470417994-9780470417997-13728/
JavaScript Mini FAQ 1st Edition by Danny Goodman ISBN

https://ebookball.com/product/javascript-mini-faq-1st-edition-by-
danny-goodman-isbn-11420/

Beginning HTML XHTML CSS and JavaScript 1st edition by Jon Duckett
ISBN 8126525515 9788126525515

https://ebookball.com/product/beginning-html-xhtml-css-and-
javascript-1st-edition-by-jon-duckett-
isbn-8126525515-9788126525515-10940/

Web Animation using JavaScript Develop and Design 1st Edition by


Julian Shapiro ISBN 0134096703 9780134096704

https://ebookball.com/product/web-animation-using-javascript-
develop-and-design-1st-edition-by-julian-shapiro-
isbn-0134096703-9780134096704-16170/

JavaScript and jQuery Interactive Front End Web Development 1st


Edition by Jon Duckett ISBN 1118531647 9781118531648

https://ebookball.com/product/javascript-and-jquery-interactive-
front-end-web-development-1st-edition-by-jon-duckett-
isbn-1118531647-9781118531648-16160/

Advanced JavaScript 2nd Edition by Chuck Easttom ISBN 155622852X


9781556228520

https://ebookball.com/product/advanced-javascript-2nd-edition-by-
chuck-easttom-isbn-155622852x-9781556228520-13370/
JavaScript and Node FUNdamentals
A Collection of Essential Basics

Azat Mardan
This book is for sale at http://leanpub.com/jsfun

This version was published on 2014-05-29

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.

©2013 - 2014 Azat Mardan


Tweet This Book!
Please help Azat Mardan by spreading the word about this book on Twitter!
The suggested hashtag for this book is #JavaScriptFUNdamentals.
Find out what other people are saying about the book by clicking on this link to search for this
hashtag on Twitter:
https://twitter.com/search?q=#JavaScriptFUNdamentals
Also By Azat Mardan
Rapid Prototyping with JS
Oh My JS
Express.js Guide
Contents

1 JavaScript FUNdamentals: The Powerful and Misunderstood Language of The Web . 2


1.1 Expressiveness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Loose Typing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Object Literal Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6 Prototypal Nature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7 Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.8 No Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.9 Immediately-Invoked Function Expressions (IIFEs) . . . . . . . . . . . . . . . . . . . 8
1.10 Keyword “this” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.11 Pitfalls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.12 Further Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2 CoffeeScript FUNdamentals: The Better JavaScript . . . . . . . . . . . . . . . . . . . . 11


2.1 Semicolons, Whitespace and Parentheses . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2 Vars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.3 Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.5 Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.6 Arrays and Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.7 Splats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.8 Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.9 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

3 Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks . . . . . 25


3.1 Typical Backbone.js App Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.2 Setting up Backbone.js App from Scratch . . . . . . . . . . . . . . . . . . . . . . . . 26
3.3 Dependencies for the Backbone.js Project . . . . . . . . . . . . . . . . . . . . . . . . 27
3.4 Working with Backbone.js Collections . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.5 Event Binding with Backbone.js and jQuery . . . . . . . . . . . . . . . . . . . . . . 39
3.6 Backbone.js Views and Subviews with Underscore.js . . . . . . . . . . . . . . . . . . 44
3.7 Super Simple Backbone Starter Kit . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.8 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
CONTENTS

4 Node.js FUNdamentals: JavaScript on The Server . . . . . . . . . . . . . . . . . . . . . 55


4.1 Read-Eval-Print Loop (a.k.a. Console) in Node.js . . . . . . . . . . . . . . . . . . . . 57
4.2 Launching Node.js Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.3 Node.js Process Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.4 Accessing Global Scope in Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.5 Exporting and Importing Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.6 Buffer is a Node.js Super Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.7 __dirname vs. process.cwd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.8 Handy Utilities in Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.9 Reading and Writing from/to The File System in Node.js . . . . . . . . . . . . . . . . 62
4.10 Streaming Data in Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
4.11 Installing Node.js Modules with NPM . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.12 Hello World Server with HTTP Node.js Module . . . . . . . . . . . . . . . . . . . . 63
4.13 Debugging Node.js Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
4.14 Taming Callbacks in Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
4.15 Introduction to Node.js with Ryan Dahl . . . . . . . . . . . . . . . . . . . . . . . . . 65
4.16 Moving Forward with Express.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

5 Express.js FUNdamentals: The Most Popular Node.js Framework . . . . . . . . . . . . 67


5.1 Express.js Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.2 Express.js Command-Line Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.3 Routes in Express.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.4 Middleware as The Backbone of Express.js . . . . . . . . . . . . . . . . . . . . . . . 69
5.5 Configuration of an Express.js App . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5.6 Jade is Haml for Express.js/Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5.7 Conclusion About The Express.js Framework . . . . . . . . . . . . . . . . . . . . . . 70
5.8 Update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

6 About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71


6.1 Errata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
6.2 Contact Us . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
CONTENTS 1

If it’s not fun, it’s not JavaScript.


1 JavaScript FUNdamentals: The
Powerful and Misunderstood
Language of The Web
1.1 Expressiveness
Programming languages like BASIC, Python, C has boring machine-like nature which requires
developers to write extra code that’s not directly related to the solution itself. Think about line
numbers in BASIC or interfaces, classes and patterns in Java.
On the other hand JavaScript inherits the best traits of pure mathematics, LISP, C# which lead to a
great deal of expressiveness¹ (and fun!).
More about Expressive Power in this post: What does “expressive” mean when referring to
programming languages?²
The quintessential Hello World example in Java (remember, Java is to JavaScript is what ham to a
hamster):

1 public class HelloWorld {


2 public static void main(String[] args) {
3 System.out.println("Hello World");
4 }
5 }

The same example in JavaScript:

1 console.log('Hello World')

or from within an HTML page:

¹http://en.wikipedia.org/wiki/Expressive_power
²http://stackoverflow.com/questions/638881/what-does-expressive-mean-when-referring-to-programming-languages
JavaScript FUNdamentals: The Powerful and Misunderstood Language of The Web 3

1 <script>
2 document.write('Hello World')
3 </script>

JavaScript allows programmers to focus on the solution/problem rather that to jump through hoops
and API docs.

1.2 Loose Typing


Automatic type casting works well most of the times. It a great feature that saves a lot of time and
mental energy! There’re only a few primitives types:

1. String
2. Number (both integer and real)
3. Boolean
4. Undefined
5. Null

Everything else is an object, i.e., mutable keyed collections. Read Stackoverflow on What does
immutable mean?³
Also, in JavaScript there are String, Number and Boolean objects which contain helpers for the
primitives:

1 'a' === new String('a') //false

but

1 'a' === new String('a').toString() //true

or

1 'a' == new String('a') //true

By the way, == performs automatic type casting while === not.

1.3 Object Literal Notation


Object notation is super readable and compact:
³http://stackoverflow.com/questions/3200211/what-does-immutable-mean
JavaScript FUNdamentals: The Powerful and Misunderstood Language of The Web 4

1 var obj = {
2 color: "green",
3 type: "suv",
4 owner: {
5 ...
6 }
7 }

Remember that functions are objects?

1 var obj = function () {


2 this.color: "green",
3 this.type: "suv",
4 this.owner: {
5 ...
6 }
7 }

1.4 Functions
Functions are first-class citizens, and we treat them as variables, because they are objects! Yes,
functions can even have properties/attributes.

1.4.1 Create a Function


1 var f = function f () {
2 console.log('Hi');
3 return true;
4 }

or

1 function f () {
2 console.log('Hi');
3 return true;
4 }

Function with a property (remember functions are just object that can be invoked, i.e. initialized):
JavaScript FUNdamentals: The Powerful and Misunderstood Language of The Web 5

1 var f = function () {console.log('Boo');}


2 f.boo = 1;
3 f(); //outputs Boo
4 console.log(f.boo); //outputs 1

Note: the return keyword is optional. In case its omitted the function will return undefined upon
invocation.

1.4.2 Pass Functions as Params


1 var convertNum = function (num) {
2 return num + 10;
3 }
4
5 var processNum = function (num, fn) {
6 return fn(num);
7 }
8
9 processNum(10, convertNum);

1.4.3 Invocation vs. Expression


Function definition:

1 function f () {};

Invocation:

1 f();

Expression (because it resolve to some value which could be a number, a string, an object or a
boolean):

1 function f() {return false;}


2 f();

Statement:
JavaScript FUNdamentals: The Powerful and Misunderstood Language of The Web 6

1 function f(a) {console.log(a);}

1.5 Arrays
Arrays are also objects which have some special methods inherited from Array.prototype⁴ global
object. Nevertheless, JavaScript Arrays are not real arrays. Instead, they are objects with unique
integer (usually 0-based) keys.

1 var arr = [];


2 var arr2 = [1, "Hi", {a:2}, function () {console.log('boo');}];
3 var arr3 = new Array();
4 var arr4 = new Array(1,"Hi", {a:2}, function () {console.log('boo');});

1.6 Prototypal Nature


There are no classes in JavaScript because objects inherit directly from other objects which is called
prototypal inheritance: There are a few types of inheritance patterns in JS:

• Classical
• Pseudo-classical
• Functional

Example of the functional inheritance pattern:

1 var user = function (ops) {


2 return { firstName: ops.name || 'John'
3 , lastName: ops.name || 'Doe'
4 , email: ops.email || '[email protected]'
5 , name: function() { return this.firstName + this.lastName}
6 }
7 }
8
9 var agency = function(ops) {
10 ops = ops || {}
11 var agency = user(ops)
12 agency.customers = ops.customers || 0
13 agency.isAgency = true
14 return agency
15 }
⁴https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Properties
JavaScript FUNdamentals: The Powerful and Misunderstood Language of The Web 7

1.7 Conventions
Most of these conventions (with semi-colons being an exception) are stylistic, and highly preferential
and don’t impact the execution.

1.7.1 Semi-Colons
Optional semi-colons, except for two cases:

1. In for loop construction: for (var i=0; i++; i<n)


2. When a new line starts with parentheses, e.g., Immediately-Invoked Function Expression
(IIFE): ;(function(){...}())

1.7.2 camelCase
cameCase, except for class names which are CapitalCamelCase, e.g.,

1 var MainView = Backbone.View.extend({...})


2 var mainView = new MainView()

1.7.3 Naming
_,$ are perfectly legitimate characters for the literals (jQuery and Underscore libraries use them a
lot).
Private methods and attributes start with _ (does nothing by itself!).

1.7.4 Commas
Comma-first approach

1 var obj = { firstName: "John"


2 , lastName: "Smith"
3 , email: "[email protected]"
4 }

1.7.5 Indentation
Usually it’s either tab, 4 or 2 space indentation with their supporters’ camps being almost religiously
split between the options.
JavaScript FUNdamentals: The Powerful and Misunderstood Language of The Web 8

1.7.6 White spaces


Usually, there is a space before and after =, +, { and } symbols. There is no space on invocation, e.g.,
arr.push(1);, but there’s a space when we define an anonymous function: function () {}.

1.8 No Modules
At least until ES6⁵, everything is in the global scope, a.k.a. window and included via <script> tags.
However, there are external libraries that allow for workarounds:

• CommonJS⁶
• AMD and Require.js⁷

Node.js uses CommonJS-like syntax and has build-in support for modules.
To hide your code from global scope, make private attributes/methods use closures and immediately-
invoked function expressions⁸ (or IIFEs).

1.9 Immediately-Invoked Function Expressions (IIFEs)


1 (function () {
2 window.yourModule = {
3 ...
4 };
5 }());

This snippet show an example of a object with private attribute and method:

⁵https://wiki.mozilla.org/ES6_plans
⁶http://www.commonjs.org/
⁷http://requirejs.org/
⁸http://en.wikipedia.org/wiki/Immediately-invoked_function_expression
JavaScript FUNdamentals: The Powerful and Misunderstood Language of The Web 9

1 (function () {
2 window.boo = function() {
3 var _a = 1;
4 var inc = function () {
5 _a++;
6 console.log(_a);
7 return _a;
8 };
9 return {
10 increment: inc
11 };
12 }
13 }());
14 var b = window.boo();
15 b.increment();

Now try this:

1 b.increment();
2 b.increment();
3 b.increment();

1.10 Keyword “this”


Mutates/changes a lot (especially in jQuery)! Rule of thumb is to re-assign to a locally scoped variable
before attempting to use this inside of a closure:

1 var app = this


2 $('a').click(function(e){
3 console.log(this) //most likely the event or the target anchor element
4 console.log(app) //that's what we want!
5 app.processData(e)
6 })

When in doubt: console.log!

1.11 Pitfalls
JS is the only language that programmers think they shouldn’t learn. Things like === vs. ==, global
scope leakage, DOM, etc. might lead to problems down the road. This is why it’s important to
understand the language or use something like CoffeeScript, that take a way most of the issues.
JavaScript FUNdamentals: The Powerful and Misunderstood Language of The Web 10

1.12 Further Learning


If you liked this articled and would like to explore JavaScript more, take a look at this amazing free
resource: Eloquent JavaScript: A Modern Introduction to Programming⁹.
Of course for more advanced JavaScript enthusiasts and pros, there’s my book Rapid Prototyping
with JS¹⁰ and intensive programming school HackReactor¹¹, where I teach part-time.
⁹http://eloquentjavascript.net/
¹⁰http://rpjs.co
¹¹http://hackreactor.com
2 CoffeeScript FUNdamentals: The
Better JavaScript
The CoffeeScript is a language that was built on top of JavaScript. CoffeeScript has some added
benefits and its code is compiled into native JavaScript for execution. The CoffeeScript pros include:
better syntax, function and class construction patterns, automatic var insertion, comprehensions
and others.
Most of these perks will be obvious once we take a look at some examples. This quick language
reference can get you started with CoffeeScript:

• Semicolons, Whitespace and Parentheses


• Vars
• Conditions
• Functions
• Classes
• Arrays
• Splats
• Comprehensions

2.1 Semicolons, Whitespace and Parentheses


While in JavaScript, semicolons are redundant and optional; in CoffeeScript they are banned.
The whitespace and indentation (typically two-space) are parts of the CoffeeScript language.
Parentheses for function invocation are optional (except when there are no arguments). The same
goes for curly braces for object literals. We can even next objects without curly braces:
CoffeeScript FUNdamentals: The Better JavaScript 12

1 a =
2 x: 1
3 y: -20
4 z: () ->
5 console.log a.x+a.y
6
7 a.z()
8
9 b = [
10 1,
11 2,
12 x: 10
13 y: 20
14 ]

Translates into this JavaScript:

1 var a, b;
2
3 a = {
4 x: 1,
5 y: -20,
6 z: function() {
7 return console.log(a.x + a.y);
8 }
9 };
10
11 a.z();
12
13 b = [
14 1, 2, {
15 x: 10,
16 y: 20
17 }
18 ];

As you might have noticed, the logical block’s curly braces that we use to write code for functions
(i.e., {}) are also replaced by indentation. Let’s not forget that functions are just objects in JavaScript.
:-)
CoffeeScript FUNdamentals: The Better JavaScript 13

2.2 Vars
CoffeeScript automatically inserts var keywords for us and prohibits manual usage of var. For
example, a,b, and c variable declarations will have the var in the JavaScript code:

1 a = 10
2 b = 'x'
3 c = [1,2,3]

JavaScript code:

1 var a, b, c;
2
3 a = 10;
4
5 b = 'x';
6
7 c = [1, 2, 3];

CoffeeScript always puts vars at the top of the scope where this particular variable was encountered
first. The scope is defined by the function or window. For example, the anonymous function d will
have e scoped to it, because CoffeeScript first saw e inside of the function:

1 a = 10
2 b = 'x'
3 c = [1,2,3]
4
5 d = () ->
6 e = a
7 console.log e
8 d()

JavaScript output:
CoffeeScript FUNdamentals: The Better JavaScript 14

1 var a, b, c, d;
2
3 a = 10;
4
5 b = 'x';
6
7 c = [1, 2, 3];
8
9 d = function() {
10 var e;
11 e = a;
12 return console.log(e);
13 };
14
15 d();

2.3 Conditions
Conditions are more readable by humans (English-like?) in CoffeeScript:

1 a = b = c = d = 1
2 if a is b or b isnt c and not c is d
3 console.log 'true'
4 else
5 console.log 'false'

1 var a, b, c, d;
2
3 a = b = c = d = 1;
4
5 if (a === b || b !== c && !c === d) {
6 console.log('true');
7 } else {
8 console.log('false');
9 }

So is is ===, isnt is !==, not is !, and is &&, and or is ||.


In CoffeeScript some fancy and arguably more readable constructions are possible:
CoffeeScript FUNdamentals: The Better JavaScript 15

1 console.log a if a is not null


2 if a isnt null then console.log a
3 if not a is null then console.log a
4 unless a is null then console.log a

Note: unless is just a shortcut for if not.

2.4 Functions
Functions in CoffeeScript are defined with arrows ()-> and and fat arrows ()=> (more on this later):

1 a = (x,y) -> console.log x+y


2 a(10,-5)

JavaScript code:

1 var a;
2
3 a = function(x, y) {
4 return console.log(x + y);
5 };
6
7 a(10, -5);

Longer expressions can be on multiple lines using indentation, while the default values can be
assigned right in the function signature (i.e., (name=value)):

1 a = (x, y, z=15) ->


2 sum = x + y + z
3 console.log sum
4 a(10,-5)
CoffeeScript FUNdamentals: The Better JavaScript 16

1 var a;
2
3 a = function(x, y, z) {
4 var sum;
5 if (z == null) {
6 z = 15;
7 }
8 sum = x + y + z;
9 return console.log(sum);
10 };
11
12 a(10, -5);

So back to the far arrow, it does two things: 1. Defines a function 2. Binds the new function’s scope
to the current value of this
Remember that this is dynamically scoped, i.e., its meaning changes based on where it is situated
in the code (what’s the scope). For example, if we have a jQuery event handler click, we might
want to use this as the object in which we defined the handler, not as the DOM element to which
the handler is bound.
For example, this CoffeeScript code will return window object both times (that’s what we want):

1 console.log @
2 $('div').click ()=>
3 console.log @

The JavaScript code:

1 console.log(this);
2
3 $('div').click((function(_this) {
4 return function() {
5 return console.log(_this);
6 };
7 })(this));

However, with single arrows it’s back to the DOM scope for the event handler, (this might be bad if
unexpected):
CoffeeScript FUNdamentals: The Better JavaScript 17

1 console.log @
2 $('div').click ()->
3 console.log @

1 console.log(this);
2
3 $('div').click(function() {
4 return console.log(this);
5 });

Traditionally for the snippet above, without the CoffeeScript’s far arrows, you would see workarounds
like these which use interim variables like that, self, or _this:

1 console.log(this);
2 var that = this;
3 $('div').click(function() {
4 return console.log(that);
5 });

2.5 Classes
Classes are probably the most yummiest and the most complex and confusing feature in CoffeeScript.
In JavaScript classes are absent at all! We use prototypes instead, so the objects inherit from other
objects. We can also use factories, i.e., the functions that create objects.
However, if a developer wants to implement a class, it could be really tricky and often requires a
good understanding of pseudo-classical instantiation patterns. This is not the case with CoffeeScript,
which introduces class keyword. Inside of the class we can use constructor method and super
call, for the initialization logic and the invocation of the parent’s methods correspondingly.
For example, we have a parent class Vehicle from which we extend two classes Compact and Suv. In
these classes, we write custom move methods with the super call, that allows us to re-use the logic
from the parent class Vehicle.
CoffeeScript FUNdamentals: The Better JavaScript 18

1 class Vehicle
2 constructor: (@name) ->
3
4 move: (meters) ->
5 console.log @name + " moved #{meters} miles."
6
7 class Compact extends Vehicle
8 move: ->
9 console.log "Cruising..."
10 super 5
11
12 class Suv extends Vehicle
13 move: ->
14 console.log "Speeding..."
15 super 45
16
17 camry = new Compact "Camry"
18 caddi = new Suv "Cadillac"
19
20 camry.move()
21 caddi.move()

The console outputs this:

1 Cruising...
2 Camry moved 5 miles.
3 Speeding...
4 Cadillac moved 45 miles.

The JavaScript output is quite lengthy, so no wonder developers often prefer functional or other
patterns:

1 var Compact, Suv, Vehicle, caddi, camry,


2 __hasProp = {}.hasOwnProperty,
3 __extends = function(child, parent) { for (var key in parent) { if (__hasProp.c\
4 all(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor \
5 = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child\
6 .__super__ = parent.prototype; return child; };
7
8 Vehicle = (function() {
9 function Vehicle(name) {
10 this.name = name;
CoffeeScript FUNdamentals: The Better JavaScript 19

11 }
12
13 Vehicle.prototype.move = function(meters) {
14 return console.log(this.name + (" moved " + meters + " miles."));
15 };
16
17 return Vehicle;
18
19 })();
20
21 Compact = (function(_super) {
22 __extends(Compact, _super);
23
24 function Compact() {
25 return Compact.__super__.constructor.apply(this, arguments);
26 }
27
28 Compact.prototype.move = function() {
29 console.log("Cruising...");
30 return Compact.__super__.move.call(this, 5);
31 };
32
33 return Compact;
34
35 })(Vehicle);
36
37 Suv = (function(_super) {
38 __extends(Suv, _super);
39
40 function Suv() {
41 return Suv.__super__.constructor.apply(this, arguments);
42 }
43
44 Suv.prototype.move = function() {
45 console.log("Speeding...");
46 return Suv.__super__.move.call(this, 45);
47 };
48
49 return Suv;
50
51 })(Vehicle);
52
CoffeeScript FUNdamentals: The Better JavaScript 20

53 camry = new Compact("Camry");


54
55 caddi = new Suv("Cadillac");
56
57 camry.move();
58
59 caddi.move();

2.6 Arrays and Slicing


Arrays in CoffeeScript can be defined just as they are in native JavaScript: arr = [1, 2, 3]. But we
can do so much more with arrays in CoffeeScript! For example, we can use a range when defining
an array (useful in iterators and comprehensions) and use slice:

1 arr = [1..10]
2 slicedArr = arr[2..4]
3 console.log arr, slicedArr

The console outputs:

1 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [3, 4, 5]

1 var arr, slicedArr;


2
3 arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
4
5 slicedArr = arr.slice(2, 5);
6
7 console.log(arr, slicedArr);

Trivia fact: for array declarations with 20+ items (e.g., range of [0..20] and larger), CoffeeScript
compiler will switch to the for loop.

2.7 Splats
Splats is a better way of using a variable number of arguments and arguments object (from native
JavaScript):
CoffeeScript FUNdamentals: The Better JavaScript 21

1 a = (x...) ->
2 sum = 0
3 x.forEach (item) -> sum += item
4 console.log sum
5 a(10,-5, 15)

1 var a,
2 __slice = [].slice;
3
4 a = function() {
5 var sum, x;
6 x = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
7 sum = 0;
8 x.forEach(function(item) {
9 return sum += item;
10 });
11 return console.log(sum);
12 };
13
14 a(10, -5, 15);

Spats work with invocations too. For example, our sum function from the previous example needs
to treat the array not as a first element, but as all arguments:

1 a = (x...) ->
2 sum = 0
3 x.forEach (item) -> sum += item
4 console.log sum
5
6 a [-5..50]...

The output is 1260. And the JavaScript:


CoffeeScript FUNdamentals: The Better JavaScript 22

1 var a, _i, _results,


2 __slice = [].slice;
3
4 a = function() {
5 var sum, x;
6 x = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
7 sum = 0;
8 x.forEach(function(item) {
9 return sum += item;
10 });
11 return console.log(sum);
12 };
13
14 a.apply(null, (function() {
15 _results = [];
16 for (_i = -5; _i <= 50; _i++){ _results.push(_i); }
17 return _results;
18 }).apply(this));

2.8 Comprehensions
The last but not least topic is comprehensions. They are probably the most used feature in
CoffeeScript and replace (or at least try to replace) all loops.
For example, a simple iteration over an array:

1 arr = [
2 'x',
3 'y',
4 'z'
5 ]
6
7 for a in arr
8 console.log a

The console output is:

1 x
2 y
3 z

The compiled code:


CoffeeScript FUNdamentals: The Better JavaScript 23

1 var a, arr, _i, _len;


2
3 arr = ['x', 'y', 'z'];
4
5 for (_i = 0, _len = arr.length; _i < _len; _i++) {
6 a = arr[_i];
7 console.log(a);
8 }

As is the case with conditions, comprehensions might be reversed in order, e.g., console.log a for
a in arr. Then, we can get an index which will be the second parameter, e.g., console.log a, i
for a, i in arr outputs:

1 x 0
2 y 1
3 z 2

The when clause acts like a filter method; in other words, we can apply a test to the iterator:

1 arr = ['x', 'y', 'z']


2 console.log a, i for a, i in arr when a isnt 'y'

The console outputs:

1 x 0
2 z 2

To step with an increment we can use by: evens = (x for x in [0..10] by 2). In addition, for
iterating over objects we can use of:

1 obj =
2 'x': 10
3 'y':-2
4 'z': 50
5
6 coordinates = for key, value of obj
7 "coordinate #{key} is #{value}pt"
8 console.log coordinates

The console output is:


CoffeeScript FUNdamentals: The Better JavaScript 24

1 ["coordinate x is 10pt", "coordinate y is -2pt", "coordinate z is 50pt"]

The JavaScript code is:

1 var coordinates, key, obj, value;


2
3 obj = {
4 'x': 10,
5 'y': -2,
6 'z': 50
7 };
8
9 coordinates = (function() {
10 var _results;
11 _results = [];
12 for (key in obj) {
13 value = obj[key];
14 _results.push("coordinate " + key + " is " + value + "pt");
15 }
16 return _results;
17 })();

2.9 Conclusion
This CoffeeScript FUNdamentals is a concise overview that should highlight major pros of this
language, which has many more useful features. We hope that classes, arrow function declaration,
comprehensions, splats, and the clean syntax were enough to spark interest and lead to more
exploration and experimentation with CoffeeScript.
Here’s the list of further CoffeeScirpt reading:

• CoffeeScript Quirks¹
• The Little Book on CoffeeScript²
• CoffeeScript Cookbook³
• Smooth CoffeeScript⁴
• CoffeeScript Ristretto⁵

¹http://webapplog.com/coffeescript-quirks/
²http://arcturo.github.io/library/coffeescript/
³http://coffeescriptcookbook.com/
⁴http://autotelicum.github.io/Smooth-CoffeeScript/
⁵https://leanpub.com/coffeescript-ristretto/read
3 Backbone.js FUNdamentals: The
Cornerstone of JavaScript MV*
Frameworks
If you are reading this chapter, you’re probably familiar with the benefits of using an MV* (asterisk
means a controller, another view or something else) over plain jQuery that grows into unmanageable
spaghetti code with time and added complexity.
Backbone.js is the cornerstone of all JavaScript frameworks because it’s one of the most mature
(i.e., dependable) and popular solutions in the ever-growing multitudes of browser JavaScript MV*
(model-view-controllers and model-view-something) frameworks. If we draw a quick comparison
between Backbone.js and other frameworks (not a fair one but still might be useful for some readers),
it will be somewhere in the middle in complexity and features between Spine¹&KnockoutJS² (the
lighter side) and Ember.js³&Angular.js⁴ (heavier side). Which one to choose depends on whether
developers will have to customize a lot (go with lightweights) or use right-out-of-the-box (go with
heavyweights).
A bit of trivia: Backbone.js was created by the same person (Jeremy Ashmenas⁵) that brought
CoffeeScript and Underscore.js to the world!
Therefore, we’ll demonstrate how to build a Backbone.js simple application from scratch. This is
not your typical to-do list, examples of which you can find plenty at TodoMVC⁶, but a simplified
application that is easier to understand but that still uses all components: views, collections,
subviews, models, and event binding. The example is the apple database application.
In this chapter we’ll cover following:

• Typical Backbone.js App Structure


• Setting up Backbone.js App from Scratch
• Dependencies for the Backbone.js Project
• Working with Backbone.js Collections
• Event Binding with Backbone.js and jQuery
• Backbone.js View and Subviews with Backbone.js Underscore.js
• Super Simple Backbone Starter Kit
• Conclusion
¹http://spinejs.com/
²http://knockoutjs.com/
³http://emberjs.com/
⁴https://angularjs.org/
⁵https://twitter.com/jashkenas
⁶http://todomvc.com/
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 26

3.1 Typical Backbone.js App Structure


There are just four classes in Backbone.js:

• Router: mapping of URL to methods


• View: methods related to browser&user events, HTML output (rendering)
• Collection: a list of models with extra helpers such as fetch()
• Model: an individual data item with extra helpers

A typical Backbone.js app will have the main Router class. From that class all the routes (URL paths)
will be defined. The router can create and call methods of other classes such as Views, Collections,
and Models. For example, for path /books we’ll render books view.
The recommended usage is that Views usually have one Collection or one Model. A Collection is
just a list of Models. However, this is not written in stone. Backbone.js is very flexible and should be
used according to the specific needs. For example, an application can have a Model that has Views
and each View that has collections.
In our concise example, we’ll have one main Router that has Views. These Views will have models
and collections.

3.2 Setting up Backbone.js App from Scratch


Firstly, we’re going to build a typical starter “Hello World” application using Backbone.js and the
model-view-controller (MVC) architecture. I know it might sound like overkill in the beginning, but
as we go along we’ll add more and more complexity, including Models, Subviews and Collections.
The structure of the project is keep it simple stupid:

• index.html: the main file and all the application’s JavaScript code
• jquery.js: jQuery library
• underscore.js: Underscore.js library
• backbone.js: Backbone.js library

A full source code for the “Hello World” app is available at GitHub under github.com/azat-
co/rpjs/backbone/hello-world⁷.
jQuery, Underscore are required dependencies for Backbone.js.
⁷https://github.com/azat-co/rpjs/tree/master/backbone/hello-world
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 27

3.3 Dependencies for the Backbone.js Project


To build our apple database, we’ll need to download the following libraries:

• jQuery 1.9 development source file⁸


• Underscore.js development source file⁹
• Backbone.js development source file¹⁰

Alternatively, you can hot-like these libraries from some CDNs (e.g., Google Hosted Libraries¹¹), but
then we’ll need an internet connection every time you run your app.
Include these frameworks in the newly created index.html file like this:

1 <!DOCTYPE>
2 <html>
3 <head>
4 <script src="jquery.js"></script>
5 <script src="underscore.js"></script>
6 <script src="backbone.js"></script>
7
8 <script>
9 //TODO write some awesome JS code!
10 </script>
11
12 </head>
13 <body>
14 </body>
15 </html>

Note
We can also put <script> tags right after the </body> tag in the end of the file. This will
change the order in which scripts and the rest of HTML are loaded and impact performance
in large files.

Some developers shy away from using Backbone Router (it’s an optional class/component), but we
always find that Router brings more benefits and clarity. In a way, it serves as a starting point of
your application and helps to understand the foundation and how all the pieces fit together such as
views, models, etc. So, let’s define a simple Backbone.js Router inside of a <script> tag:
⁸http://code.jquery.com/jquery-1.9.0.js
⁹http://underscorejs.org/underscore.js
¹⁰http://backbonejs.org/backbone.js
¹¹https://developers.google.com/speed/libraries/devguide
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 28

1 ...
2 var router = Backbone.Router.extend({
3 });
4 ...

Note
For now, to Keep It Simple Stupid (KISS), we’ll be putting all of our JavaScript code right
into the index.html file. This is not a good idea for a real development or production code.
We’ll refactor it later.

Then set up a special routes property inside of an extend call:

1 var router = Backbone.Router.extend({


2 routes: {
3 }
4 });

The Backbone.js routes property needs to be in the following format: 'path/:param': 'action'
which will result in the filename#path/param URL triggering a function named action (defined in
the Router object). For now, we’ll add a single home route:

1 var router = Backbone.Router.extend({


2 routes: {
3 '': 'home'
4 }
5 });

This is good, but now we need to add a home function (the right part of the route: action key-value
pair):

1 var router = Backbone.Router.extend({


2 routes: {
3 '': 'home'
4 },
5 home: function(){
6 //TODO render html
7 }
8 });

We’ll come back to the home function later to add more logic for creating and rendering of a View.
Right now, we should define our homeView:
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 29

1 var homeView = Backbone.View.extend({


2 });

Does it look familiar to you? Right, Backbone.js uses similar syntax for all of its components,
such as Backbone.View, Backbone.Router, Backbone.Model and Backbone.Collection. The class
is followed by the extend function and a JSON object as a parameter to it. This object often contains
some initialization options or attributes of the class.
There are multiple ways to proceed from now on, but the best practice is to use the el and template
properties, which are magical, i.e., special in Backbone.js, because they allow us to do two things:

1. el: attach the Backbone View object to a Document Object Model (DOM) element
2. template: store the Underscore (in this case we use Underscore but it can be changed to
another library) template

Here’s the code for the home view:

1 var homeView = Backbone.View.extend({


2 el: 'body',
3 template: _.template('Hello World')
4 });

The property el is just a string that holds the jQuery selector (you can use class name with ‘.’ and id
name with ‘#’). The template property has been assigned an Underscore.js function template with
just a plain text ‘Hello World’.
To render our homeView we use this.$el which is a compiled jQuery object referencing element
in an el property, and the jQuery .html() function to replace HTML with this.template() value.
Here is what the full code for our home Backbone.js View looks like:

1 var homeView = Backbone.View.extend({


2 el: 'body',
3 template: _.template('Hello World'),
4 render: function(){
5 this.$el.html(this.template({}));
6 }
7 });

Now, if we go back to the router we can add these two lines to the home function:
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 30

1 var router = Backbone.Router.extend({


2 routes: {
3 '': 'home'
4 },
5 initialize: function(){
6 // some awesome code that will be executed during object's creation
7 },
8 home: function(){
9 this.homeView = new homeView;
10 this.homeView.render();
11 }
12 });

The first line will create the homeView object and assign it to the homeView property of the router.
The second line will call the render() method in the homeView object, triggering the “Hello World”
output.
Finally, to start a Backbone app, we call new Router inside of a document-ready wrapper to make
sure that the file’s DOM is fully loaded. The app variable is made global in this sense, this helps to
access some Router properties (it’s a good idea to use a prefix specific to your application):

1 var app;
2 $(document).ready(function(){
3 app = new router;
4 Backbone.history.start();
5 })

Confused so far? Don’t be because here is the full code of the index.html file:

1 <!DOCTYPE>
2 <html>
3 <head>
4 <script src="jquery.js"></script>
5 <script src="underscore.js"></script>
6 <script src="backbone.js"></script>
7
8 <script>
9
10 var app;
11
12 var router = Backbone.Router.extend({
13 routes: {
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 31

14 '': 'home'
15 },
16 initialize: function(){
17 //some code to execute
18 //when the object is instantiated
19 },
20 home: function(){
21 this.homeView = new homeView;
22 this.homeView.render();
23 }
24 });
25
26 var homeView = Backbone.View.extend({
27 el: 'body',
28 template: _.template('Hello World'),
29 render: function(){
30 this.$el.html(this.template({}));
31 }
32 });
33
34 $(document).ready(function(){
35 app = new router;
36 Backbone.history.start();
37 })
38
39 </script>
40 </head>
41 <body>
42 <div></div>
43 </body>
44 </html>

Open index.html in the browser to see if it works, i.e., the “Hello World” message should be on the
page.

3.4 Working with Backbone.js Collections


Backbone Collections are useful classes that developers can use for storing any sets of data that
belong to the same type. In other words, Collections are sets or lists of models, and they (collections)
can have their own custom methods and logic as well as some built-in Backbone methods.
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 32

The full source code of Backbone Collections example is under the GitHub’s rpjs/backbone/collec-
tions¹².
This example is about Backbone Collections, and it’s built on top of the previous “Hello World”
example from the Setting up Backbone.js App from Scratch which is available for download at
rpjs/backbone/hello-world¹³.
We should add some data to play around with and to hydrate our views. To do this, add this right
after the script tag and before the other code:

1 var appleData = [
2 {
3 name: "fuji",
4 url: "img/fuji.jpg"
5 },
6 {
7 name: "gala",
8 url: "img/gala.jpg"
9 }
10 ];

Grab the images (see picture below) from GitHub: https://github.com/azat-co/rpjs/tree/master/


backbone/collections/img, or add your own.

Fuji apple illustration

¹²https://github.com/azat-co/rpjs/tree/master/backbone/collections
¹³https://github.com/azat-co/rpjs/tree/master/backbone/hello-world
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 33

Gala apple illustration

This is our apple database. :-) Or to be more accurate, our REST API endpoint-substitute, which
provides us with names and image URLs of the apples (data models). If you want some real-world
servers, you can use:

• Parse.com¹⁴: back-end-as-a-service provider


• Node.js and MongoDB REST API¹⁵: a free-JSON API built with Node.js, Express.js and
MongoDB

Note
This mock dataset can be easily substituted by assigning REST API endpoints of your back-
end to url properties in Backbone.js Collections and/or Models, and calling the fetch()
method on them.
¹⁴http://parse.com
¹⁵http://webapplog.com/express-js-4-node-js-and-mongodb-rest-api-tutorial/
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 34

Now to make the User Experience (UX) a little bit better, we can add a new route to the routes
object in the Backbone Route:

1 ...
2 routes: {
3 '': 'home',
4 'apples/:appleName': 'loadApple'
5 },
6 ...

This will allow users to go to index.html#apples/SOMENAME and expect to see some information
about an apple. This information will be fetched and rendered by the loadApple function in the
Backbone Router definition:

1 loadApple: function(appleName){
2 this.appleView.render(appleName);
3 }

Have you noticed an appleName variable? It’s exactly the same name as the one that we’ve used
in route. This is how we can access query string parameters (e.g., ?param=value&q=search) in
Backbone.js.
Now we’ll need to refactor some more code to create a Backbone Collection, populate it with data
in our appleData variable, and to pass the collection to homeView and appleView. Conveniently
enough, we do it all in the Router constructor method initialize:

1 initialize: function(){
2 var apples = new Apples();
3 apples.reset(appleData);
4 this.homeView = new homeView({collection: apples});
5 this.appleView = new appleView({collection: apples});
6 },

At this point, we’re pretty much done with the Router class, and it should look like this:
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 35

1 var router = Backbone.Router.extend({


2 routes: {
3 '': 'home',
4 'apples/:appleName': 'loadApple'
5 },
6 initialize: function(){
7 var apples = new Apples();
8 apples.reset(appleData);
9 this.homeView = new homeView({collection: apples});
10 this.appleView = new appleView({collection: apples});
11 },
12 home: function(){
13 this.homeView.render();
14 },
15 loadApple: function(appleName){
16 this.appleView.render(appleName);
17 }
18 });

Let’s modify our homeView a bit to see the whole database:

1 var homeView = Backbone.View.extend({


2 el: 'body',
3 template: _.template('Apple data: <%= data %>'),
4 render: function(){
5 this.$el.html(this.template({
6 data: JSON.stringify(this.collection.models)
7 }));
8 }
9 });

For now, we just output the string representation of the JSON object in the browser. This is not
user-friendly at all, but later we’ll improve it by using a list and subviews.
So far, our apple Backbone Collection is very clean and simple:

1 var Apples = Backbone.Collection.extend({


2 });

Note
Backbone automatically creates models inside of a collection when we use the fetch() or
reset() functions.
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 36

Apple view is not any more complex; it has only two properties: template and render. In a template,
we want to display figure, img and figcaption tags with specific values. The Underscore.js template
engine is handy at this task:

1 var appleView = Backbone.View.extend({


2 template: _.template(
3 '<figure>\
4 <img src="<%= attributes.url %>"/>\
5 <figcaption><%= attributes.name %></figcaption>\
6 </figure>'),
7 ...
8 });

To make a JavaScript string, which has HTML tags in it, more readable we can use the backslash
line breaker escape (\) symbol, or close strings and concatenate them with a plus sign (+). This is an
example of appleView above, which is refactored using the latter approach:

1 var appleView = Backbone.View.extend({


2 template: _.template(
3 '<figure>'+
4 +'<img src="<%= attributes.url %>"/>'+
5 +'<figcaption><%= attributes.name %></figcaption>'+
6 +'</figure>'),
7 ...

Please note the ‘<%=’ and ‘%>’ symbols; they are the instructions for Undescore.js to print values in
properties url and name of the attributes object.
Finally, we’re adding the render function to the appleView class.

1 render: function(appleName){
2 var appleModel = this.collection.where({name:appleName})[0];
3 var appleHtml = this.template(appleModel);
4 $('body').html(appleHtml);
5 }

We find a model within the collection via where() method and use [] to pick the first element.
Right now, the render function is responsible for both loading the data and rendering it. Later we’ll
refactor the function to separate these two functionalities into different methods.
The whole app, which is in the rpjs/backbone/collections/index.html¹⁶ folder, looks like this:
¹⁶https://github.com/azat-co/rpjs/tree/master/backbone/collections
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 37

1 <!DOCTYPE>
2 <html>
3 <head>
4 <script src="jquery.js"></script>
5 <script src="underscore.js"></script>
6 <script src="backbone.js"></script>
7
8 <script>
9 var appleData = [
10 {
11 name: "fuji",
12 url: "img/fuji.jpg"
13 },
14 {
15 name: "gala",
16 url: "img/gala.jpg"
17 }
18 ];
19 var app;
20 var router = Backbone.Router.extend({
21 routes: {
22 "": "home",
23 "apples/:appleName": "loadApple"
24 },
25 initialize: function(){
26 var apples = new Apples();
27 apples.reset(appleData);
28 this.homeView = new homeView({collection: apples});
29 this.appleView = new appleView({collection: apples});
30 },
31 home: function(){
32 this.homeView.render();
33 },
34 loadApple: function(appleName){
35 this.appleView.render(appleName);
36 }
37 });
38
39 var homeView = Backbone.View.extend({
40 el: 'body',
41 template: _.template('Apple data: <%= data %>'),
42 render: function(){
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 38

43 this.$el.html(this.template({
44 data: JSON.stringify(this.collection.models)
45 }));
46 }
47 //TODO subviews
48 });
49
50 var Apples = Backbone.Collection.extend({
51
52 });
53 var appleView = Backbone.View.extend({
54 template: _.template('<figure>\
55 <img src="<%= attributes.url %>"/>\
56 <figcaption><%= attributes.name %></figcaption>\
57 </figure>'),
58 //TODO re-write with load apple and event binding
59 render: function(appleName){
60 var appleModel = this.collection.where({
61 name:appleName
62 })[0];
63 var appleHtml = this.template(appleModel);
64 $('body').html(appleHtml);
65 }
66 });
67 $(document).ready(function(){
68 app = new router;
69 Backbone.history.start();
70 })
71
72 </script>
73 </head>
74 <body>
75 <div></div>
76 </body>
77 </html>

Open collections/index.html file in your browser. You should see the data from our “database”,
i.e., Apple data: [{"name":"fuji","url":"img/fuji.jpg"},{"name":"gala","url":"img/gala.jpg"}].
Now, let’ go to collections/index.html#apples/fuji or collections/index.html#apples/gala
in your browser. We expect to see an image with a caption. It’s a detailed view of an item, which in
this case is an apple. Nice work!
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 39

3.5 Event Binding with Backbone.js and jQuery


In real life, getting data does not happen instantaneously, so let’s refactor our code to simulate it. For
a better UI/UX, we’ll also have to show a loading icon (a.k.a., spinner or ajax-loader, see the picture
below) to users to notify them that the information is being loaded.

Spinner GIF

It’s a good thing that we have event binding in Backbone. The event binding is not an exclusive
to Backbone feature, because it is part of jQuery. But without Backbone organization and code
structure, things tend to end up messier (with plain jQuery). For example, we’ll have to pass a
function that renders HTML as a callback to the data loading function, to make sure that the
rendering function is not executed before we have the actual data to display.
Therefore, when a user goes to detailed view (apples/:id) we only call the function that loads the
data. Then, with the proper event listeners, our view will automagically (this is not a typo) update
itself; when there is a new data (or on a data change, Backbone.js supports multiple and even custom
events).
Let’s change the code in the router:

1 ...
2 loadApple: function(appleName){
3 this.appleView.loadApple(appleName);
4 }
5 ...

Everything else remains the same until we get to the appleView class. We’ll need to add a constructor
or an initialize method, which is a special word/property in the Backbone.js framework. It’s called
each time we create an instance of an object, i.e., var someObj = new SomeObject(). We can also
pass extra parameters to the initialize function, as we did with our views (we passed an object
with the key collection and the value of apples Backbone Collection). Read more on Backbone.js
constructors at backbonejs.org/#View-constructor¹⁷.

¹⁷http://backbonejs.org/#View-constructor
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 40

1 ...
2 var appleView = Backbone.View.extend({
3 initialize: function(){
4 //TODO: create and setup model (aka an apple)
5 },
6 ...

Great, we have our initialize function. Now we need to create a model which will represent a
single apple and set up proper event listeners on the model. We’ll use two types of events, change and
a custom event called spinner. To do that, we are going to use the on() function, which takes these
properties: on(event, actions, context) — read more about it at backbonejs.org/#Events-on¹⁸:

1 ...
2 var appleView = Backbone.View.extend({
3 this.model = new (Backbone.Model.extend({}));
4 this.model.bind('change', this.render, this);
5 this.bind('spinner',this.showSpinner, this);
6 },
7 ...

The code above basically boils down to two simple things:

1. Call render() function of appleView object when the model has changed
2. Call showSpinner() method of appleView object when event spinner has been fired.

So far, so good, right? But what about the spinner, a GIF icon? Let’s create a new property in
appleView:

1 ...
2 templateSpinner: '<img src="img/spinner.gif" width="30"/>',
3 ...

Remember the loadApple call in the router? This is how we can implement the function in
appleView:

¹⁸http://backbonejs.org/#Events-on
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 41

1 ...
2 loadApple:function(appleName){
3 this.trigger('spinner');
4 //show spinner GIF image
5 var view = this;
6 //we'll need to access that inside of a closure
7 setTimeout(function(){
8 //simulates real time lag when
9 //fetching data from the remote server
10 view.model.set(view.collection.where({
11 name:appleName
12 })[0].attributes);
13 },1000);
14 },
15 ...

The first line will trigger the spinner event (the function for which we still have to write).
The second line is just for scoping issues (so we can use appleView inside of the closure).
The setTimeout function is simulating a time lag of a real remote server response. Inside of it, we
assign attributes of a selected model to our view’s model by using a model.set() function and a
model.attributes property (which returns the properties of a model).

Now we can remove an extra code from the render method and implement the showSpinner
function:

1 render: function(appleName){
2 var appleHtml = this.template(this.model);
3 $('body').html(appleHtml);
4 },
5 showSpinner: function(){
6 $('body').html(this.templateSpinner);
7 }
8 ...

That’s all! Open index.html#apples/gala or index.html#apples/fuji in your browser and enjoy


the loading animation while waiting for an apple image to load.
The full code of the index.html file:
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 42

1 <!DOCTYPE>
2 <html>
3 <head>
4 <script src="jquery.js"></script>
5 <script src="underscore.js"></script>
6 <script src="backbone.js"></script>
7
8 <script>
9 var appleData = [
10 {
11 name: "fuji",
12 url: "img/fuji.jpg"
13 },
14 {
15 name: "gala",
16 url: "img/gala.jpg"
17 }
18 ];
19 var app;
20 var router = Backbone.Router.extend({
21 routes: {
22 "": "home",
23 "apples/:appleName": "loadApple"
24 },
25 initialize: function(){
26 var apples = new Apples();
27 apples.reset(appleData);
28 this.homeView = new homeView({collection: apples});
29 this.appleView = new appleView({collection: apples});
30 },
31 home: function(){
32 this.homeView.render();
33 },
34 loadApple: function(appleName){
35 this.appleView.loadApple(appleName);
36
37 }
38 });
39
40 var homeView = Backbone.View.extend({
41 el: 'body',
42 template: _.template('Apple data: <%= data %>'),
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 43

43 render: function(){
44 this.$el.html(this.template({
45 data: JSON.stringify(this.collection.models)
46 }));
47 }
48 //TODO subviews
49 });
50
51 var Apples = Backbone.Collection.extend({
52
53 });
54 var appleView = Backbone.View.extend({
55 initialize: function(){
56 this.model = new (Backbone.Model.extend({}));
57 this.model.on('change', this.render, this);
58 this.on('spinner',this.showSpinner, this);
59 },
60 template: _.template('<figure>\
61 <img src="<%= attributes.url %>"/>\
62 <figcaption><%= attributes.name %></figcaption>\
63 </figure>'),
64 templateSpinner: '<img src="img/spinner.gif" width="30"/>',
65
66 loadApple:function(appleName){
67 this.trigger('spinner');
68 var view = this; //we'll need to access
69 //that inside of a closure
70 setTimeout(function(){ //simulates real time
71 //lag when fetching data from the remote server
72 view.model.set(view.collection.where({
73 name:appleName
74 })[0].attributes);
75 },1000);
76
77 },
78
79 render: function(appleName){
80 var appleHtml = this.template(this.model);
81 $('body').html(appleHtml);
82 },
83 showSpinner: function(){
84 $('body').html(this.templateSpinner);
Backbone.js FUNdamentals: The Cornerstone of JavaScript MV* Frameworks 44

85 }
86
87 });
88 $(document).ready(function(){
89 app = new router;
90 Backbone.history.start();
91 })
92
93 </script>
94 </head>
95 <body>
96 <a href="#apples/fuji">fuji</a>
97 <div></div>
98 </body>
99 </html>

3.6 Backbone.js Views and Subviews with


Underscore.js
This example is available at rpjs/backbone/subview¹⁹.
Subviews are Backbone Views that are created and used inside of another Backbone View. A
subviews concept is a great way to abstract (separate) UI events (e.g., clicks) and templates for
similarly structured elements (e.g., apples).
A use case of a Subview might include a row in a table, a list item in a list, a paragraph, a new line,
etc.
We’ll refactor our home page to show a nice list of apples. Each list item will have an apple name
and a “buy” link with an onClick event. Let’s start by creating a subview for a single apple with our
standard Backbone extend() function:

1 ...
2 var appleItemView = Backbone.View.extend({
3 tagName: 'li',
4 template: _.template(''
5 +'<a href="#apples/<%=name%>" target="_blank">'
6 +'<%=name%>'
7 +'</a>&nbsp;<a class="add-to-cart" href="#">buy</a>'),
8 events: {
9 'click .add-to-cart': 'addToCart'
¹⁹https://github.com/azat-co/rpjs/tree/master/backbone/subview
Other documents randomly have
different content
Würtzburg, League of.
A league of the Catholic princes of Germany, formed in 1610, under
Maximilian of Bavaria, to oppose the Protestant Union.

Wyandotte Constitution.
The Constitution of Kansas, adopted in 1859, under which Kansas was
admitted to the Union. It abolished slavery throughout the State.

Wyoming Massacre.
During the American War of Independence in 1778, the settlement in the
Valley of Wyoming, Pennsylvania, was attacked by the British, together
with a band of Seneca Indians. Most of the able-bodied men were in the
field under Washington, and only 300 opposed the British force, which
overpowered them, and accepted their surrender. It was, however,
impossible to control the Indians, who later again attacked the settlement,
and massacred a large number of the inhabitants.
X

X Y Z Mission.
An American mission despatched to France in 1797. Attempts were
made to bribe them, the agents employed using, in their correspondence, the
initials X, Y, Z.
Y

Yandabo, Treaty of.


A treaty between Great Britain and Burmah, signed in 1826, at the end of
the Burmah War of 1824, whereby Great Britain acquired Arrakan and
Tenasserim.

Yangtse Agreement.
See Anglo-German Agreement.

Yankee.
The name first applied to the colonists in the New England States by the
British soldiers during the American War of Independence. It is supposed to
be derived from an Indian corruption of English—“Yengies,” or
“Yanghies.”

Year of Corbie.
This name was given by the French during the Thirty Years’ War to the
year 1636, when the Imperial troops penetrated into France to Corbie,
within fifty miles of Paris, and apparently had the capital at their mercy.
They preferred, however, to retire, loaded with booty, but the imminent
danger was long an unpleasant memory to the Parisians.

Young Cub.
Charles James Fox (1749-1806) was so called.

Young Czechs.
The Radical section of the Czech or National Party in Bohemia.
Young England.
The party of young Tories who strongly opposed the repeal of the Corn
Laws from 1839 to 1846, and favoured a return to the manners and customs
of an earlier day. Among its leaders was Lord John Manners.

Young Ireland Party.


A party formed in Ireland in 1847, as a rival association to the Repealers
who followed O’Connell. Their leaders were Smith O’Brien, Meagher and
Mitchel, and they were in favour of physical force rather than of
constitutional agitation. An abortive attempt at a rising under their auspices
in 1848 was easily suppressed, and the society came to an end immediately
afterwards.

Young Italy.
A secret society founded by Mazzini about 1830, to work for the
emancipation of Italy.

Young Pretender.
Charles Edward Stuart, son of James Edward, and grandson of James II,
was so called by the supporters of the Hanoverian succession.

Young Turks.
The Turkish reform party. For obvious reasons they are for the most part
resident beyond the limits of the Turkish Empire.
Z

Zanzibar, Treaty of.


A treaty between Germany and Zanzibar, signed in 1885. The Sultan of
Zanzibar thereby recognized Germany’s rights over Chagga and
Kilimanjaro, and accorded certain trade facilities to the German East Africa
Company.

Zaporovian Commonwealth.
A community of Free Cossacks on the Dnieper. They were not finally
deprived of their independence till the reign of Catherine II, circ. 1780.

Zehngerichtenbund.
See Ten Jurisdictions.

Zelanti.
A body of Cardinals, headed by Cardinal Orsini, who had great influence
in Rome circ. 1700, and whose efforts were directed towards stricter
discipline in the Church.

Zemindars.
Under the Mohammedan rulers of India, the Zemindars were officers
who were charged with the collection of taxes over a certain district. In
1793 these officers were, in Bengal, converted by Lord Cornwallis into
landowners, each in his own district, who alone paid land-tax to the
Government, and recouped themselves by rents received from the peasants
or ryots. This system is known as the Zemindari System.

Zemstvo.
The Russian provincial and district assemblies are so called. The
Zemstvo is elected, in certain fixed proportions, by the landowners, the
village communes and the municipalities. It meets at least once a year, but
has a permanent bureau, always in session, chosen from among its members
for executive purposes. It is charged with the maintenance of roads and
bridges and other public works, and the supervision of education, sanitation
and agriculture. It also elects the local justices of the peace.

Zollverein.
A union of the German States for commercial purposes, entered into
under the auspices of Prussia in 1833. It provided for free internal trade, and
a uniform system of customs duties for the whole union.

Zurich, Compromise of.


An attempt by Calvin and Farel, in 1549, to amalgamate the different
doctrines of Calvin and Zwingli. It met with little acceptance on the part of
the Protestant Cantons.

Zurich, Treaty of.


A treaty signed in 1859 confirming the Treaty of Villafranca, which
provided for the cession by Austria of Lombardy, to be transferred by
France to Sardinia.
INDEX

A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, Y, Z
Aargau, 231.
Abbaside Khalifs, 23.
Abd-el-Kader, 247.
Abdallah, King of Granada, 1.
Abdul Hamed, Sultan of Turkey, 140.
Abdul Mejid, Sultan of Turkey, 115.
Aboyne, Lord, 42.
Abyssinia, 2, 172.
Acre, 134.
Adams, Samuel, 91, 171.
Adansi, 96.
Addison, Joseph, 139.
Adige (River), 154.
Adjanta Ghât, 235.
Adrian I, Pope, 78.
Adrian IV, Pope, 3.
Adrian VI, Pope, 218.
Adrianople, 3.
Adolphus Frederick of Holstein, 2.
Æthelfled, 95, 141.
Æthelred I, 176.
Æthelred the Unready, 72, 104, 118, 221.
Æthelstan, 117.
Æthelwulf, 193.
Afghanistan, 103, 105, 166, 188, 217, 234.
Afridis, 105, 166.
Agilulf, King of the Lombards, 129.
Ahausen, 204.
Ahmed I, Sultan of Turkey, 174.
Ahmednaggar, 235.
Aix-la-Chapelle, Peace of, 20, 201.
Alabama, 112.
Alabama claims, 275.
Alaska, 11, 26.
Albania, 130, 277.
Albert II, Emperor, 201.
Albert of Brandenburg, 251.
Albuquerque, Alfonso d’, 200.
Alemtejo, 97.
Alençon, 106.
Alençon, Duc d’, 201.
Alexander III, Pope, 3, 48, 190.
Alexander IV, Pope, 150.
Alexander V, Pope, 122, 196, 226.
Alexander VI, Pope, 75, 122, 222.
Alexander I of Russia, 261.
Alexander II of Russia, 174, 230.
Alexander I of Scotland, 232.
Alexander III of Scotland, 156.
Alexandria, 13, 70.
Alfonso I of Aragon, 93.
Alfonso III of Aragon, 13.
Alfonso V of Spain, 102.
Alfonso VI of Spain, 53.
Alfonso the Wise, 234.
Alfred the Great, 79, 141, 160, 170, 276.
Algarves, 97.
Algeria, 233, 247.
Allahabad, 27, 125.
Allen, Cardinal, 3.
Alsace, 99, 163, 191, 277.
Althorp, Lord, 128.
Alva, Duke of, 33, 245.
Amadeus V of Savoy, 12.
Amatongaland, 246.
Amazon (River), 43.
Amboyna, 239.
Amiens, 270.
Amoy, 180.
Amsterdam, 225.
Amurath I, Sultan of Turkey, 131.
Anabaptists, 213.
Anatolia, 14.
Ancona, 256.
Andrassy, Count, 10.
Andres, Last of the Incas, 213.
Andrew II of Hungary, 107.
Anglo-Saxons, 34, 39, 50, 82, 88, 92, 95, 96, 100, 103, 104, 116, 117, 118,
122, 142, 149, 156, 160, 181, 221, 222, 232, 238, 249, 251, 260, 263, 272,
276, 278.
Angola, 63.
Angus, Archibald Sixth Earl of, 18.
Aniello, Tommaso, 161.
Anjou, 1, 38, 101.
Annam, 31, 99, 121, 254.
Anne Boleyn, 244.
Anne de Joyeuse, 217.
Anne of England, 37, 88, 149, 192, 203, 206, 231, 246, 253, 267.
Anne of Austria, 82.
Anne, Regent of France, 112, 124.
Anselm, Archbishop of Canterbury, 26.
Anspach, 204, 227.
Antigua, 38.
Antrim, 242.
Antwerp, 101, 158, 239, 274.
Appenzell, 144, 252.
Arabi Pasha, 81.
Arabia, 166, 274.
Arad, 122.
Aragon, 13, 135, 167.
Arbitration Tribunal, 113.
Archaicus of Scotland, 253.
Arcis-sur-Aube, 15.
Ardalian, 28.
Ardrossan, 274.
Argentine Republic, 104, 196, 259, 269.
Argyll, Archibald Fifth Earl of, 69.
Argyll, Archibald Eighth Earl of, 124, 213, 214.
Arizona, 103.
Arkansas, 26.
Arlington, Henry Earl of, 42.
Armagnacs, 185, 262.
Armellini, 218.
Armenians, 112, 118.
Arminians, 65, 79, 108, 213.
Armstrong, William, 138.
Arnauld, Antoine, 131, 199.
Arnold of Brescia, 117.
Arracan, 280.
Arteveldt, James van, 39.
Artois, 105, 158, 205.
Ashanti, 96.
Ashbourne, Lord, 128.
Ashley, Earl of Shaftesbury, 42.
Assi, 60.
Assumptionists, 18.
Atalanta, 232.
Athens, 78.
Athole, Earl of, 206.
Atterbury, Bishop, 19.
Auckland, Lord, 234.
Auerstadt, Battle of, 31.
Augsburg Confession, 203, 227, 249.
Augsburg, Diet of, 235.
Augsburg, League of, 220.
Augsburg, Religious Peace of, 212.
Augustinus, 124, 131.
Augustus II of Poland, 197, 224.
Austerlitz, Battle of, 253.
Australia, 20, 91, 100, 124.
Austrian Succession, War of the, 201.
Auxerre, 15.
Avalos, Ferdinand de, 225.
Avignon, 256.
Azores, 75.
Azov, 140, 204.

Babek, 136.
Bacon, Nathaniel, 21, 109.
Baden, 105, 202, 215.
Bagimont of Vicci, 21.
Baillie of Jerviswood, 132.
Baji Rao II, 25.
Bakunin, Michael, 127.
Balaclava, Battle of, 73.
Balasore, 75.
Baldwin I of Flanders, 37.
Balfour, A. J., 98.
Balfour, Sir James, 69.
Ballard, Father, 21.
Balliol, Edward, 67, 156.
Balliol, John, 256.
Baltic, 239, 251, 278.
Baltimore, Lord, 161.
Banér, Johan Gustafsson, 148.
Bantry Bay, 175.
Baramahal, 230.
Barbaroux, 92.
Barbés, 222.
Barbiano, Count, 221.
Barcelona, 64.
Barclay, Sir George, 16.
Barebone, Praise-God, 23, 176.
Barlaymont, 65.
Barlow, Sir George, 155.
Barneveldt, Jan van Olden, 15.
Baro (River), 2.
Baroda, 23.
Barré, Isaac, 238.
Barrot, Odilon, 61.
Barton, Elizabeth, 177.
Basle, 225, 252.
Bassano, Duc de, 164, 254.
Bassein, 193, 245.
Basutos, 7, 124, 175, 237, 251.
Batapins, 242.
Bates’ Case, 35.
Bath, William, Earl of, 233.
Batman, John, 199.
Batoum, 28.
Bautzen, Battle of, 236.
Bavaria, 19, 25, 103, 105, 150, 215, 221, 235, 271.
Bayard, Seigneur de, 52.
Bayonne, I.
Beaconsfield, Lord, 28.
Beaugé, Battle of, 262.
Bechuanaland, 136, 168, 242.
Becket, Thomas à, 65.
Bedford, John, Duke of, 94.
Bedford, John, Fourth Duke of, 26.
Belesme, 106.
Belfort, 100.
Belgium, 7, 27, 45, 57, 151, 154, 187, 215, 228.
Benedict IX, Pope, 37.
Benedict XII, Pope, 213.
Benedict XIII, Pope, 196.
Bengal, 281.
Benigsen, Baron, 171.
Berar, 75, 198.
Bérenger, Loi, 150.
Berg, 215.
Berghem, 158.
Berlichingen, Götz von, 130, 191.
Berlin, 4, 63, 134.
Berlin Congress, 120, 224.
Bermudez, 88.
Bernadotte, 137.
Bernard, 222.
Berne, 46, 84, 146, 200, 208, 231, 256.
Berri, Duc de, 63.
Berry, Sir Graham, 86.
Bessarabia, 27, 28.
Bessborough, Earl of, 29.
Beza, 58.
Bezuidenhoot, Jan, 236.
Billioray, 60.
Birmingham, 210.
Biron, Baron de, 30.
Biscay, 46.
Bismarck, Otto von, 33, 46, 48, 99, 112, 120, 129, 134, 164, 212, 214.
Black Sea, 5, 27, 32, 47, 136, 188, 220.
Blackburn, 32.
Blackheath, 96.
Blaine, J. G., 35, 185, 248.
Blair, F. P., 139.
Blanche of Castile, 24.
Bland, Mr., 32.
Blanqui, Louis Auguste, 60, 222.
Blennerhassett, Harman, 42.
Bligh, Admiral, 36.
Bloemfontein, 33.
Blount, Sir James, 239.
Blucher, Marshal, 98.
Blue Nile, 2.
Boccold, John, 9.
Boer War, 4, 61, 114, 157, 171, 269.
Bogdan of Moldavia, 166.
Bohemia, 157, 168, 179, 180, 201, 202, 280.
Bolingbroke, Henry, Viscount, 178, 190.
Bolivar, Simon, 109, 147, 255.
Bolivia, 9, 184, 225.
Bologna, 10, 145.
Bombay, 35, 189.
Bond, Sir Robert, 35.
Boniface VIII, Pope, 56, 146, 191, 264.
Bonnivard, François de, 203.
Booth, John Wilkes, 35.
Bordeaux, 1, 182, 196.
Boris of Russia, 75.
Bosnia, 28, 217.
Bosphorus, 188, 266.
Bossuet, 56, 211.
Boston, 36, 69, 211, 249.
Bothwell, 48, 69.
Bouillon, Godefroi de, 56, 146.
Boulanger, General, 36.
Boulogne, 36, 48.
Boulonnais, 15.
Bourbon, Adalbert de, 172.
Bourbon, Cardinal de, 133.
Bourbon, Duc de, 29, 201.
Bourbon, General de, 32.
Bourbons, 46, 276.
Bourges, 190.
Bover, 126.
Boycott, Captain, 37.
Boyens, Adrian, 225.
Brabant, 76, 105, 133, 163.
Bradlaugh, Charles, 203.
Braemar, Hunting of, 122.
Brahminism, 16, 37, 104, 139, 234, 244, 245, 268.
Brazil, 43, 74, 87, 256, 259, 261.
Breda, 38.
Brederode, Count Henry of, 112.
Bregenz, 144.
Bremen, 100, 114, 242, 277.
Brescia, 117.
Bresse, 256.
Brétigny, Peace of, 100, 277.
Bretwalda, 117.
Bridgwater, 138.
Briel, 49.
Bright, John, 3, 39, 101, 120, 260.
Brissot, J.P., 39.
Bristol, 39.
British Columbia, 11, 45.
British Guiana, 180, 227, 269.
British South Africa Company, 131.
Brittany, 18, 38, 106.
Brittany, Duke of, 29, 63.
Brooke, George, 42.
Brown, John, 115.
Brown, Major-General, 1.
Brownists, 125.
Bruce, Robert, 176, 209.
Bruges, 107, 158.
Brunswick, Duke of, 31.
Brussels, 40, 193.
Buccleugh, Lord of, 138.
Bucer, Martin, 251.
Buchanan, Mr., 183.
Buckingham, George Villiers, Duke of, 42.
Bulgaria, 6, 24, 28, 41, 55, 224, 237.
Bundelcund, 207.
Burdett, Sir Francis, 207.
Burgos, 41.
Burgundians, 261.
Burgundy, 15, 110, 155, 163.
Burgundy, Duke of, 29.
Burke, Edward, 2.
Burke, T. H., 127, 195.
Burleigh, Cecil Lord, 50.
Burmah, 71, 119, 280.
Burns, John, 257.
Burr, Aaron, 42.
Burrard, Sir Harry, 54.

Caboche, 43.
Cade, Jack, 60, 198.
Cadiz, 64.
Cadiz, Duke of, 239.
Cadoudal, Georges, 53, 195.
Cahors, 9.
Cairns, Earl, 98, 230.
Calais, 38.
Calcutta, 31.
California, 13, 61, 107, 111, 143, 169.
Calixtus II, Pope, 143.
Callao, 147.
Calvin, John, 44, 63, 116, 199, 281.
Calvinists, 44, 63, 108, 116, 122, 141, 147.
Cambacérès, Jean Jacques de, 58.
Cambray, Peace of, 184.
Cambridge, 266.
Camerata, Count, 218.
Cameron, Richard, 44, 224.
Camissards, 87.
Campbells, 107.
Canada, 16, 45, 56, 81, 92, 95, 96, 113, 114, 121, 191, 206, 209, 216, 261.
Canning, George, 135.
Canning, Lord, 56, 183.
Canning, Sir Stratford, 85, 115.
Canossa, 46.
Canton, 180, 247.
Cape Cod, 162.
Cape Colony, 3, 31, 33, 41, 59, 76, 82, 94, 106, 116, 118, 123, 135, 138,
171, 186, 187, 197, 204, 236, 259, 276.
Cape Verde, 256.
Cappel, 46.
Caraffa, John, 251.
Carbonari, 224.
Cardwell, Lord, 15.
Carelia, 177, 243.
Caribbean Sea, 40, 239.
Carisbrooke, 273.
Carlisle, 138.
Carlists, 28.
Carlos, Don, 46.
Carlowitz, Treaty of, 190.
Carlsbad, 47.
Carlyle, Thomas, 266.
Carmarthen, Lord, 175.
Carmel Mount, 47.
Carnarvon, Lord, 232.
Carnot, Lazare Nicolas, 182.
Carolina, 47, 166.
Caroline Islands, 47.
Carrier, 177.
Carpathians, 248.
Cartwright, Thomas, 3.
Casimir the Great of Poland, 278.
Caspian Sea, 112.
Cassano, Battle of, 150.
Cassilis, Earl of, 18.
Cassini, Count, 48.
Castriot, George, 6, 130, 277.
Castro, Thomas, 55.
Catalonia, 4.
Câteau Cambrésis, Treaty of, 270.
Catesby, Robert, 112.
Catherine of Aragon, 177, 244.
Catherine of France, 261.
Catherine II of Russia, 49, 67, 132, 140, 166, 197, 229, 243, 248, 281.
Cavagnari, Sir Louis, 104.
Cavaignac, General, 18.
Cavendish, Lord Frederick, 127, 195.
Cavour, Count, 130.
Cawnpore, 50.
Cayenne, 38.
Cayugas, 96.
Cecil, Earl of Salisbury, 42.
Cerdagne, 23.
Cellier, Mrs., 162.
Celts, 29, 38, 88.
Central America, 53, 62, 72, 185.
Cevennes, 262.
Ceylon, 9.
Chagga, 281.
Chalmers, Dr., 100, 270.
Chamberlain, Joseph, 58, 120, 219.
Chambord, Comte de, 146.
Chambul (River), 207.
Chang How, 140.
Chantaboon, 99.
Charleroi, 24.
Charlemagne, 78, 119, 185, 269.
Charles of Anjou, 233.
Charles, Archduke of Austria, 239.
Charles of Blois, 252.
Charles, Dauphin of France, 38.
Charles I of England, 15, 25, 28, 33, 50, 84, 87, 95, 106, 124, 152, 155,
161, 174, 176, 194, 211, 213, 219, 224, 233, 238, 244, 260, 266, 267, 273.
Charles II of England, 1, 30, 31, 35, 38, 42, 47, 55, 58, 66, 69, 74, 79, 89,
111, 121, 132, 148, 163, 179, 194, 199, 203, 211, 213, 220, 238, 241, 256,
260, 269.
Charles I of France (the Bold), 40, 163, 178, 269.
Charles III of France (the Simple), 35.
Charles V of France, 25, 60.
Charles VI of France, 14, 181, 262.
Charles VII of France, 15, 99, 200, 201.
Charles VIII of France, 23.
Charles IX of France, 131, 221, 261.
Charles X of France, 134, 182, 215.
Charles IV of Germany, 107, 194.
Charles V of Germany, 23, 44, 47, 48, 93, 105, 107, 119, 125, 127, 135,
153, 155, 184, 190, 210, 212, 218, 225, 228, 256.
Charles VI of Germany, 20, 200.
Charles VII of Germany, 99.
Charles III of Savoy, 12, 239.
Charles II of Spain, 239.
Charles III of Spain, 201.
Charles IV of Spain, 97, 199, 203.
Charles X of Sweden, 217.
Charles XII of Sweden, 6, 39, 155, 204, 207, 224.
Charles the Bold of Burgundy, 193.
Charles the Good of Flanders, 144.
Charleston, 211.
Charolais, Comte de, 63.
Charterhouse, 48.
Chartres, 51, 152.
Chartreuse, Grande, 48.
Chattanooga, Battle of, 50.
Chefoo, 52.
Cherbourg, 43.
Chesnelong, M. de, 265.
Chester, 52, 68.
Chiavenna, 167.
Chicago, 91.
Chihli, 247.
Chile, 9, 168, 184, 192, 225.
Chillon, Castle of, 203.
China, 4, 10, 19, 37, 48, 52, 97, 110, 140, 148, 152, 159, 164, 170, 172,
180, 186, 192, 233, 234, 247, 254, 259, 262, 274.
Chinandega, 53.
Choshiu, 71.
Chotusitz, Battle of, 38.
Chouiski, 27.
Christian (Mate of the Bounty), 36.
Christian of Anhalt, 204.
Christian II of Denmark, 33.
Christian III of Denmark, 91, 208.
Christian IV of Denmark, 153.
Christian V of Denmark, 72, 85, 135.
Christian IX of Denmark, 226.
Christian of Schleswig Holstein, 15, 226.
Christian of Spain, 53, 88, 140.
Christina of Sweden, 165, 237.
Churchill, Lord Randolph, 98, 257.
Cinq Mars, 53.
Cis-Alpine Republic, 45.
Ciudad Rodrigo, 256.
Clare, County, 250, 257.
Clare, Richard de, 192, 243.
Clarendon, Lord, 47, 55.
Clay, Henry, 147, 228.
Clayton-Bulwer Treaty, 55, 116.
Clement V, Pope, 21, 249, 251, 272, 273.
Clement VII, Pope, 23, 119, 226.
Clement XIV, Pope, 78, 124.
Cleveland, President, 170, 180, 269.
Clifford, Lord High Treasurer, 42.
Clifford, Mr. (O.P. Riots), 177.
Clovis, 222.
Cluseret, 60.
Cobbett, W., 207.
Cobden, Richard, 12, 101, 159.
Cobham, Lord, 42.
Cochin China, 99.
Cochrane, Earl of Mar, 27.
Cockerton, T. B., 57.
Cognac, 221.
Colbert, J. B., 141.
Coligny, Admiral, 221.
Colley, General, 157.
Collings, Jesse, 253.
Cologne, 114, 228.
Colombia, United States of, 186.
Colorado, 50.
Columbia, District of, 61.
Columbus, Ohio, 141.
Columbus, Christopher, 222.
Combes, M., 18, 33.
Comyn, Alexander, 209.
Condé, Louis, Prince de, 7, 82, 228.
Condé, Henri, Prince de, 184.
Condorcanqui, 213.
Conflans, Treaty of, 29.
Congo Free State, 63, 40, 127.
Conkling, Roscoe, 240.
Connaught, 34, 60, 257.
Connecticut, 34, 62, 101, 113, 153, 173, 177, 252.
Connemara, 121.
Conrad II, Emperor, 190.
Conrad III, Emperor, 112.
Constance, 144.
Constance, Council of, 123, 226.
Constance, Diet of, 259.
Constance, Peace of, 150.
Constantine, Grand Duke of Russia, 73.
Constantinople, 14, 226, 233.
Conway (American Cabal), 43.
Corbie, 280.
Cornwall, 96, 241.
Cornwallis, Lord, 28, 175, 198, 281.
Corsica, 130.
Corsini, Count, 218.
Cortes, Hernando, 175.
Corti, Count, 67.
Cossacks, 281.
Courtrai, Battle of, 240.
Courtray, 4.
Couthon, G., 172.
Covenanters, 144, 207, 224, 245, 261, 275, 277.
Coventry, 266.
Coventry, Sir James, 69.
Cowper-Temple, 69.
Cranborne, Lord, 145.
Craven, Lord, 47.
Crete, 70.
Crichtons of Frendraught, 41.
Crim Tartary, 67, 140.
Crimea, 140, 188, 197, 225.
Croatia, 235.
Croker, John Wilson, 63.
Cromwell, Oliver, 74, 94, 121, 125, 126, 130, 146, 152, 157, 179, 184, 194,
211, 213, 214, 219, 228, 230, 231, 260, 273.
Cromwell, Richard, 38, 206.
Crusades, 7, 222.
Cuba, 8, 206, 209.
Culloden, Battle of, 42, 98, 143.
Cumberland, Duke of, 42, 56, 98.
Cunningham Graham, 257.
Curran, J.P., 265.
Custer, General, 71.
Cuyuni (River), 268.
Cyprus, 71.
Czartoryski, Adam, 261.
Czechs, 201, 280.

D’Alembert, J. le R., 87.


D’Artois, Comte, 195.
D’Avila, Sancho, 239.
D’Enghien, Duc, 195.
D’Este, Marquis, 150.
D’Estrées, Maréchal, 56.
Dalai Lama, 250.
Dalhousie, Lord, 245, 247, 253.
Dalmatia, 45, 130, 181.
Dalrymple, Sir Hew, 54.
Damascus, 145.
Danes, 72, 82, 95, 142, 221, 275, 276.
Dangerfield, 162.
Danton, G. J., 143, 165, 169.
Dantzig, 114, 197.
Danube, 3, 32, 72, 122, 188.
Dardanelles, 188, 266.
Dardanelles, Treaty of, 134.
Darling, Sir Charles, 270.
Darnley, Lord, 48, 220.
Dashkoff, Princess, 49.
Daulat Rao Sindhia, 235.
David I of Scotland, 211.
Davis, Jefferson, 62.
Davitt, Michael, 142.
De l’Hôpital, Chancellor, 169, 182, 218.
De la Marck, William, 26.
De Lesseps, Comte, 186.
De Montfort, Count Simon, 6.
De Montford, Simon, Earl of Leicester, 24, 77, 136, 146.
De Thou, 54.
De Witte, Admiral, 38.
Deccan, 195.
Defoe, D., 145.
Delagoa Bay Railway, 81.
Delaware, 35, 76, 161, 176, 252.
Delaware (River), 95.
Demarcation, Bull of, 256.
Demetrius Ivanovitch of Russia, 75.
Denkera, 96.
Denmark, 33, 35, 38, 40, 72, 82, 85, 91, 114, 135, 137, 139, 151, 153, 208,
216, 217, 226, 239, 255, 265, 274.
Derby, 95.
Derby, Edward, Earl of, 75, 145, 220, 249, 278.
Dermot, King of Leinster, 243.
Derry, 264.
Derwentwater, Lord, 94.
Deshima, 8.
Desmond, Earl of, 162.
Desmoulins, Camille, 143.
Despard, Colonel, 76.
Despencers, The, 277.
Devonshire, William, 1st Duke of, 175.
Devonshire, Spencer, 8th Duke of, 39, 120.
Dhuleep Singh, 141, 205.
Diaz de Vivar, Rodrigo, 53.
Diderot, Denis, 87.
Dindigul, 230.
Dingaan, 76.
Dinizulu, 173.
Disraeli, Benjamin, Earl of Beaconsfield, 145, 249.
Dnieper (River), 67, 197, 281.
Dniester (River), 132.
Doab, 141.
Doctrinaires, 180.
Döllinger, Dr., 179.
Dominicans, 126.
Don (River), 67.
Donauwörth, Troubles of, 204.
Donegal, Marquis of, 242.
Dongan, Thomas, 79.
Donis, Statute de, 276.
Donnelly, Ignatius, 199.
Doria, Andrea, 91, 93.
Dorr, Thomas W., 79.
Dorset, Earl of, 175.
Dort, Synod of, 15, 108.
Dost Mahomed, 234.
Dozsa, George, 80, 140.
Douglas, Archibald, Earl of Angus, 27.
Douglas, Sir James, 79.
Douglasses, The, 56.
Dover, 54.
Dow Win Sheou, 186.
Down, County, 242.
Drake, Sir Francis, 127.
Drakensberg, 171.
Drapier’s Letters, 279.
Dreyfus, Captain, 80.
Druses, 145.
Drutsch (River), 197.
Du Breuil, Peter, 153.
Du Tremblay, François, 37, 86.
Dublin, 48, 195.
Duclair, 81.
Duguesclin, Bertrand, 82.
Dunbar, 30, 67.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookball.com

You might also like