0% found this document useful (0 votes)
21 views76 pages

JavaScript and Node FUNdamentals 1st Edition by Azat Mardan ISBN B00HDYHKN6 Instant Download

The document provides links to various JavaScript and Node.js-related ebooks available for download, including titles by authors such as Azat Mardan and Jon Duckett. It highlights the contents and key topics covered in the book 'JavaScript and Node FUNdamentals' by Azat Mardan, which focuses on essential JavaScript concepts and Node.js fundamentals. Additionally, it mentions the Lean Publishing process used for the book's publication.

Uploaded by

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

JavaScript and Node FUNdamentals 1st Edition by Azat Mardan ISBN B00HDYHKN6 Instant Download

The document provides links to various JavaScript and Node.js-related ebooks available for download, including titles by authors such as Azat Mardan and Jon Duckett. It highlights the contents and key topics covered in the book 'JavaScript and Node FUNdamentals' by Azat Mardan, which focuses on essential JavaScript concepts and Node.js fundamentals. Additionally, it mentions the Lean Publishing process used for the book's publication.

Uploaded by

longezadrap0
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/ 76

JavaScript and Node FUNdamentals 1st Edition by

Azat Mardan ISBN B00HDYHKN6 install download

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

Explore and download more ebooks or textbooks


at 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
Ancient Conceptions of Art

C losely allied to the thought that the painter creates beauty is the
ancient tradition that the artist is inspired to produce works of
art. This conviction had its origin very early in the history of art. In
the time of Praxiteles this belief was entertained by many; it was
thought, for instance, that in the production of the Aphrodite of
Knidos the sculptor was inspired by the goddess herself.
This conception of art doubtless grew out of the fact that the early
art of the Egyptians and Greeks was largely devoted to the
representation of deities and to the erection of temples which should
be their shrines. This association of art with the gods and their
temples doubtless contributed to the belief that the artist was
inspired or that he possessed a superior power or the gift of
inspiration.
Closely allied with this thought was the conception
Hegel
expressed by Hegel with reference to a distinction
between the external and material forms of art and
the spirit which he suggests permeates the work and of which it is a
manifestation. Hegel, although accepting the theory that “art has the
vocation of revealing the truth in the form of sensuous artistic
shape,” speaks of the union of the material with the spiritual in a
manner, which although quite true in abstract reasoning, contributes
to this impression. Discussing Architecture as a Fine Art, he wrote:
“The material of architecture is matter itself in its immediate
externality as a heavy mass subject to mechanical laws, and its
forms remain the forms of inorganic nature, but are merely arranged
and ordered in accordance with the abstract rules of the
understanding, the rules of symmetry. But in such material and in
such forms the ideal as concrete spirituality cannot be realized; the
reality which is represented in them remains, therefore, alien to the
spiritual idea, as something external which it has not penetrated or
with which it has but a remote and abstract relation.... Into this
temple now enters the God himself. The lightning-flash of
individuality strikes the inert mass, permeates it, and a form no
longer merely symmetrical, but infinite and spiritual, concentrates
and molds its adequate bodily shape.” No one today in the presence
of a superb relic of architecture asks whether or not it is the abiding
place of a spirit. It is accepted as expressing the spirit of beauty and
is enjoyed for this alone.
Hegel’s conception of a work of art, frequently expressed in his
philosophy, was that the content or idea is the important thing. This
conception conformed to early art because painting and sculpture
were employed primarily to express ideas.
With the development of the Landscape School of Art and the
enjoyment of art on the purely aesthetic side, modern thought has
materially changed. Gradually our appreciation of the beautiful for its
own sake has developed. The influence of this movement has
reacted upon all phases of art expression, and even those works
which express ideas in the sense of subject matter have come to be
judged upon the basis of aesthetic beauty, rather than with
reference to the idea or content as thus defined.
Therefore what Hegel says applies to the early conception of art
rather than to that of the present time.
Another conception of art suggests the union of the
Socrates
beautiful with the good. The philosophy of Socrates
teaches this. He regarded the beautiful as coincident
with the good, and both of them as resolvable into the useful. He
does not seem to have attached importance to the immediate
gratification which a beautiful object affords to perception and
contemplation, but rather to have emphasized its power of
furthering the more necessary ends of life.
These early theories and conceptions with reference to art may in
some degree account for the prevalence of an impression, even in
our own time, that the artist is inspired or that he creates his
masterpiece as the result of some supernatural power. It has always
seemed to the inexperienced that the creation of a work of art
implies an element of mystery or represents something inexplicable.
What is to the painter a natural process becomes mysterious.
Nothing existed on the blank canvas and behold, presently, there
appears a picture simulating life. Having no knowledge of the
methods employed, or of the years of patient labor required to
secure the technical ability to represent the actual truth and spirit of
natural objects, the result seems far removed from the ordinary.
Thence it is but a step to the point of view that the artist is one
“inspired.”
Although the conception of a work of art which places it above
nature is very old, I do not recall a definition made under this
impression which seems satisfactory. There is always apparent the
effort to compromise or bring together two distinct conceptions—the
one attributing to the work a quality superior to nature and the other
demanding that it be a truthful representation of nature. Defining a
work of art as something superior to nature, and at the same time
insisting that it represent nature faithfully is an inconsistency
eternally cropping out.
John Constable touched this subject with remarkable
John Constable
acumen and expressed his conviction with precision
when he said: “It appears to me that pictures have
been over-valued; held up by a blind admiration as ideal things, and
almost as standards by which nature is to be judged rather than the
reverse; and this false estimate has been sanctioned by the
extravagant epithets that have been applied to painters, as ‘the
divine,’ ‘the inspired,’ and so forth. Yet, in reality what are the most
sublime productions of the pencil but selections of some of the forms
of nature, and copies of a few of her evanescent effects; the result,
not of inspiration, but of long and patient study, under the direction
of much good sense.”
This, then, is my argument: First, that art is the expression of
supreme or predominant character and the representation of grace
and harmony as these qualities exist in nature; and, second, that the
truthful rendering of these qualities is the high mission of the painter
and sculptor.
Evidence of Painters and Sculptors

I f we will now turn to the evidence bearing upon this subject, we


will discover what I have already indicated, namely, that the able
artists who have expressed opinions touching the philosophy of their
art have done so in no uncertain terms, and that the opinions which
refer art to nature as the highest source seem convincing. We will
also discover that not only do the majority of able painters agree
upon what art really is, and express their opinions with clearness
and precision, but that many of the philosophers of recent and
ancient times define art in the same forceful way.
Let us first examine opinions expressed by painters and sculptors.
Michelangelo wrote: “In my judgment that is the
Michelangelo
excellent and divine painting which is most like and
best imitates any work of immortal God, whether a
human figure, or a wild and strange animal, or a simple and easy
fish, or a bird of the air, or any other creature.... To imitate perfectly
each of these things in its species seems to me to be nothing else
but to desire to imitate the work of immortal God. And yet that thing
will be the most noble and perfect in the works of painting which in
itself reproduced the thing which is most noble and of the greatest
delicacy and knowledge.” Michelangelo thus reduces the philosophy
of art to the simple problem of selection, and the faithful and
truthful representation of the dominant, the graceful, the
harmonious, and the beautiful in nature. His statement, which so
simply, even quaintly, expresses the opinion of a great master whose
works have commanded the homage of the world during nearly four
centuries, is worthy of the most careful consideration. It reveals his
reliance upon nature without confusion of thought or pretension of
any kind. There are here no intricate definitions of art or complex
theories concerning his method of creating his masterly
representations of the best he found in nature—“the thing which is
most noble!”
The universality of this profound truth and of its independence of
local conditions and circumstances is emphasized by the fact that
another great master of another race, one whose technical methods
and choice of subjects differed widely from those of Michelangelo,
expressed the same reliance upon nature. Albrecht
Albrecht Dürer
Dürer was a contemporary of Michelangelo, but he
worked under widely different conditions. It is the
great fundamental quality of truth so quaintly commended by
Michelangelo that distinguishes the works of Albrecht Dürer. Albrecht
Dürer wrote: “Life in Nature proves the truth of these things;
therefore consider her diligently, guide thyself by her, and swerve
not from Nature, thinking that thou canst find something better of
thyself, for thou wilt be deceived. For Art standeth firmly fixed in
Nature, and whoso can thence rend her forth, he only possesseth
her.”
We find in Leonardo da Vinci’s notebook reference to
Leonardo da
Vinci
this same principle. He recommends application to the
study of the works of nature and advises the student
to withdraw as far as possible from the companionship of others in
order that he may more earnestly and effectively do this. His sage
advice emphasizes the importance of study. “The eye, which is called
the window of the soul, is the chief means whereby the
understanding may most fully and abundantly appreciate the infinite
works of nature.... All visible things derive their existence from
nature, and from these same things is born painting.”
Another painter who has written his opinion upon this
William
Hogarth
subject is William Hogarth, who said: “Nature is
simple, plain, and true, in all her works, and those
who strictly adhere to her laws, and closely attend to her
appearances in their infinite varieties, are guarded against any
prejudiced bias from truth.”
Of the great painters who have touched upon the
Sir Joshua
philosophy of art in their writings, no one has written,
Reynolds
shall I say, more fluently than has Sir Joshua
Reynolds. He may even be said to have been eloquent. His lectures
prepared for the students of the Royal Academy have been famous
for a century and a half. They have not only inspired generations of
art students with a keener interest in art, but they are probably the
most helpful utterances upon the subject given to the world in his
time or since. It seems to me, however, that, as is often the case
where great facility of expression is practiced, Reynolds employs a
term which, without clear definition, confuses the mind. This is true
where he frequently uses the term “genius.” The term is associated
in popular belief with the power to create works of art. Although
using a term which is at least subject to this interpretation, Reynolds
definitely denies to the human mind this power, asserting that the
power to create is simply the power to imitate nature. Reynolds
wrote: “I am on the contrary persuaded that by imitation only,
variety, and even originality of invention, is produced. I will go
further; even genius, at least what generally is so called, is the child
of imitation.” He further says: “The study of nature is the beginning
and the end of theory. It is in nature only we can find that beauty
which is the great object of our search; it can be found nowhere
else; we can no more form any idea of beauty superior to nature
than we can form an idea of a sixth sense, or any other excellence
out of the limits of the human mind.” Reynolds again writes:
“Invention, strictly speaking, is little more than a new combination of
those images which have been previously gathered and deposited in
the memory: nothing can come of nothing: he who has laid up no
materials can produce no combinations.”
John Constable, a contemporary of Reynolds, and to
John Constable
whose judgment we have already referred, further
expressed his opinion upon this subject. A statement
of principle by him seems to be conviction crystallized. Constable,
although unaccustomed to writing, even unaccustomed to
discussion, because he was a man of quiet and simple life, seems to
have thought profoundly; and when the rare occasion to express his
opinion did come he condensed within a few words a great
fundamental principle with unerring precision. His definition of the
purpose and method of the artist cannot, I think, be excelled for
accuracy or fullness of meaning. He wrote: “In art, there are two
modes by which men aim at distinction; in the one, by a careful
application to what others have accomplished, the artist imitates
their works, or selects and combines their various beauties; in the
other, he seeks excellence at its primitive source, nature. In the first,
he forms a style upon the study of pictures, and produces either
imitative or eclectic art; in the second, by a close observation of
nature, he discovers qualities existing in her which have never been
portrayed before, and thus forms a style which is original. The
results of the one mode, as they repeat that with which the eye is
already familiar, are soon recognized and estimated, while the
advances of the artist in a new path must necessarily be slow, for
few are able to judge of that which deviates from the usual course,
or qualified to appreciate original studies.” There is here no mystery
or ambiguity. This is the statement of a profound truth by a great
painter who knew perfectly his reliance upon nature. It was
prompted by the conviction of a great mind which saw only the
underlying fact and abjured all trivialities and hair-splitting theories.
In his mental attitude and grasp, Constable was like Winslow Homer,
a man of few words, one given to much thought and to firm
convictions.
In one of his lectures at the Royal Institution of Great
Sir Thomas
Lawrence
Britain, Constable said: “It was said by Sir Thomas
Lawrence, that ‘we can never hope to compete with
nature in the beauty and delicacy of her separate forms or colours,
our only chance lies in selection and combination.’”
Gilbert Stuart expressed a like reliance upon nature
Gilbert Stuart
when he said: “You must copy nature, but if you leave
nature for an imaginary effect, you will lose all.
Nature cannot be excused, and as your object is to copy nature, it is
the height of folly to work at anything else to produce that copy.”
Corot was equally assured of the importance of this
Corot
principle to an artist. He said: “Truth is the first thing
in art, and the second, and the third.”
Let us take the opinion of another able painter, that of
Millet
Millet, who said: “Men of genius are, as it were,
endowed with a divining-rod. Some discover one
thing in nature, some another, according to their temperament....
The mission of men of genius is to reveal that portion of nature’s
riches which they have discovered, to those who would never have
suspected their existence. They interpret nature to those who cannot
understand her language.”
“I should like to do nothing which was not the result of an
impression received from the appearance of nature, either in
landscape or figures.”
“I should express the type very strongly, the type being, to my mind,
the most powerful truth.”
These opinions are at once simple and comprehensive. They express
the thoughts of men who have achieved great works. Indeed, I have
never heard the able master of art say otherwise than that he has
striven with all his power, sometimes in despair, to wrest from nature
the subtle beauties of form and colour possessed by her and
discovered by those who have the power to perceive and understand
these qualities. Nature is the supreme standard, attained to only in
part. We may accept nature as the source of all beauty and harmony
in art and rest assured that the stream has never risen above its
source.
The opinions here quoted do not differ materially from those
expressed by painters of our own time.
I recall that Whistler upon the occasion of one of my
Whistler
visits expressed an opinion upon this subject.
Whistler’s “White Girl,” “Girl at the Piano” and many
other works are such notable examples of truthful representation as
to give weight to his opinion. The absolute certainty with which the
several parts of these pictures exist in relation to each other cannot
be overstated.
In response to my inquiry regarding the most important quality in
the art of the painter, Whistler said: “Art is the science of the
beautiful. The parts of nature bear a certain relation to each other,
and this relation is as true as a mathematical fact. People sometimes
say my pictures are dark. That depends upon whether or not the
subject was dark; whether the conditions made it dark. If a dark or
low toned phase of nature is selected, then the picture must be
absolutely true to those conditions.”
“There it is, the subject. Certain relations exist between the value
notes, and these relations must be reproduced absolutely. Two and
two make four—that is a simple truth in mathematics as it is in
nature. Two and two make four—the trouble is that many painters
do not see that two and two make four. They do not see this fine
relationship which results in a simple truth. Not seeing, they try all
kinds of numbers.”
Turning from the easel in front of which we were standing, Whistler
lifted a book from the table with a quick, almost nervous action, and
as he opened it said with a quizzical expression, “It is all in here.”
The book was the “Gentle Art of Making Enemies.” Tuning quickly to
the paragraph he had in mind, he read, “Nature contains the
elements, in colour and form, of all pictures, as the keyboard
contains the notes of all music. But the artist is born to pick, and
choose, and group with science, these elements, that the result may
be beautiful.” He continued to read for a good part of an hour.
Whistler by Whistler was an inimitable and rare treat. The slightest
shade of meaning was expressed with great delicacy, by inflection
and gesture.
At the end of very many years of study and observation, Whistler’s
sensitive appreciation and power of selection were extraordinary.
The most subtle and harmonious qualities in nature made an
irresistible appeal to him. He has described this faculty as the power
to pick and choose. By the very choice of many of his subjects he
was enabled to eliminate all insignificant details and thereby to
render the harmonies of nature as they appeared to him. He
described his method or mental attitude with reference to nature
when he said: “As the light fades and the shadows deepen all petty
and exacting details vanish, everything trivial disappears, and I see
things as they are, in great strong masses.”
This represents Whistler in the presence of subdued and gentle
qualities in nature, but it was the same Whistler, without
modification or change in his attitude with respect to nature, who
rendered with such startling realism and absolute fidelity to truth in
his marvellous etchings the shipping, the city, and the river Thames.
Under the blazing light of noonday the masts and rigging of the
ships, the forms and details of the hulls, even the tile upon the roofs
of the city houses were distinctly seen. He recorded his impressions
manifestly without the slightest deviation from the simple truth of
form and value. No one who has studied Whistler’s set of the
Thames etchings will for an instant dispute this statement. The
quality of simple truth is so astonishingly present in every line and
form in these works that no argument is needed touching this point.
The Whistler who made these etchings, the Whistler who painted
the “White Girl” and the “Girl at the Piano,” must be reconciled with
the Whistler who painted the evening symphonies representing the
river, the “Portrait of Sarasate,” and other works of subdued and
gentle qualities. The simple truth is that Whistler was as faithful and
scientific in the one case as in the other, and that the result
depended upon his choice of subject, and the time, and effect
observed. I am told that in his later period he sought after and
discovered means of securing the more gentle aspects of nature;
that he toned and diffused the light in his studio scientifically by the
use of semi-transparent window curtains. However this may be, it is
undoubtedly true that he did rely upon the effect actually before him
and that he sought to represent the subdued effect in his studio or
the gentle light of evening so beautifully described by him in his “Ten
O’Clock.” It would be difficult to imagine a more beautiful pen picture
than this description by Whistler. It indicates his love for the gentle
and harmonious qualities in nature.
“When the evening mist clothes the riverside with poetry, as with a
veil, and the poor buildings lose themselves in the dim sky, and the
tall chimneys become campanili, and the warehouses palaces in the
night, and the whole city hangs in the heavens, and fairyland is
before us—then the wayfarer hastens home; the workingman and
the cultured one, the wise man and the one of pleasure, cease to
understand, as they have ceased to see, and Nature, who, for once,
has sung in tune, sings her exquisite song to the artist alone, her
son and her master—her son in that he loves her, her master in that
he knows her.”
This power to select and represent the beautiful
Abbott Thayer
qualities in nature, a power which is the result of
repeated efforts, has been defined by Abbott H.
Thayer with rare skill and poetic beauty. “It is as though a man were
shown a crystal, a perfect thing, gleaming below depths of water—
far down beyond reach. He would dive and dive again, driven by his
great desire to secure it, until finally, all dripping, he brought it up.
But that in the end he could bring it—a perfect thing—to us, was
possible solely because he had first seen it, gleaming there. Others
might dive and dive, might work and labor with endless patience and
endless pain, but unless they had first seen the crystal—unless they
had been given this divine gift of seeing—this vision—they would
come up empty-handed. The occasional so-called genius does not
make the crystal, but he alone sees it, where it lies gleaming below
depths of water, and by his effort brings it to us. The whole question
is how absolutely, how perfectly, the artist sees this vision.”
“After the artist has lived, for a certain period, in worship of some
particular specimen or type of the form of beauty dearest to him,
this crystal-like vision forms, clearer and clearer, at the bottom of his
mind, which is, so to speak, his sea of consciousness, until at last
the vision is plainly visible to him, and the all-strain and danger-
facing time has come for putting it into the form in which as one of
the world’s treasures it is to live on.”
When asked whether the artist has ever been granted a vision of any
beauty which is not based upon the beauty of nature, Thayer
exclaimed emphatically, “No, no, no! I don’t see the slightest
material for any such conception.”
And when the question was further put—granted that the artist has
the gift of seeing beauty in nature to which others are blind, is his
picture Art in proportion as he truthfully records the beauty of the
nature that he sees? Mr. Thayer answered, “Yes. Everything in art, in
poetry, music, sculpture, or painting, however fantastic it looks to
people who are not far enough on that road, is nothing but truth-
telling, true reporting of one or another of the great facts of nature
—of the universe.”
The ability to see, as Thayer suggests, is the very foundation of the
artist’s power. It is this power of seeing which enables him to
discover truth and beauty, and it is the skill of the trained master
which enables him to reproduce these for the delight and inspiration
of his fellows.
That men are endowed by inheritance with varying degrees of
mental power is a self-evident fact. No one will dispute this; it comes
within our common experience. Providence has been lavish in the
bestowal of extraordinary powers upon the few, but it remains
everlastingly true that even with these success depends upon effort.
Nothing is more fully established than this truism. The records of
successful men in all periods and in every avenue of life bear
testimony to this fact.
To the artist, seeing is the all important thing, and to him there is no
mystery either in the development of this power or in the result
obtained. To him it is simply a matter of logical evolution, the result
of the day’s work well done. He begins his career as a student by
laboriously copying nature. His first studies are, as a rule, hard and
unsympathetic. I have not discovered an exception to this rule. In
the beginning the art student does not even see colour in its fullness
and beauty. Gradually he acquires greater power of perception. He
discovers beautiful and harmonious colours in nature which were
unseen at first. He realizes the exquisite grace of line to be found on
every hand but unperceived before—the movement, charm, and
beauty of natural forms. New beauties are revealed from day to day;
new harmonies are seen and felt. Presently the inharmonious
becomes distasteful; the ugly, intolerable; the offensive, a distress.
He comes into the presence of nature with a new vision. Her
beauties are revealed to him. He feels a thrill in the love he bears for
the exceptional and profound beauty of an evening sky or a grey
day. He never talks about inspiration or soul, although he has
searched out the very soul of the landscape. He simply seeks with
every power at his command, as Constable, borrowing the thought
from Wordsworth, expressed it, “to give ‘to one brief moment caught
from fleeting time’ a lasting and sober existence, and to render
permanent many of those splendid but evanescent Exhibitions which
are ever occurring in the endless varieties of Nature.”
The sculptor, I think, in some such manner lies in wait for the grace
and charm of movement, the supreme expression of character and
of harmony, as an animal lies in wait for its prey. When one or all of
these qualities are seen he seizes his chisel and strives to fix what
he has discovered in permanent form.
The artist, looking back over twenty or thirty years of continuous
and earnest study, of repeated and laborious effort, and of failures
and successes, realizes that the power of perception and selection
which he now possesses is the result of these years of observation
and labor. He also realizes that he has never quite attained to the full
height of his ambition to represent truthfully the supreme qualities of
beauty which he has learned to discover in nature.
In the selection of subjects for his works and in the production of
arrangements or combinations representing either grace, beauty of
colour and form, or essential character, the painter or sculptor is
aided by two very powerful influences.
The first of these is his inherited or acquired taste. Step by step,
precept upon precept, first as a student in the art school, then as an
artist, this faculty known as taste is cultivated, increased, until with
rare discrimination and judgment he selects, “picks and chooses,” as
Whistler said, the things of beauty and harmony, being guided all the
while by the unwritten law of harmony of which we are all conscious.
To arrive at this consummation of the artist’s highest endeavors is
not an easy task.
His course may be, and often is, a very delightful and agreeable one,
but it is one of infinite effort and labor. Before the painter acquires
this knowledge or power which enables him to discriminate with
judgment and taste, selecting those forms and colours expressive of
harmony, grace and beauty, he must have served an apprenticeship
of many long years. The sculptor who would aspire to the exquisite
and discriminating taste of a Rodin, who observes with patience and
who seizes with marvellous skill upon the very essence of grace as it
is expressed by the human figure, must travel the same tedious
road. If the sculptor would read and know character as does a Saint-
Gaudens, he must travel many a weary mile over the path which
leads to perfection in art.
The second powerful influence helping the artist to acquire
knowledge is, as Constable suggested, art itself. The student while
pursuing the plodding course of training in the art school and later in
a wider field as an artist, is not only searching out in nature the
qualities of grace and harmony, but his eyes are constantly turned in
the direction of the accumulated records of art. He studies with
assiduous care and thought in the great works of all times, the
qualities, the harmonies, the character wrested from nature by the
able painters and sculptors of the past. Myriads have tried and failed
to know and master nature during the past few hundred years, and
only the few who have succeeded have left the record of their
success. All the weak productions have gone into oblivion. To these
really great works the painter and sculptor turn again and again,
patiently, persistently, unfalteringly, sometimes through hours of
silent study at other times by earnest effort to copy, but always with
a single purpose in mind—to know and master the secrets of the
masters. Little by little, always referring the master to nature for
confirmation or proof, the artist struggles upward to a more
consummate understanding of the works of nature, but he never
forsakes or belittles this supreme source of all his power and
knowledge.
I recall asking Winslow Homer if he did not think the
Winslow Homer
beauty existing in nature must be discovered and
reproduced by the painter. Quick as a flash he
answered: “Yes, but the rare thing is to find a painter who knows a
good thing when he sees it.”
On another occasion we were picking our way along the Maine
coast, over the shelving rocks he painted so often and with such
insight and power, when I suddenly said: “Homer, do you ever take
the liberty, in painting nature, of modifying the colour of any part?”
I recall his manner and expression perfectly. He stopped quickly and
exclaimed: “Never! Never! When I have selected the thing carefully I
paint it exactly as it appears.”
During our talk he emphasized, however, the importance of
selection. “You must not paint anything you see—you must wait and
wait patiently for a particular effect, and then when it comes, if you
have sense enough to know it when you do see it—well, that’s all
there is to that.”
At another time, referring contemptuously to the calm ocean under a
vacant sky, he said: “I take no interest in that.” There came,
however, one morning while I was at Prout’s Neck a misty and
threatening sky. Grey clouds bewitching in their silvery tones went
hurrying across the troubled sea. By noon it was blowing a gale and
the waves were lashing the coast, sending spray high into the air.
Once and again great clouds of mist drove across the deserted
rocks, and the music of old ocean rose to an ominous and
resounding tone. Presently Homer hurried into my room, clad from
head to foot in rubber, and carrying in his arms a storm coat and a
pair of sailor’s boots. “Come,” he said, “quickly! It is perfectly grand.”
For an hour we clambered over rocks, holding fast to the wiry shrubs
which grew from every crevice, while the spray dashed far overhead.
This placid, reserved, self-contained little man was in a fever of
excitement, and his delight in the beautiful and almost overpowering
expression of the ocean as it foamed and rioted was inspiring. To
him this was the supreme expression of beauty and power. The
moment he had patiently waited for had come.
Homer’s love for and appreciation of those rugged, elemental
qualities in nature resulted in the production of forceful works of
great beauty. In the selection of subjects he expressed his individual
taste.
I recall an opinion expressed by the late Henry W.
Henry W.
Ranger
Ranger to the effect that Tolstoi’s definition of art had
never been excelled. He referred to Tolstoi’s definition
of art as the power to pass on a sensation. Ranger maintained the
opinion that art is the expression of the individual’s feeling, that the
artist uses the facts of nature to express his own sensation and that
no great landscape was ever painted directly from nature. “The
technical difficulties,” he said, “and the rapidly changing effects
made it hard to paint out of doors. He could do better by depending
upon his memory.” It was his opinion that the deeper qualities were
secured in the studio; that nature only furnishes the hooks upon
which the painter hangs his work; that he in reality expresses his
own feeling, the poetry or sentiment which is in himself. Ranger here
describes a vague or not clearly defined quality which is referred to
as personal temperament. His opinion is in direct contradiction to the
almost universal testimony of painters and sculptors, and Ranger
himself in his practice failed to maintain it. Although he did not
complete his works in the presence of nature, he made many
sketches from nature and copied his larger canvases from these.
I think Ranger at the end of a long career had the power of
discovering beautiful qualities in nature and of seeing them
profoundly. I knew him well, and many times we discussed art and
artists. I found his knowledge broad and intimate. His view that a
painter simply passes on a sensation was repeated to me many
times. I think one may frankly agree with this opinion, but I do not
think a painter originates or creates a sensation. In the presence of
nature he simply receives it and then transmits it, the result being
dependent upon his natural or acquired power of perception, his
memory, and his technical ability.
Ranger’s paintings are characterized by an understanding of nature,
and this was the result of a lifetime of the most earnest, patient, and
persistent study. Probably no modern artist was more industrious,
for his studio was filled with studies in colour and many thousands of
pencil drawings. Indeed, so familiar was he with the colours and
characteristic forms of nature that he frequently reproduced these
with much delicacy, relying solely upon his memory and a few
accurate pencil notes. In discussing his method, I recall his remark
that he painted in the studio because he could get closer to nature
that way than by painting out of doors. Painters universally
understand the difficulties of painting in the open because of
conflicting lights. They also realize the more certain judgment of the
experienced eye when painting in a quiet or more subdued light; but
to do this requires great knowledge and a retentive memory.
As illustrating Ranger’s method of study and his reliance upon
memory, I recall an occasion when he studied long and patiently the
union or combination of two colour notes, the sky and water—for we
were sailing at the time. He remarked upon the beautiful harmony
expressed by these colours. He studied them intently, evidently with
the thought of reproducing them later. I also remember a painting
expressive of the charm and beauty of a moon-light night. It was
painted at his Noank home. I believe this picture was painted almost
wholly in his studio. I think it was the result of an infinite number of
impressions received as he studied, evening after evening, the ocean
and the sky. By this I mean that while Ranger in this painting was
passing on a sensation, he was only passing on the truth and beauty
of nature as realized by him night after night, and recorded in his
memory.
The point here raised is one of vital importance with reference to the
subject under consideration. It is that the painter does not express
anything he has not received. He pursues one of two methods: he
either secures beautiful qualities in the presence of nature or he
reproduces qualities stored in his memory.
John La Farge referred to these two methods, the one
John La Farge
by which the painter works directly from nature and
the other by which he depends upon his memory, and
his opinion bears directly upon the point raised. La Farge wrote: “He
[the painter] will then go again to nature, perhaps working directly
from it, perhaps only to his memory of sight, for remember, that in
what we call working from nature—we painters—we merely use a
shorter strain of memory than when we carry back to our studios the
vision that we wish to note. And more than that, the very way in
which we draw our lines, and mix our pigments, in the hurry of
instant record, in the certainty of successful handling, implies that
our mind is filled with innumerable memories of continuous trials.”
As La Farge points out, the difference between painting in the
presence of nature and painting from memory is only a different
span of memory. One painter pursues one way, another a different
method. The end sought is the same.
Giovanni Segantini’s method was to go to nature
Segantini
finally. He began his paintings in the studio, working
from studies, and finished them in the presence of
nature. I recall a delightful visit with this able Italian painter at his
home at Maloja, and also his interesting description of his method.
His art was little known at that time, some twenty years ago. His
works are now well known to art lovers throughout the world.
I had but recently seen his “Ploughing in the Engadine” at an
exhibition in the Bavarian capital. It impressed me as possessing a
very vital quality. The technical manner seemed at that time strange
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