100% found this document useful (5 votes)
22 views

JavaScript and Node FUNdamentals 1st Edition by Azat Mardan ISBN B00HDYHKN6instant download

The document provides links to various JavaScript and Node.js textbooks available for instant download in multiple formats. It includes titles such as 'JavaScript and Node FUNdamentals' by Azat Mardan and 'JavaScript Data Structures and Algorithms' by Sammie Bae, among others. Additionally, it outlines the contents of 'JavaScript and Node FUNdamentals,' covering essential concepts and techniques related to JavaScript and Node.js.

Uploaded by

viurrafojkar
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
100% found this document useful (5 votes)
22 views

JavaScript and Node FUNdamentals 1st Edition by Azat Mardan ISBN B00HDYHKN6instant download

The document provides links to various JavaScript and Node.js textbooks available for instant download in multiple formats. It includes titles such as 'JavaScript and Node FUNdamentals' by Azat Mardan and 'JavaScript Data Structures and Algorithms' by Sammie Bae, among others. Additionally, it outlines the contents of 'JavaScript and Node FUNdamentals,' covering essential concepts and techniques related to JavaScript and Node.js.

Uploaded by

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

Instantly Access and Download Textbook 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
'You are sure it is the girl of the island?' she asked.
'Quite sure,' answered Loswa. 'Madame Nadège asked me some
questions, you gave me a hint, Lemberg spoke of some new
protégée of Rosselin's. I inquired about the theatres, at the
Conservatoire; I imagined this hidden miracle was the future Desclée
of Bonaventure. I found out that she lived near Magny, and was
visited by Othmar; Magny is not the North Pole that they should
deem it unvisitable; I went there unseen myself, and a farm labourer
pointed out to me "la demoiselle:" she was at a distance from me,
walking by the river, but I recognised her at a glance. One might
have guessed it before. When she disappeared from the island it was
Othmar who knew where she went.'
'It is very droll!' said Blanchette, showing her white small teeth in a
grin of genuine appreciation. 'And do you suppose his wife knows?'
'Béthune knows, by his look the other day, and he will tell her: he
will be only too glad de lui donner une dent against Othmar.'
'I have told her something,' said Blanche de Laon; 'though I did not
know who it was I knew that there was an interest at Chevreuse; I
saw him walking in the fields there: but is the girl truly a genius?'
Loswa smiled.
'Who shall say? But the chère amie of a rich millionaire will always
find a public to swear that she is so. They already speak amongst
artists of her coming début, and it is easy to see the value which is
attached to the millions behind her. There is very little known about
her, but that fact is known of Othmar's interest in her, and no doubt
it will make it easy for her to appear on some great theatre.'
'They say she is first to appear at Othmar's own house.'
'That will be very clever, but very dangerous. Madame Nadège is not
a person with whom on peut plaisanter. I should doubt her
condescending to condonation of that kind.'
Blanchette laughed.
'He is very indulgent to her about Béthune. He may surely expect
the usual equivalent in return.'
Loswa was irritated.
'He knows well enough that Béthune is nothing to her; Béthune has
worshipped her for fifteen years. I admit that; but he has had his
pains for his payment; she lets him follow her about, but it is only
pour rire.'
Blanchette laughed and flicked her horse's throat with her little white
switch.
'You speak as if you were jealous! You always admired that cold
woman. To return to the coming Desclée. Paris already talks of her,
you say?'
'It is not my fault if it do not,' she thought.
'Vaguely, yes,' answered Loswa. 'It has an expectation of some new
talent which has what all talent in our generation requires: a prop of
gold behind it.'
'Have you discreetly whispered that it is one with the original of a
sketch of a fishing girl?'
Loswa smiled.
'I have caused it to be whispered, of course; we never say those
things ourselves.'
'Where does Othmar hide her at present, do you say?'
'At a farmhouse at Les Hameaux. He is not magnificent in his
maintenance of her; it is a very simple place, and she lives very
simply there.'
'That is just like a very rich man. Besides, Othmar always has a taste
for black bread and bare boards. You know at one time he actually
dreamed of breaking up the whole network of the Othmar power,
and stripping himself of everything, and living like St. Vincent de
Paul. That was before those children were born; their mother would
certainly never take the vow of poverty! Well, shall you and I ride
down to Magny some morning and see this prodigy of genius and
simplicity? You can recall yourself to her, and you can present me.
We will represent ourselves as inspired by what we have heard from
Rosselin.'
Loswa hesitated. Othmar was not a man whom he cared to cross.
Yet he had a desire to see again the face which he had sketched on
Bonaventure, and he had a vague idea that by going thither he
might in some way learn something which would enable him to pay
off that old score which had so long cherished against Othmar's
wife. He had had a restless and hopeless passion for her years
before; he had served and flattered her docilely because he held at
its just value the great power of her social influence; he had been of
use to her in a thousand ways at her château parties and in her Paris
entertainments; he had always been docile and devoted, and
ingenious to please, and submissive under offence, but all the same,
at the bottom of his heart there was a bitter rancour against her for
her blindness to his charms; for her criticism of his talents; for her
constant careless treatment of him as a mere décor de fête, as a
mere amateur; and if he could see her pride hurt or her indifference
penetrated, he felt that he would be happier and better satisfied. A
thousand slighting words which she had spoken out of caprice, and
forgotten as soon as they were uttered, had remained written on his
memory and unforgiven. He would not have quarrelled with her
openly for his life; he was too sensible of the pleasure of her
acquaintance, the charm of her presence, the value of her goodwill;
but if he could have helped unseen to put any thorns under the rose
leaves of her couch, he would have done so willingly; he would have
even chosen thorns which were poisoned.
'Yes, we will go and see her,' said Blanchette, as their horses paced
under the boughs. 'It is always amusing to be the first to inspect a
person the world is going to be asked to admire. On peut la dénigrer
si bien!'
'But,' suggested Loswa, with hesitation, 'if we dénigrer here, we
shall please Madame Nadège. Is that what you wish to do? I think if
we go at all we must, on the contrary, go to befriend, to admire, to
assist the new talent.'
Blanche de Laon gave him a little approving caress with her whip.
'You are a clever man, Loris,' she said with appreciation. 'We will go
to-morrow—no, the day after to-morrow,' she added. 'I will meet
you at St. Cyr; the horses shall be sent there by train; I often send
mine by train to places where I wish to ride; send yours also. We will
go early because it is a long way. The day after to-morrow I know
that Othmar will be at Ferrières; there is a great breakfast; he
cannot escape from it; there will be no fear of meeting him in
Chevreuse.'
'But are you sure what we shall accomplish when we reach there?'
'You will finish the sketch begun on the island, and I shall forestall
the dramatic criticism of Francisque Sarcey.'
'Othmar will not like it.'
'Othmar need not know it. My dear Loris, do you suppose that by
feeding her on buttermilk, and hiding her under a thatched roof, he
secures the primitive virtues in his idealised peasant? You may be
sure she already tells him nothing that she does not choose to tell.
On n'est pas femme pour rien!'
Loswa rode on in silence awhile, then he said with a smile:
'I have an idea, which, if we could realise it, might possibly prove
amusing. You will recollect that there are to be dramatic
representations at Amyôt next week when the Princes are there?'
Blanchette nodded assent.
'And Madame Nadège,' continued Loswa, 'is always very solicitous
for the success of her theatre; she spares nothing at any time on
that kind of entertainment; and the representations of next week are
to be really royal; all the greatest artists are engaged for them. I
have always a good deal to do with arranging these things for
Amyôt; and I know that it is most likely that the Reichenberg, who is
to play there, will not have recovered the chill which she caught
yesterday at La Marche. If she should not, shall we substitute
Damaris Bérarde? I need not appear in the matter; I can send the
director of Amyôt to Rosselin, and in any way we should have an
entertaining scene not included in the programme. If the new
wonder succeed, the Lady of Amyôt will not be pleased, and will
undoubtedly quarrel with her husband; if, on the contrary, the girl
should turn nervous, or hysterical, or passionate, and forget her rôle,
it will be diverting enough, and in any case will embarrass Othmar
himself. I think in either event we should have a droll ten minutes.'
Blanche de Laon showed her white teeth in an approving smile.
'You are always ingenious,' she said. 'But if Othmar be already
desirous of making the girl appear under his wife's patronage,
perhaps your scheme would only gratify him? What then?'
'He is only desirous of that because he thinks that his wife does not
know of Les Hameaux; but we will take care that she does know;
and I think she may be trusted to resent it. She does not care a
straw for him, but she cares immeasurably for her own dignity, her
own influence, her own empire.'
Blanchette nodded again.
'We will see what the new star is like, first,' she answered. 'It is not
a mere handsome nobody with a turn for the stage who will excite
her jealousy: she is too proud to be easily jealous.'
'The girl is magnificent,' said Loswa, as he thought. 'Jealousy is
always alive, even if love has been dead a century.'
CHAPTER XLVIII.
The day after the morrow they kept their word to each other. She
descended at the little station of St. Cyr, and found her horse and
groom and those of Loswa waiting for her. Loswa and she bade their
men stay at the station there, and rode themselves through the
country ways which lie between St. Cyr and Les Hameaux. That if
anyone chanced to see them their meeting would look like an
assignation, did not trouble the thoughts of the Princesse de Laon
for an instant; there were far too many much more weighty
imputations which she incurred daily to allow so trivial a possible
charge as this would be to have any terrors for her. She delighted in
the creation of scandal, in the risks of equivocal positions; and
challenged both the admiration of her husband and the long-
suffering of her world with the most daring and shameless of
provocations. She knew that to those who dare much, much is
forgiven; she knew that the world would never quarrel with her. It
feared her tongue too greatly.
It was scarcely noonday when they reached the quiet fields which
stretched around the Croix Blanche. There were the greenness and
freshness of very earliest spring in all the land; little birds were flying
and twittering, with thoughts of coming nests, to be hidden away
under orchard blossoms, and the sheep were cheerfully cropping the
short grass which covered the ruins of Port Royal. All these things
and the memories which went with them said nothing to Blanchette;
all she knew of spring was the dates of the various races, and all she
knew of history was that it gave you travesties for costume balls.
They left their horses in charge of a labouring servant, who was
sitting resting under one of the ash trees to eat his noonday bread,
and then, crossing the courtyard, pushed their way without
ceremony past the dairy-wench who tried to stop them and learn
their errand, and so, without either announcement or apology,
opened the door at the head of the wooden stair and found
themselves in the chamber of Damaris.
She was sitting reading at a table, the white dogs lay at her feet; a
great volume was open on the table before her, her head leaned on
her hand, which was hidden in the masses of her close-curling hair.
As she started at the unclosing of the door and rose to her feet, and
restrained the dogs with a gesture, the intruders upon her privacy
were both astonished to see the development which her beauty had
taken since the night two years before when she had stood,
bewildered and astray, like a young night-hawk brought into a
lighted house from the shadows of night, in the drawing-rooms of
St. Pharamond. She did not speak; she remained motionless, her
hand on the head of the male dog; she recognised Loswa instantly,
with a sense of pain and of regret that he had found her there; his
companion she was not conscious of ever having seen before.
'Here is Loris Loswa, whom you will remember, and I am Madame de
Laon,' said Blanchette, advancing towards her, with her abrupt
familiarity, her eyes roving all over the place and coming back to
fasten themselves with envy on the beautiful lines of the girl's throat
and bosom.
'We are come to see you,' she continued, 'because you will be a
celebrity very soon; Rosselin is going to bring you out at the Français
or the Odéon; you will have no trouble; everything is arranged;
Othmar's name is enough, and your story will please Paris when it is
in a romantic mood. It is romantic sometimes, despite the
naturalists. You are very handsome, my dear, very; you have an
antique type, and what blood and what health there are in you!—
enough to make a million of our anémiques! Why do you go on
living in this hole among pigeons and dogs? I should have thought
he would have given you an hotel in the Avenue Joséphine or the
Boulevard Hausmann before now!'
Damaris looked at her from under bent brows; she did not
understand, but she had a sense of offence in the way she was
addressed; this great lady seemed to her rudely familiar, brusquely
intimate; she did not like her tone, her face, her manner; and the
use of Othmar's name bewildered her. She was silent because she
had no idea at all what she should reply.
Loswa tried to propitiate her.
'I have not forgotten my day on the island,' he said to her, 'nor all
your goodness to me. Is it true that you are going to dazzle all Paris
in "Dona Sol" as you charmed us on that island with "Esther"? Why
does Rosselin delay to give the world so much pleasure, and why
does he keep you so hidden?'
Damaris heard with impatience and anger.
'I do not suppose I shall ever play Dona Sol,' she said abruptly; 'and
if I did, most likely Paris would laugh, and you first of all.'
'Paris does not laugh at handsome people,' said Blanche de Laon,
cutting short the flattering protestations of Loswa. 'Not, at least, till
it gets tired of their good looks. But it is quite true, is it not, that you
are being taught by Rosselin to rival Bernhardt?'
'I do not know as to rivalry,' said Damaris, with constraint and
displeasure. 'If I ever follow art I shall endeavour to be as true to it
and as far from imitation of others as I can. M. Rosselin is very kind
and patient with me.'
Blanchette smiled.
'You are very grateful. Be sure he finds as much interest in training
you as you can find in being trained! I should think you might
dispense with study—with such a face as yours, and such a friend as
Otho Othmar!'
Damaris coloured angrily.
She resented the intrusion of this stranger, whose impertinent and
familiar manners offended her, and seemed to her a personal
insolence. At Loswa she did not look. His presence was unwelcome
to her, and brought back the memories of Bonaventure so strongly
that it was with difficulty that she kept the tears from rising to her
eyes. How far away it seemed, that sunny noonday, when she had
made him welcome to her little balcony amongst the orange boughs
and the lemon leaves! And then how basely he had repaid her and
betrayed her, and brought his friends to laugh at her, as he had
brought this woman of fashion now!
Blanchette continued to gaze at her with unsparing examination, and
Loswa continued to make to her those pretty speeches of graceful
compliment of which he was a finished master. She grew angered
and stubborn under the eye of the one and deaf and contemptuous
to the flatteries of the other. Why had they come? When would they
depart? These were the only two questions in her thoughts.
She was troubled, too, by the abrupt mention of Othmar, and
uncertain what she ought to say, how she should reply. If only
Rosselin had been there! He would have known how to meet these
insolent gay people, who stared at her as though she were some
curious strange beast; he would have stood between her and their
persistent inquisitive examination. But the visit of Rosselin had been
paid on the previous day, and he would not return until the morrow.
The woman of the house was at the market of Versailles; she was
wholly alone; and she had lost the dauntless, careless courage with
which she had treated Loswa on the island, the courage born of
childish ignorance and of childish audacity. Life seemed now very
difficult and intricate to her, and her steps in it were shy and unsure.

'If I ever do go before the world I shall probably fail,' she said
wearily, in answer to their continued allusions to her coming career.
'Fail!' echoed Blanche de Laon, breaking in roughly on the graceful
protestations of Loswa. 'You will not fail, you shall not fail; it would
please her too much. Dame! how unlike you are to us! You look as if
you were made of some other stuff than we are made of; you look
as if you had come fresh out of the sea like the Greek goddess that
is in the Salon every year. Has she seen you again? You ought to let
her see you now.'
'Who?' said Damaris.
'Who?' said Blanchette, and muttered in her small white teeth 'Ah!
ça fait l'innocente, ça se pose!——'
Aloud she said to her companion, 'My dear Loswa, go and sketch the
nymphs of the farm; there are always nymphs on a farm, are there
not? I want to be alone a moment with Mademoiselle Bérarde. Allez-
vous-en!'
As he obeyed her unwillingly and with a look of eloquent regret,
Blanchette scanned with all the penetration of her pale keen eyes
the poetic and classic face of Damaris; she was a skilled appraiser of
female beauty, and there were a force, a colour, an ideality here
which she had never seen before, which were as unlike the beauties
of the women of her own world, washed with lait d'Iris and
shadowed with kolh, as a warm morning on southern fields, where
the sun shines on wine-hued wind flowers, is unlike a waxlit evening
in a conservatory.
'Paris has had nothing like her for ages,' she thought. 'But she is
stupid; she does not know her own power; she lives on at a farm; if
she waits for Othmar's leave she will never be seen by the world;
she does not understand; perhaps she mixes sentiment up with it;
she has the head of a Sappho; that type is always romantic.'
'Now he is gone,' she said aloud. 'Do not be afraid and do not pose.
Tell me truly, has Othmar's wife seen you since you left your island?'
'No.' Damaris coloured at the name.
'No? What a pity! Look you, my dear,' she continued, as she leaned
familiarly towards her and poured the sharp pale rays of her
penetrating eyes into the face of Damaris. 'I will befriend you
because you hate her. She had power once, but now I have more
than she had. Le jour est aux jeunes. I will use my power for you.
You shall become great if my world can make you so, because she
will suffer in seeing it. You must be great, I tell you; it is all very well
to filer le parfait amour with him under these trees if you like it—I
wonder you like it, it is such waste of time, and you should have had
your hotel and your major-domo, and your blood-horses by now,
and men never think much of a woman for whom they do little; it is
the woman they are ruined by whom they esteem;—but you must
be great, you must shine, you must set all Paris talking or you will
not hurt her in the least. I do not think she cares what affairs he
may have, all that is beneath her; she will only care if you can
oppose her de puissance à puissance, if the world admires you,
adores you, and flatters him and insults her every time that it praises
you. Do you understand? I do not think you understand. Are you
stupid or do you only pose? Do not feign with me. Why should you
feign with me? All that serves nothing. You only hurt yourself and
lose influence if you let him think you are content to be shut up like
this, adoring his image. You are one of the sentimentalists I see; you
must change all that. It is not of our time, it is not in our manners; it
is silly and provincial, and you may be sure does you no good with
him. Let Rosselin bring you out on any theatre he can, any is better
than none; but with Othmar behind him he will be able to buy all the
theatres in Paris. You are magnificent to look at; they say you have
talent, and you have a lover who is a Crœsus; it will be your own
fault if you are not the admiration of all Europe at a bound. Then
she will hate you, and she will be wounded to the soul, and she will
realise that her day is done; le jour est aux jeunes. And then I will
kiss you on both cheeks before all Paris if you like. Yes—I, even I—
Blanche de Vannes, Princesse de Laon!——'
Her voice had risen into a swift enthusiasm, a faint flush had come
on her pale features, she smiled with pleasure at the vision her
words conjured up; her cold narrow world-encrusted soul expanded
with the sweetness of a satisfied hatred and the honesty of a
genuine sentiment. Love she could not, but she could hate, and in
all the cruelty and the wickedness of her there was thus much of
candour and of feeling; she was true to the childish affections and
the promised revenge of a day long gone by. Even as she spoke she
was thinking of the poor little verses hidden with the dead roses in
the drawer at Amyôt; even as she spoke she was saying in her
heart, 'My pure angel, I do not forget; better people than I forget,
but I do not. She shall suffer what you suffered; she shall lose what
you lost; she shall feel that she is the laugh of the world; she shall
know that she is as powerless to hold the heart of her husband as
you were, and she shall see him chained in public to the triumphal
car of this child. And I shall be by the child's ear, and I shall tell her
all the secrets of power and all the vices that make men like sheep
to be driven, and I shall make her dupe him and deceive him, and
keep other lovers on his gold, and ruin him body and soul; and no
one will know I am there behind her but myself. I shall know, and
what a jest it will be!'
All these thoughts floated before her while her hands clasped the
ivory handled white whip and her eyes flashed their pale fires over
the face of Damaris.
To tempt, to corrupt, to revenge: they are a triad sweeter to those
who love them than are ever all the Graces and Persuasion, or
Charity and her gentle sisters.
Damaris still did not speak. The colour was hot in her face and her
eyebrows were drawn together; a look of intense suffering had
replaced the momentary stupor of bewilderment and surprise; she
breathed loudly and slowly with effort; the blue veins of her throat
were swollen. Little by little she had gathered up the sense of all
which had been said to her, and ravelled it out bit by bit, and
comprehended it.
The swift shrill voice of her temptress still went on in her ear.
'Perhaps you wonder what business it is of mine, why I mix myself
up in it, why I care what your lover does. Well, I care nothing at all
for him; he may have a harem as large as Versailles for aught I care,
but I hate her; I have always hated her. She is insolent, she is
arrogant, she has that power over men still which it irritates one to
see, and she killed my cousin. You may have heard of Othmar's first
wife and of her death. I was fond of my cousin; she was of a type so
rare—so rare!—one that one never sees now; she was only a child,
and she took her own life because Othmar loved this woman who is
his wife now; she thought she would make him happy in that way—
poor little sweet generous fool! So she died by the sea there, in that
country of yours. I was sorry then; I am angry still; I have always
said that I would live to see this other woman humiliated and
abandoned as she was humiliated and abandoned. And that is why I
will be your friend; openly, freely, I cannot be so, but I will do all I
can in my world to make you great, and I can do a great deal,
because great you must be. She will not care if he only make love to
you à la derobée under these ash trees. You are nothing now; you
are only a little peasant whom it has pleased him to set in a dovecot
—it does not matter to her even if she knows of it. But, if you
triumph in the sight of all Paris, then it will wound her. If you be a
second Desclée as she prophesied for you, so Loris says, then it will
make her bitterly mortified if she sees herself deserted for you.'
She paused to take breath after the rapid, voluble, unstudied
sentences which had followed each other so fast and in so
impressive a whisper off her lips.
Damaris made no word in reply. She listened as though she were
made of wood or stone; her full curved lips were pressed close
together, her eyes were sombre and had a dusky ominous gleam in
them, the only expression on her face was that of a vague, half-
stupid bewilderment which left her companion in the same doubt as
before, as to whether she were stupid or feigning.
'If she have no more intelligence than this,' Blanche de Laon
thought, impatiently, 'how can they think to make her famous for all
her beauty? To be sure, great artists are sometimes great imbeciles.'
She leaned still nearer till her eyes seemed to plunge themselves
into those of Damaris; she had drawn off her gloves, and her thin
small hands with their glittering rings were clasped on her riding
whip where it lay on the table in front of her; her voice rose swifter
and shriller as she resumed her argument.
'You do not understand your own forces,' she said, with the
impatience of a keen intelligence baffled by a slow one. 'You do not
see that now—now—now is the moment for you to do everything
you choose, to get everything you wish; if you let time go by,
Othmar will refuse you a piece of pinchbeck where now he would
give you a river of diamonds. If you waste your best years living in
obscurity to please him, he will recompense you by leaving you to
obscurity all the rest of your days. Men never appreciate sacrifice. If
he cannot do better for you than a room or two in a farmhouse,
what use is it to you that he is worth millions of millions as he is?
You are only a handsome child, only a handsome peasant; but if you
come into the world you will be a beautiful woman. You will lead
men any way you like, and he will love you all the more because he
will be afraid of his rivals.'
Suddenly she rose and stood erect.
'I know what you mean,' she answered, with the vibration of a great
passion in her voice 'At first I did not know. I think you cannot
understand. He saved me from the streets, as a man may a dog. He
has been as an angel to me. He does not care for me except in pity.
He loves her. I would give my body and my soul to him if he wished
for them. But he does not. He is not mine in any way, nor will he
ever be. You do not understand. If I could make him happy for one
hour I would burn in hell for all eternity with joy. But I have not the
power. I am nothing to him, nothing; no more than the world is to
me. You do not understand—go, go.'
Her voice lost its intensity of expression, and sank exhausted at the
close; the colour faded from her face; she leaned against the wall
with a sense of sudden weakness on her.
Blanche de Laon stared on her with hard unsympathetic sceptical
eyes; she laughed a little, coarsely, rudely.
'Dame! You have a mind to show me you can act! If you were on the
boards now you would bring down the house. You are no simpleton
I see. No doubt you know the rôle which pays you best. I spoke to
you in sincerity, and you answer me with a tissue of untruths. C'est
bien du midi ça!'
Damaris looked at her wearily: the pain in her was too great for
anger to have any place in it.
'You can believe what you like,' she said with effort. 'Go!'
Blanche de Laon, who had never in her life known any impulse of
submission or any sense of fear, was vaguely awed and touched into
involuntary acquiescence. Her swift, ready, insolent, and cruel
tongue was silent.
She was baffled and angered. She had spoken so frankly and so
cynically, because she had been certain that her words would fall on
a willing ear, and be received by a mind open and ready for them.
The possibility that Damaris might refuse to hearken to them had
never presented itself to her. She had made the usual mistake of an
ignoble mind. The possibility of a mind being noble had never
suggested itself to her.
She was sure that Othmar was the lover of this child, and that the
girl denied it to save him from all comment of the world, and all
jealousy of his wife.
Such a denial was stupid and exaggerated, and unwise, because the
force of all women lies in their power to make themselves feared,
and in their unblushing employment and proclamation of their
triumphs: still it was fine, even Blanche de Laon felt that. She did
not for a moment believe the answer given her, and she was bitterly
incensed at the rejection of all her overtures and the failure of all her
counsels; but she was moved despite herself to a certain unwilling
admiration of so much courage and of so much loyalty. It was a lie
she felt sure; but there were a grandeur and utter oblivion of self in
such a lie which impressed her by their utter unlikeness to herself.
She looked at the averted face of Damaris; then gathered up her
gloves and whip, and without any other words went from the
chamber.
'May I not go back to make my adieux?' asked Loswa, who waited
for her in the courtyard of the house.
'No,' she said sharply. 'What should you do there? You are no
student of the antique. That child is a daughter of the gods—a sister
of Phædra and of Medea—no contemporary of yours or mine. Let
her alone. She will not suit your canvas.'
'Will she play at Amyôt?'
'I do not think so.'
She mounted her horse and rode in silence through the fields and
lanes. Her tireless incessant voice for once was mute, and her face
was troubled and surprised. All the malice and the vileness which
had been in her thoughts, her hopes, her suggestions, had been
scared and confounded by the sense of a great unintelligible
passion, the nobility of which was incomprehensible to her, yet
affected her with a dim sense of its strength and its strangeness.
Once she laughed aloud and turned to Loswa.
'Desclée! Desclée never equalled Damaris Bérarde. What an
incomparable actress the future will enjoy whether we get her to
Amyôt or not!'
'You mean——' asked Loswa perplexed.
'My dear Loris! Almost she persuaded me that she loves Otho
Othmar for himself and not for his millions! Almost she persuaded
me too that he is not as yet her lover, though he may be when he
will! You will grant that she surpasses Desclée.'
CHAPTER XLIX.
When the echo of their horses' feet had ceased from the stones of
the courtyard, and the quiet air had no sound in it except the twitter
of the sparrows pecking among the food of the poultry in the yard
below, Damaris remained motionless, leaning against the wall of the
chamber. One by one all the words which had been spoken to her
returned on her memory, bringing with them a clearer meaning, a
fuller comprehension, a deeper disgust.
Little by little she understood all which Blanche de Laon had meant,
all which she had promised, all which she had supposed.
'They think that I live on his money, and that all I care for is that,'
she muttered with the sick sense of a loathsome imputation stealing
all the strength out of her nerves, and all the peace out of her life.
Othmar to her was as a deity. But the very exaltation and intensity
and ideality of the passion which moved her for him, rendered all the
coarse suggestions and conclusions of this woman of fashion most
intolerable to her, most cruel, and most degrading. Because she
would have followed him to any fate with joy and with devotion,
therefore was she most tortured, most outraged, by the supposition
that she could regard him as the means to riches and to fame.
Nothing on earth suffers so intensely as a loyal and lofty passion,
which sees itself classed with venal and avaricious lusts.
Perhaps even he himself might suspect her of some such vile hopes
as these!
She leaned against the wall, sick at heart in her utter solitude, her
lips white, her brow red with dusky colour, her breathing slow and
loud, her limbs cold. The white dogs watched her with wistful eyes
as they had once watched her little boat go away over the moonlit
sea. The morning crept onward, the pale sunbeams strayed across
the floor, amorous pigeons cooed in their little homes under the
eaves, distant voices of labourers, calling one to another, came
through the stillness; there was the sound of the strokes of an axe in
the copse.
She was conscious of nothing.
An hour and more passed uncounted by her, when the step of
Rosselin, still so firm and so light, mounted rapidly the wooden stairs
and his voice called gaily to her before he had reached the door of
her chamber.
'My child, where are you? I have great news for you. You had no
expectation of a visit from me to-day. I have great news for you, my
dear; it would not brook delays; the Fates have sent us the very
chance we wanted, there is always a dea Fortuna for genius, the
very stars fight in their courses for it——'
His gay and excited voice dropped suddenly, for his eyes caught
sight of her leaning against the wall of the room, where she had
stood during the last words spoken by Blanche de Laon. She turned
her head and looked at him, but without much recognition in the
look, her face was suffused with dark colour, she had an expression
in her eyes, stunned, disgusted, bewildered, and yet one of intense
anger.
'Who has been with you?' said Rosselin, abruptly. 'What have they
done to you?'
She did not reply.
Rosselin repeated his question impatiently.
'Have you not trust enough in me to speak? You look as if you had
seen ghosts. Good God! what has happened to you? Child, cannot
you answer me?'
'There is nothing to say,' she replied slowly. Not for the universe
could she have repeated what she had heard.
'Nothing to say! and you have lost faith in me in a night! I left you as
usual yesterday. You have been graver, shyer, stiller of late it is true,
but you have never been like this. I came to tell you of a great
chance. There may be no more gods for the vulgar, for aught I
know, but there is a divine providence still for genius! Mdlle.
Reichenberg is ill from cold; she was to play in the great theatricals
at Amyôt. Louis Loswa, who directs them as he always does, has
just sent to me to suggest that you should take her place in two
scenes from the "Misanthrope." He says that Othmar suggested it;
that he wishes his wife to see you there. You are letter perfect, I say,
in the part of Célimène, you have recited it so many times with me.
True you have never played on any stage, but I am not afraid of you
if you will be courageous, if you will speak as you speak when we
are alone. Child, you have genius. What is the use of having it if you
are dumb as the stocks and stones? Why do you look so? What has
happened to you since I left you?'
Damaris stared at him with dilated eyes.
'Amyôt!' she repeated.
'Yes, Amyôt,' said Rosselin angrily. 'The great country house of
Othmar. It is what I always most desired. It will be the finest début
you can have, and will, perhaps, stay evil tongues. You have said
that you would be dumb if you stood before her, but that
pusillanimity is wholly unworthy of you. What is she to you! A
woman who once predicted fame for you. Show her that she
predicted aright. You can succeed if you choose. Succeed then, to do
honour to me and justice to yourself——'
She did not reply.
'Cannot you trust me to know what is best for you?' said Rosselin,
still with anger and upbraiding. 'I have arranged everything. You will
go down to Beaugency to-night with me; rest one day, rehearse
twice or thrice there, and on the next play the part at Amyôt. It will
be perfectly easy. You are neither weak nor nervous, though you are
impressionable and take strange loves and hatreds. All is arranged; I
have your costumes ordered; the people who will act with you are all
my friends, and will aid you in every way. God in heaven! What can
you hesitate for? What can you want? At your age had I had such an
opportunity to take my place at a bound on the highest steps of
French art I should have gone mad with joy!'
Damaris was silent. Her face was in shadow and he could not see its
expression.
'Does he wish it, you say?' she asked in a low voice.
'Othmar? Yes, I believe so. He gave his permission for such a
presentation of you to his wife months ago; he will be present, and
he will certainly be glad to see your triumph. He knows well that
there is no other life possible for you. You cannot go back to the life
you left; you will not be content with the paths of obscurity; you
have touched the enchanted cup and you must go on to drink of it,
whether you will or no. There are a score of reasons, which it is not
necessary to detail, why it is much to be desired that you should be
seen first at Amyôt, beyond all other places. I think you should trust
me. I am not likely to mislead you after having passed so many
months in striving to develop the talents Nature has given you. Your
natural gifts are great; if you do not throw them away in a passion
of mistaken feelings or of childish despair you may live to reign in
France as a woman of genius can reign in no other country in the
world. You make me angry to see you so—Othmar's wife! What is
Othmar's wife to you that you should fret your soul for her? What
matter to you, child, are your own gifts, your own future, your own
victory? Love Art and follow it. It will be more faithful to you than
any lover that lives!'
She still did not reply.
He grew impatient and indignant with her. He had the conviction
which is so sincere in a great artist, that all passions, affections,
joys, woes and desires, loves and hatreds, were of no weight
whatever put in the scale with Art and with renown. He had given up
his whole existence to Art, and now that he was old his devotion to
it had remained in him whilst he had forgotten the force and the
despair of the affections and of the passions when they govern the
early years of life.
It seemed to him intolerable, incredible, that the mere weight and
sway of Othmar's memory should stand for a moment in the same
scale with her as her destiny in the world, her place in fame. As a
youth he himself had swept away all the flowers of feeling whenever
they had threatened to choke the growing laurel of his genius: why
could she not do the same? Was it because she was weak with the
weakness of women?
After love there is nothing so cruel as the tyrannies of art, and
Rosselin was art incarnated. Moreover he believed in the magnetism
and vivifying force of unexpected events and of sudden emotions.
They were a portion of those drastic and searching medicines with
which he thought an imperfectly developed genius needs treatment.
Once he had wished and wished sincerely that Damaris Bérarde
should remain in the cool and shady paths of private life; but he had
long ceased to wish it; he was impatient for the world to crown the
novitiate on which he had bestowed so much care and labour.
The thought of the fêtes at Amyôt captivated and stimulated his own
imagination. They seemed to him the occasion she most needed; a
very frame of Renaissance carvings, in which the portrait of
Célimène as portrayed by Damaris would show in its finest colours
and its finest lines. He dreaded for her the coarse and ugly trivialities
of a theatre with its throng of actors, its imperious direction, its hired
applause, its niggard criticisms; he feared that she would feel in it
like a hind caught in the toils, would rebel against it all and flee. But
at Amyôt it would be pure art which would claim her, refined praise
which would salute her, an atmosphere of delicacy, of culture, of
magnificence which would be about her. If such a scene and such a
stimulant would not arouse all the soul slumbering in her, then he
thought that he would be ready to confess: 'I mistake; she has no
genius; let her go and till the earth and reap its fruits; of the fruits of
art she shall have none.'
If she failed in such an air with such an opportunity, he thought that
he could be as cruel to her as Garcia was to Malibran when her
Desdemona was too timid and too tame.
'I want you to be seen at Amyôt,' he said once more, with irritation
at being forced to explain. 'Othmar's friendship for you is only an
injury unless you have his wife's countenance too. You can feel for
her what aversion you will, but you must be seen by the world in her
presence: then she can do you no harm. You are too ignorant and
too young to see the perils in your path, but I see them. I will save
you from them if you will be guided by me. If you are afraid to act, if
you are unwilling to be with the others, they must find some other
substitute for Reichenberg; there are many eager enough to replace
her; and you yourself shall only say some legend in verse, some
monologue, some simple poem, the "Révolte des Fleurs" or the
"Vase et l'Oiseau;" anything will do; you will be heard, you will be
seen, you will be known to have recited on the stage at Amyôt; it
will suffice.'
He did not add that he expected so much from the charm of her
voice and from the beauty of her face that the slightest cause which
should afford a reason for her being seen by the great world would,
in his anticipations, suffice to give her a place in its admiration, and
rank in its realms of Art.
'Come,' he said imperiously, 'there is little time to lose. We must
reach Beaugency to-morrow in the forenoon. All the rest are already
there. You must rehearse with them thrice at the least, for you have
none of the habits of the stage, though I think they will come to you
easily; I have taught you all there really is to know. Come: why do
you stand like that? Have you been moon-struck or sun-struck since
I saw you the day before yesterday? You have an opportunity given
you for which you should go on your knees with thanksgiving, and
you look as though you were doomed to your death! Oh, child, what
did I tell you the other day? If the hate of this woman be in your
soul, let it spur you on to great efforts, let it move you to high
endeavours, let it force her to own that you are dowered by nature
with what she has not. Hate is an ignoble thing, and I do not think it
the parent of noble actions, but if you cannot cast it out of your
breast, compel it to inspire you nobly. You have wished for the
world's applause, for the solace of art, for the joys of moving the
minds of multitudes: all these may become yours, if you choose. But
not if you consume your soul in vain passions.'
The face of Damaris grew duskily red. She knew his meaning.
'I cannot play at Amyôt,' she said slowly. 'Do not ask me, I cannot. I
should disgrace you. My tongue would cleave to my mouth. You
would curse me.'
'Great God!' cried Rosselin, furious and amazed. 'Because that one
woman has such terror for you?'
'Not that,' said Damaris.
She was mute some moments, the blue veins swelled in her throat,
a mist of tears gathered hastily in her eyes.
'I was starving and he fed me, I was friendless and he befriended
me. He shall not think that I look on his kindness as a mere stairway
to climb by to fame and the ways of the world. His wife and his
friends shall not say that I am made by his gold and sustained by his
influence; a mere thing of selfish, covetous, ambitious, mercenary
greed—like so many, many women—so they say. I did not
understand; now I have thought—and I do understand. You are
angry and I must seem thankless. But I will never go upon the stage
—never—never—never—because his wife and his world, and
perhaps his own thoughts, would always tell him that all I cared for
was the help he could give me, the reflection his wealth could cast
on me. I never saw it like that before, but now that I have seen it
so, once, I cannot go back into blindness.'
The tears rolled slowly from her eyes down the burning crimson of
her cheeks; her voice was lost in one great sob. Rosselin seized her
arm with a violent gesture.
'Who has been with you?' he said, fiercely. 'Who has dared to spit on
you the venom of the world's lying mouth?'
'I have thought it out all myself. Before I did not know,' she
answered briefly, and more than that he could not force from her.
She could not have told him the temptations and the suggestions
made by Blanche de Laon to save her life. All their shamefulness had
burnt into her very soul, as vitriol burns the flesh.
He stayed with her till night had fallen, and urged, implored,
commanded, persuaded, entreated her, with all the might of that
golden speech of which he was master. But it was all in vain. The
rocks of her own island were not more deeply rooted in their deep-
sea bed, than was her immovable purpose—never to try and force
her way into the world's publicity.
'Do you mean to say,' he asked, with incredulity and despair, 'that
you give up all idea of a dramatic career?'
She made a sign of assent.
'You cannot know what you do,' he cried in amazement and
indignation. 'You have gifts which are not given to many. Do you
mean to say that you will let all these lie and rust because of some
sentimental fancy which has rooted itself against all reason in your
mind? Your objections are absurd. They are the morbid, exaggerated
feelings of a child who has lived too much alone, and knows nothing
of the world except what books can tell. What has Othmar to do
with it either way? If it be a sacrifice made for him he will not care
for it. He has been kind to you; he is kind to half a million people;
but your future is nothing to him, except as he wishes you well,
assuredly he wishes you well, and the more success and happiness
you gain the less remorse will he feel that he and his broke up your
life in the south. Oh, my child, my dear, be wise while it is time. The
world is all before you, do not take a false step on its very threshold.
The gods are seldom benevolent; if we refuse the good that they
would do us, they leave us alone ever afterwards. They will never
return to ingrates.'
She was silent; but by the look upon her face he saw that he had
not altered her resolve.
'I seem to speak harshly no doubt,' he pursued, 'for you cannot see
in my heart, and for the first time since I have known you, you
refuse to believe in my judgment. I tell you that your idea is absurd,
that Othmar will never attribute to you the motives you fancy; he is
too wise and too generous, and no one could look at you, child, and
think of you an ignoble thing. You may be a great artist if you
choose. If you are not that, you will be of all creatures the most
wretched, for you will live against all the instincts of your nature,
against all the bend of your mind. What made you, when you read
your poets on your island, dream of a life wholly unknown to you, if
not the forces of genius which made you dissatisfied where you
were, and cried to you "Go." Fate has been kind to you: it has set
open the door; it has left you free. If you are thankless and refuse
what it offers, you will deserve to perish in misery.'
She was still quite silent.
'But what will become of you?' he cried in his amazement and his
grief. 'Child, you are so young, you cannot pass all your life living
down all the vital powers that are in you. Genius struggles like a
child in the womb to force its way out to light. You cannot go against
your nature. What will you do? What will you do? We have made you
for ever unfit for the existence to which you were born. If you do not
go and sit where Fame beckons you now, you will stay out in the
cold, friendless and homeless for life. Have I not told you so before?
There is nothing on earth so wretched as the genius which is born to
speak, yet fettered by circumstance, stands dumb.'
She heard, but she remained unmoved. She was but a child, and she
had a great hopeless passion shut in her heart, and the vileness of
the world had touched her like the saliva of an unclean beast, and
what could the fame which such a world could give seem ever worth
to her? All the youth and the warmth, and the awaking senses and
the wasted tenderness in her all yearned for gentler, simpler,
tenderer things, than the glittering corselet of fame and the noisy
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