1. Dart By Example 1st Edition Davy Mitchell pdf
download
https://ebookgate.com/product/dart-by-example-1st-edition-davy-
mitchell/
Get Instant Ebook Downloads – Browse at https://ebookgate.com
2. Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats
Flash Game Development by Example Feronato
https://ebookgate.com/product/flash-game-development-by-example-
feronato/
D3 js By Example 1st Edition Michael Heydt
https://ebookgate.com/product/d3-js-by-example-1st-edition-
michael-heydt/
Mathematica by example 5th edition Edition Abell
https://ebookgate.com/product/mathematica-by-example-5th-edition-
edition-abell/
Programming game AI by example 1st Edition Mat Buckland
https://ebookgate.com/product/programming-game-ai-by-example-1st-
edition-mat-buckland/
3. Mathematica by Example Fourth Edition Martha L. Abell
https://ebookgate.com/product/mathematica-by-example-fourth-
edition-martha-l-abell/
UNIX Shells by Example 4th Edition Ellie Quigley
https://ebookgate.com/product/unix-shells-by-example-4th-edition-
ellie-quigley/
Maple by Example 3rd Edition Martha L. Abell
https://ebookgate.com/product/maple-by-example-3rd-edition-
martha-l-abell/
Mathematica by Example 3rd ed Edition Martha L. Abell
https://ebookgate.com/product/mathematica-by-example-3rd-ed-
edition-martha-l-abell/
ASP NET by Example 6th Edition Steven A. Smith
https://ebookgate.com/product/asp-net-by-example-6th-edition-
steven-a-smith/
4. i
Dart By Example
Chapter 1: Starting the Text Editor3
Defining Dart3
History of Web scripting 4
The origins of Dart 5
Downloading the tools 6
Building your first application 10
Debugging a Dart application 20
Summary 23
Chapter 2: Advancing the Editor 25
The next steps for the text editor 25
Building the dialog package 27
The command-line app for source code statistics 40
Building web interfaces with Dart 47
Compiling to JavaScript 47
Summary 49
Chapter 3: Slideshow Presentations 51
Building a presentation application 51
Accessing private fields 56
Mixin' it up 56
Changing the colors 66
Adding a date 67
Timing the presentation 68
An overview of slides70
Handout notes 71
Summary 73
5. ii
Table of Contents
Chapter 4: Language, Motion, and Sound75
Going fullscreen 75
Adding metadata 79
Exploring the intl package 81
Working with dates 87
Animating slides 89
Playing sound in the browser 90
Summary 93
Chapter 5: A Blog Server 95
The Hello World server example 95
A blog server 97
Introducing Dart's server frameworks 106
Deployment 108
Load testing 112
Summary 113
Chapter 6: Blog Server Advanced 115
Logging 115
A blog editor 117
Caching 123
Watching the filesystem 124
XML feed generation125
The JSON feed generation 128
Static generation 131
Introducing the await and async keywords 131
Load testing revisited 134
Summary 135
Chapter 7: Live Data Collection 137
Kicking off the earthquake monitoring system 137
Introducing the data source 138
Exploring the GeoJSON format 138
Logging 140
Saving to the database 142
Introducing the pgAdmin GUI 144
Observing the Dart VM internals 153
Unit testing 154
Summary 158
Chapter 8: Live Data and a Web Service 159
Freeing the data 159
Creating the web service 164
6. iii
Table of Contents
Recapping the system so far170
Consuming application 171
Summary 178
Chapter 6: A Real-Time Visualization 179
Iteration overview 179
Application overview180
Notifying the user of an update 191
Plotting the user's location 192
Sorting the feature list 194
Documenting Dart code with dartdoc 196
Summary 199
Chapter 7: Reports and an API 201
Recapping the earthquake system 201
Advancing the REST API 203
Passing parameters to the API 204
Posting on the API 205
Summary 218
7. [ 3 ]
Starting the Text Editor
The rung of a ladder was never meant to rest upon, but only to hold a man's foot
long enough to enable him to put the other somewhat higher.
– Thomas Huxley
Defining Dart
Dart is a language and platform for modern web applications that can run both in the
web browser and on the server. The Dart language, tools, and API allow innovative,
productive, enlightened, and talented developers (that's you!) to write scalable web
applications that make the best of the modern Web.
With Dart, you can take a leap forward in web development and tooling. It is a clean,
modern, yet familiar language syntax that runs on a platform created by the world's
leading virtual machine experts.
Dart is run as an open source project with a defined process for enhancement
proposals. It has flexible libraries with common documentation packaging, unit
testing, and dependency resolution. The language became an ECMA standard in
July of 2014, and does not require any plugin for end users to run as it is compiled to
JavaScript.
If that is not enough, you can bring your existing HTML, CSS, JavaScript skills, and
even code along for the ride—Dart plays nicely with others!
8. Starting the Text Editor
[ 4 ]
History of Web scripting
The high sophistication of current web pages with animations, dynamic content,
fades, 3D effects, responsive designs, and clever navigation make it easy to forget
that the early web was mostly textual pages, dumb forms, and images that often
took a while to load. Then, along came JavaScript, in the form of a script interpreter
built into the browser, providing form data validation, news ticker moving displays,
animation, and games. For small projects, it succeeded in spicing up static websites
without requiring server-side CGI scripts.
Developers enjoyed the near instant edit and refresh cycle—changing a line of code
and hitting F5 (refresh) in the browser to see the result. JavaScript did not stay in the
browser and was soon found on the server side of web applications. It also became
a general purpose script for use outside the browser.
Fun fact: JavaScript was written in just ten days by Brendan Eich for the
Netscape browser and was originally called LiveScript. Dart has been
renamed too—originally, it was called Dash.
Considering the timescale it was written under, JavaScript is a great technical
achievement, but in 20 years it has not advanced very much, while web applications
have rapidly progressed. Web applications can contain thousands of lines of
JavaScript code. Outside of very simple pages, plain JavaScript is not enough
anymore, as evidenced by the number of tools and libraries that have sprung
up to assist development.
Many of these solutions are created to fix problems with JavaScript, ranging from
syntax and features to design and productivity. The language simply was not
designed for the type of web application that the modern web requires.
Recent advances in JavaScript engines have produced great leaps forward in
performance. The V8 engine that powers the Chrome browser and Node.js has
shown great improvement in making new kinds of applications viable. However,
the returns from JavaScript virtual machine optimizations have been diminishing
over time.
9. Chapter 1
[ 5 ]
The origins of Dart
Google has a lot of experience with both large web applications and writing web
browsers. They clearly have a strong self-interest in a better web platform (so
people search more) and an improved developer productivity (to stay ahead of
the competition). It is mentioned in Google presentations that a single code change
in their Gmail web application takes around 20 minutes to rebuild the site for the
developer to test it out.
This harks back to software build times decades ago. The project to fix this
problem was started, and Google wanted to share and work with the development
community as an open source project.
In 2011, at the GOTO conference, the Dart language and virtual machine was
unveiled to the world. Dart is designed to be a "batteries included" project—a
complete stack for writing, compiling, testing, documenting, and deploying web
applications.
Developed by the Chrome team, the project was founded by Lars Bak (the developer
of the Java HotSpot VM and JavaScript V8 Engine) and Kasper Lund (a V8
developer). The aim was both to improve the open web platform by opening up new
avenues for high performance client web applications and to improve developer
productivity.
The upstart language was designed to have a familiar 'curly brackets' syntax
similar to Java, C-sharp, and JavaScript, run on both the client and the server, and
to support the full range of modern web browsers by being able to compile to
regular JavaScript. New language features were only added to Dart if they could be
compiled satisfactorily to JavaScript.
10. Starting the Text Editor
[ 6 ]
Dart is often referred to as DartLang to avoid confusion with other "darts." Keep
this in mind when searching the Web for better results. The Dart language, like
JavaScript, is not only meant for the web browser; it is also available for server
applications and command-line applications. Future targets are mobile applications
on iOS and Android.
That is the history, the challenge, and the reaction of the biggest Internet company
in the world. So, what is Dart all about, then? The remainder of this chapter will
compare and contrast Dart and JavaScript and take you into building your first Dart
application so that you can see for yourself.
The rest of this book will take you on a tour of Dart through a set of interesting
projects, exploring all of Dart's habitats. We will be building useful applications
straight away and using increasingly powerful features.
Downloading the tools
Let's get started by installing a complete Dart development environment on your
computer. The home of Dart on the Internet is https://www.dartlang.org, which
contains the software, a wealth of documentation, and links to the online Dart
community.
I would strongly recommend signing up for the e-mail lists on this site to keep up
with Dart, and also the Dartisans Google+ community (http://g.co/dartisans).
The number of daily messages can be overwhelming at first, but there are some great
discussions and information sharing. It is also a great opportunity to interact with
Dart's creators.
It is recommended that you use the Stable channel. This version
updates roughly every few months via a built-in update tool.
There is also a Dev (development) channel that updates once or
twice a week with the very latest code from the Dart developers.
This is great for seeing new features early, but it is not as polished
or reliable as the Stable releases.
The downloads for all supported platforms (Linux, Mac, and Windows) are available
at https://www.dartlang.org/tools/download.html.The same location provides
information regarding building from source. Ensure that you download both the
SDK and Dartium (a specialist browser).
It is recommended that Mac users use the Homebrew system to manage the
installation and updates of Dart. Linux users can use a .deb if that format is
supported on their distribution, with ZIP archives being the alternative. Windows
versions are also supplied as ZIP archives.
11. Chapter 1
[ 7 ]
Windows users can download, install, and update the SDK and Dartium using the
Chocolatey installation system that is built on nuget and Powershell.
See http://chocolatey.org for more information.
The Dart packages are called dart-sdk and dartium.
Introducing the WebStorm IDE
WebStorm is the premiere development environment for Dart and was created by
JetBrains, which also publishes IntelliJ IDEA for Java and ReSharper for .Net.
WebStorm is a commercial package available at https://www.jetbrains.com/.
There are free licenses available for many and deep discounts for individuals. It
supports a range of languages and development platforms and Dart support is
provided via a plug-in. The plugin comes pre-installed with the IDE.
Download the installation file and follow the installation steps on screen:
12. Starting the Text Editor
[ 8 ]
WebStorm has a number of powerful features to help write our web applications:
• Auto-completion of code: properties and methods are listed as you type
• A static analyzer that scans as you type for possible problems
• Refactoring tools to help rename entities and extract methods
• Quick fixes to correct common errors easily
• Navigation via a code tree and finding usages of a function
• A code reformatter to keep the source code in a tidy format
• A powerful debugger
Alternative development environments
If you wish to use another IDE, there are plugins for IntelliJ IDEA and Eclipse. If you
prefer a simple text editor, there are plugins for Sublime, Emacs, and Vim. These are
all listed on the DartLang download page.
If you are an avid Visual Studio user, there is a community project underway to bring
Dart to that environment. DartVS can be downloaded from the Visual Studio Gallery.
It directly uses the DartAnalyzer from the SDK to report errors, warnings, and hints
inside the IDE. Support for intellisense and other features is underway, too.
The Atom Editor (https://atom.io/) is an alternative for those who prefer a
lightweight editor to a fully fledged development environment. The plugin, named
dartlang (https://atom.io/packages/dartlang) provides code-completion,
syntax highlighting, and access to some pub commands.
Help starting a project
To help create your new project, Dart has a tool called Stagehand that creates the
scaffolding from a high quality project template of your choice. It takes care of
common tasks such as folder structure, common libraries, and style sheets. It even
has its own website (http://stagehand.pub/).
In WebStorm, creating a new project presents you with a range of powerful options,
allowing you to set the locations of the Dart SDK and choose a project type for
sample content. The project type gives a range of skeleton applications and is
powered by the Stagehand application that is part of the SDK:
13. Chapter 1
[ 9 ]
Stagehand can also be run from the command line, with the first step being to install
it as a command:
pub global activate stagehand
This step installs the stagehand command from the stagehand package:
mkdir aproject
cd aproject
stagehand web-full
This will create a folder of sample content based on the web-full template.
For full details of the current templates, see
https://pub.dartlang.org/packages/stagehand.
14. Starting the Text Editor
[ 10 ]
Elsewhere in the SDK
The download also includes a set of command-line tools, which can be found under
the dart-sdk/bin path.
Tool Description
dart The standalone Dart Virtual Machine itself.
dart2js The tool that converts Dart into JavaScript so that it can run on any
modern browser.
Dartanalyzer Analyzes the Dart source code for errors and suggestions. This is
also used by development environments to provide feedback to
users.
Dartdocgen The documentation generator that works directly on Dart code.
Dartfmt The intelligent code formatter that makes your code tidy and
consistent.
pub The package management and application deployment tool.
You may wish to place these tools on the system PATH so that you
can call them from anywhere on the command line. This is optional as
WebStorm provides an easy interface to these tools; however, many
developers find it essential to a good workflow.
For more detailed information on the installation and configuration of
pub, see
https://www.dartlang.org/tools/pub/installing.html
Also in this location is a snapshots folder. Most of the tools are written in Dart itself;
when they are started up and initialized, a binary image of the initialized state can be
stored and used for future executions of the program.
The snapshots are generated using the Dart executable and are mostly intended for
frequently used command-line applications in deployment.
Building your first application
Starting simple is a good idea, but we also want to start with something useful that
can be expanded as we explore Dart.
In day-to-day software development, the text editor is where gigantic, world-
changing software often starts. We are going to build a multi-purpose web-based text
editor to use as a scratchpad for snippets of code, a to-do list, or stripping formatting
from copied text—immensely handy. For added realism, there will be an imaginary
customer along the way asking for new features.
15. Chapter 1
[ 11 ]
In the next chapter, we will build on this foundation for some flashier features and
graphical displays.
Downloading the example code
You can download the example code files for all Packt books you
have purchased from your account at http://www.packtpub.com.
If you purchased this book elsewhere, you can visit http://www.
packtpub.com/support and register to have the files e-mailed
directly to you.
Exploring the Web project structure
Go to the WebStorm welcome page and click on Open. Select the folder where you
extracted the sample code and choose the Chapter One folder, then the sub-folder
named Start.
A good first step when opening any Dart project is to ensure all dependencies are
present and up to date. To achieve this, select pubspec.yaml and right-click to show
the context menu. Click on the Pub: Get Dependencies item. The dependencies
will then be resolved and fetched if required.
File / Folder Description
packages A link to the packages (or libraries) that are being used by
this project. In this case, you will see the 'browser' package.
pubspec.lock Controls the specific version of the packages being used.
pubspec.yaml Meta information on our project (name, description, and so
on) and a list of packages being used.
web/styles/main.css The standard cascading style sheet file.
web/index.html The entry point for our web application.
main.dart Last but not least, a Dart file!
Unwrapping packages
From the preceding list, there is clearly a lot of structure and meta files for packages
in even a simple Dart project. The philosophy of the language is that libraries are
small, focused, and likely to be from different sources. They are also numerous and
update on different schedules, so version controls are important—dependencies are
hungry and must be fed.
16. Starting the Text Editor
[ 12 ]
You want your team members to be able to build and use your new Uber package
without dependency horrors! Likewise, you want the package you download off the
Internet to "just work" and reduce the effort required to write your application.
To look after all these packages, Dart has a tool called pub. This is a Swiss Army
knife tool that helps create, manage, and deploy your programs and packages. The
main home for Dart packages is the website https://pub.dartlang.org, where
numerous open source libraries are published.
If you are curious to know the origin of the name, "pub" is British slang
for a bar where people drink and play a game of darts.
A look at Pubspec
The pubspec.yaml has a curious file extension—YAML stands for Yet Another
Markup Language:.
name: 'TextEditor'
version: 0.0.1
description: A web based text editor.
environment:
sdk: '>=1.0.0 <2.0.0'
dependencies:
browser: any
From this, it is clear to see pubspec.yaml is Dart's equivalent of a project or solution
file. This holds the typical dependency details and meta-information. The Pubspec
file is fully detailed at https://www.dartlang.org/tools/pub/pubspec.html.
Although it is an extensive and powerful file, the main interaction you will probably
have with it is adding new dependencies.
Putting Dart into the web page
The file index.html is a regular web page. The rest of the file consists of a few
simple <div> elements and, as you might expect, a <textarea> tag:
<!DOCTYPE html>
<html>
<head>
<title>TextEditor</title>
<link rel="stylesheet" href="styles/main.css">
</head>
17. Chapter 1
[ 13 ]
<body>
<div id="output">
<div id="toolbar">
TextOnTheWeb
</div>
<textarea id="editor" cols="80" autofocus>
</textarea>
</div>
<script type="application/dart" src="main.dart"></script>
<script data-pub-inline src="packages/browser/dart.js"></script>
</body>
</html>
The foot of this page is where the initial Dart file is specified. The main.dart file is
loaded and the entry point, the first function to be run, is the main() function.
If you have programmed in C/C++, C#, or Java, main is a
familiar starting or entry point to an application. The concept is
identical in Dart.
Let's work through the main.dart file section one at a time and discover some Dart
features along the way.
Importing packages
Dart features a keyword, import, to use other packages and classes in our current
code context. In this case, both are prefixed with dart: to signify they are from the
SDK:
import 'dart:html';
import 'dart:convert' show JSON;
The keyword show modifies the second import to only make the JSON property
sections of the dart:convert package. This limits the classes in the current
namespace and therefore helps avoid name clashes and developer confusion.
18. Starting the Text Editor
[ 14 ]
Variable declarations
The TextArea is central to our editor and will be referenced multiple times;
therefore, we will use a specific type for it rather than var. In contrast, JavaScript
declares variables with the all-encompassing var keyword.
TextAreaElement theEditor;
This declares a new variable called theEditor and declares it as the type
TextAreaElement. The dart:HTML package contains classes to cover the DOM and
the TextArea input element.
Dart has an optional type system, so it would be possible to declare var theEditor
and the program would still run successfully. By being specific with the type,
we gain clarity in the source code and we provide more detailed information to
developer tools, such as code editors and documentation generators:
void main() {
theEditor = querySelector("#editor");
theEditor
..onKeyUp.listen(handleKeyPress)
..text = loadDocument();
}
In the main function, we use the querySelector method from dart:HTML to connect
to the TextArea control (with the ID attribute set to editor) on the web page. Once
we have a reference to the control, we want to a) connect an event handler so that we
know when the user has typed something, and b) load any existing text and display it.
Because we are using the same object, we can use the cascade operator (..), which
helps us write very readable and flowing code. The preceding can be written as:
theEditor.onKeyUp.listen(handleKeyPress);
theEditor.text = loadDocument();
The more properties we set, the more we have theEditor cluttering up the code.
With the cascade operator, we can replace the object name with (..), and call the
method/set a property as before. One important point with the cascade operator is
that only the final use has a semi-colon at the end of the line.
19. Chapter 1
[ 15 ]
Writing the event handler
The editor's TextArea KeyUp event has been connected to this short handler
function:
void handleKeyPress(KeyboardEvent event) {
saveDocument();
}
In contrast to JavaScript, there is no function keyword and we have void before the
function. The void keyword just means that this function does not return anything
when it is finished; it can be any class or type. As Dart is optionally typed, we could
omit void altogether.
Just a minute! Where are we going to be storing this text? After all, we have only
written a single HTML page and do not have a database connection or web service
to take care of the persistence. Fortunately, HTML5 has a simple key/value based
built-in storage feature called Local Storage that is well-supported by modern web
browsers. This operates in a similar fashion to a dictionary (sometimes called a map)
data structure.
In the next two functions, we will look at loading and saving from localStorage.
The HTML5 feature window.localStorage persistently stores data
with the client's browser. Unlike data stored in cookies, it does not expire
based on a date. The data is not lost when the browser window is closed
or the computer is switched off.
The amount of storage can vary per browser and according to user
settings, but the typical default value is 5 MB. This is plenty for our text
editor and many other types of applications.
Loading the saved text
The loadDocument function lets the world know it will be returning a String object:
String loadDocument() {
String readings = "";
String jsonString = window.localStorage["MyTextEditor"];
if (jsonString != null && jsonString.length > 0)
readings = JSON.decode(jsonString);
return readings;
}
20. Starting the Text Editor
[ 16 ]
We will store the text under the key MyTextEditor. The first time the user loads
up this page, there will be nothing in the local storage for our web page, so we will
check if it is empty or null before putting the value into the readings string variable.
JSON (JavaScript Object Notation) is an ECMA standard data format
that is based on a subset of JavaScript and is an alternative to XML.
For example:
{
"Name": "Davy Mitchell",
"LuckyNumber": 123,
"CarModel": null,
"Language": "English"
}
Saving the text
The format we are using to save the text is JSON—JavaScript Object Notation—
which is a common standard in web pages. The package dart:convert gives us
both the encode and decode functions:
void saveDocument() {
window.localStorage["MyTextEditor"] = JSON.encode(theEditor.value);
}
Finally, the saved document uses the local storage to keep our text safe. This time,
we are encoding the data into the JSON format.
Running in the browser
We are now finally ready to actually run the text editor in the target environment.
How is a browser going to execute a .dart file? Internet Explorer, Chrome, and
Firefox don't speak Dart.
21. Chapter 1
[ 17 ]
Dartium is a special build of the Chromium browser (the open source project behind
Google's Chrome browser) that contains the Dart virtual machine. Though not
recommended for day-to-day browsing, it is a full powerful modern browser to use
while developing Dart applications. As shown in the screenshot, it looks just like (a
very plain) Google Chrome.
If you are running on Ubuntu and receive a start up error mentioning
libudev.so.0, run the following command in a terminal to resolve it:
sudo ln -s /lib/x86_64-linux-gnu/libudev.so.1 /lib/
x86_64-linux-gnu/libudev.so.0
For more information, see https://github.com/dart-lang/sdk/
issues/12325
In WebStorm, right-click on the index.html file to bring up the context menu and
select the run index.html. This will start a local HTTP server for your application.
22. Starting the Text Editor
[ 18 ]
Once the application is running, type some text into the editor, and then close
the browser window. Then, run the program again and you should see your text
reappear once the page has loaded.
Editing and reloading
A new requirement has arrived from our customer. The title of the application,
"TextOnTheWeb", is not to their liking, so we will have to change it.
By this point, Dart should be looking a lot more familiar to you if you have written
JavaScript. The workflow is similar, too. Let's make a change to the executing code
so that we can see the edit and reload cycle in effect.
This will be achieved in the main function so, while keeping Dartium open, open the
main.dart file again in WebStorm, and locate the main function.
Add the following code snippet to start of the function:
DivElement apptitle = querySelector("#toolbar");
apptitle.text = "TextEditor";
Once you have made the change, save the file and switch back to Dartium. Refresh
the page and the new version of the main function will run and the new title will be
displayed.
Extending the interface
Our customer has asked for a button to clear the editing area. This is a reasonable
request and should not take too long to code with the productivity of Dart.
Firstly, we will open the index.html and add an input button to the page
underneath the TextArea control:
<input type="button" id="btnClearText" value="Clear" />
Open main.dart and in the main function, connect up an event handler:
ButtonInputElement btnClear = querySelector("#btnClearText");
btnClear.onClick.listen(clearEditor);
As with JavaScript, it is very easy to pass functions around as parameters. Move
the cursor over the text clearEditor and a lightbulb will appear. This offers the
keyboard shortcut of Alt and the Enter/Return key, or you can click on the lightbulb
icon.
23. Chapter 1
[ 19 ]
The implementation of the function is straightforward. Notice that we receive a
properly typed MouseEvent object as part of the event:
void clearEditor(MouseEvent event) {
theEditor.text = "";
saveDocument();
}
Refresh the page and click the button to clear the existing text. One happy customer
and we hardly broke a sweat!
The WebStorm Dart plugin has a number of quick fixes to aid your productivity and
help avoid coding errors in the first place. They also encourage good design and
keeping to Dart conventions.
Using the CSS editor
Keep the text editor running for the moment and switch back to WebStorm. Go to the
Project tab and in the TextEditor folder, open the web/styles/main.css file.
This is going to be your editor, too, so it is important that it is your favorite color—
perhaps you would like a thinner border or are not too fond of my chosen gray
palette.
Make some changes to the color classes and save the file.
The WebStorm CSS editor is powerful and shows previews of colors. If you switch
back to Dartium and click reload, the text editor should now reflect your chromatic
preferences.
24. Starting the Text Editor
[ 20 ]
Debugging a Dart application
A good debugger is a key part of a productive development system. Let's step
through our code so that we can look closely at what is going on.
To debug an application running in Dartium from WebStorm, we need to install a
small browser extension to act as a bridge between the two applications.
Follow the guide from JetBrains at the following web page:
https://www.jetbrains.com/webstorm/help/using-
jetbrains-chrome-extension.html
The main section to be concerned with is the "Installing the JetBrains Chrome
extension" section. This only has to be done once.
1. Click on the first line of the loadDocument function.
2. Next, open the Run menu and choose Toggle Line Breakpoint. A red circle
will appear to the right of the line:
3. Select index.html in the Project tab, then open the Run menu and choose
the Debug index.html menu.
4. Once Dartium opens, the loadDocument function should run and the
breakpoint should hit. The Debugger tab will appear in WebStorm.
5. The Debugger tab shows the call stack and values of current variables.
Under the Run menu and on the toolbar, the usual debug operations of Step
Into, Step Over, and return are available.
6. Before we take any steps, hover the pointer over the return statement line. A
tool-tip will appear to show that the string variable readings is currently
set to null.
25. Chapter 1
[ 21 ]
7. Choose Step Over and the execution will move onto the next line.
8. Move the pointer over the return statement again, and the readings variable
is shown to be an empty string object.
9. Step Over until the end of the function, and the return variable will be set to
the text retrieved from local storage.
10. To get the application running again, use the Resume Program menu option
from the Run menu, or to stop it from running, select the Terminate menu
option.
Working in harmony with JavaScript
The clear button on the editor is a bit dangerous as it may wipe out some vital notes.
We will provide the user with a simple Are you sure? prompt so that they have a
chance to back out of the operation.
You are probably thinking that we could use the Dart equivalent of window.confirm
to carry it out. We certainly could, but to demonstrate the ability to call JavaScript,
we will use the non-Dart version to display a prompt to the user.
Open main.dart and add the following import to the top of the file:
import 'dart:js';
In the Dart Analysis tab directly below the Dart code editor window, you will see a
warning that we have an unused import. This can be a useful tip once a project has
grown and code has been moved around into separate packages and classes. Import
lists can soon acquire clutter.
To call the JavaScript confirm dialog, we use the context object from dart:js in the
button click event handler. The context object is a reference to JavaScript's global
object:
void clearEditor(MouseEvent event) {
var result = context.callMethod('confirm',
['Are you sure you want to clear the text?']);
if (result == true) {
theEditor.text = "";
saveDocument();
}
}
26. Starting the Text Editor
[ 22 ]
The callMethod method can be used to call any JavaScript function available in
the scope of the page—not just built in objects. In this case, the first parameter is
the name of the function we wish to call and the second parameter is the list of
arguments for that method.
Commenting in the code
Our text editor foundation is looking complete at this point, but there is one
important element that is missing from the main.dart file—code comments.
Dart uses the following familiar commenting syntax:
Comment Syntax Description
// Your comment here. A single line comment
/**
Your comment here.
*/
A multiple line comment
/// Your comment here. A doc comment (the preferred method because it is
more compact)
In mentioning an identifier, place square brackets around the name. For example:
/// Returns double of [a] input.
int doubleANumber(int a){
//Assumes parameter valid.
return a * 2;
}
Take a short time to comment each function with the above style. Use a sentence
format and punctuation.
For more information on comment style and other coding conventions,
see the guidelines for Doc comments:
https://www.dartlang.org/articles/doc-comment-
guidelines/, and the Dart coding style guide: https://www.
dartlang.org/articles/style-guide/
27. Chapter 1
[ 23 ]
Summary
This chapter was focused on giving you the background story of Dart and getting to
work with the SDK to produce a useful application.
We have discovered how the JavaScript language and its development limits, leading
to the creation of the Dart open source project (centered around the https://www.
dartlang.org website), which is being developed as an ECMA standard and can be
used to write a range of application types from client to server and command line.
We have seen that Dart has a familiar syntax and powerful package management
tool called pub. WebStorm can be used to create, launch, and debug different types of
applications, and other IDEs and text editors have Dart language support, too.
We have worked through setting up a Dart development environment and wrote our
first application using HTML5 features. We saw how to navigate the structure of a
client-side web project and carry out debugging and development.
I am certain that the simple text editor that we have created is firing off ideas in your
mind of what to do next! In the next chapter, we will continue to look at client-side
Dart and add more features to the text editor, including some that will help us write
more, and better, Dart code.
29. [ 25 ]
Advancing the Editor
We made the buttons on the screen look so good you'll want to lick them.
– Steve Jobs
The technical possibilities of ever shinier web designs and more smoothly animated
layouts that modern web browsers are capable of makes the challenge of balancing
features and attractive presentation even harder for web application developers.
Functional and non-functional requirements, such as interface design and
performance, are often conflicting priorities. There is only a finite amount of time for
any project. A good strategy (sometimes!) is to focus on those that deliver both, and
there are many new possibilities within the expanding HTML standard.
Once the requirements are all settled and the application is constructed, deploying
the applications to the production environment smoothly is key. Testing on our
target systems, such as a range of web browsers, is vital, and that is where we are
heading with this chapter.
The next steps for the text editor
We have had some feedback on the text editor so far. Users like it and want more
buttons, and the top priority is a word-count feature that displays a dialog with the
current count. Customers have has indicated that they would like a powerful toolbar
above the editor pane for a range of features. They like the pop-up dialog style, but
say that the current one does not fit into the look of the application.
30. Advancing the Editor
[ 26 ]
Starting point
Open the code sample for Chapter 2, Advancing the Editor texteditor to see a slightly
modified version of the project from the first chapter. It is not ready to run out of the
box as we will add in a package to deal with the dialog creation.
The text editor functionality has been moved into a separate file—our main.dart
was getting rather cluttered. My personal preference is to keep it as minimal as
possible. The main.dart now imports a file, editor.dart, and the main function is
used to connect the interface to the Editor object, which now contains our functions
as methods of the TextEditor class.
Dart is an object-orientated language like C# and Java. In object-orientated
languages, objects can be defined as class declarations that typically
group together variables and functions to model an aspect of a system.
For more information on object-orientated programming, see https://
en.wikipedia.org/wiki/Object-oriented_programming.
For example, web browsers have the document and window classes that
can be accessed from JavaScript. These objects encapsulate aspects of the
web page structure and web browser window in functions and properties.
Even if you have not written classes with JavaScript, you will likely have
called functions and accessed properties on the built-in browser page
objects such as the document.getElementById() method and the
document.body property.
Dart classes
We have already encountered classes for HTML elements and event handlers. Dart
has an advanced single-inheritance class system. Classes are declared with the class
keyword. The editor.dart file has a class for the TextEditor (an abbreviated
version is shown below):
class TextEditor {
final TextAreaElement theEditor;
...
TextEditor(this.theEditor){
...
}
...
}
31. Chapter 2
[ 27 ]
The constructor is declared as the same name of the class, and we have a single
parameter. Dart constructors have a convenient feature for directly setting member
variables from the parameter declaration. This saves having a separate parameter
that is only ever used to assign to the member variable. Without using this shorthand
feature, the code would be as follows:
class TextEditor {
final TextAreaElement theEditor;
...
TextEditor(TextAreaElement theEditor){
this.theEditor = theEditor;
}
...
}
The field theEditor is declared as final; this means it can only be assigned a value
once in the lifetime of the application.
Structuring the project
Our new requirements are for two pop-up dialogs, and it sounds like we may
need more. We need to build an HTML interface library to cover these needs.
It is general-purpose, so can be used in many types of application. The rest of
the application can go in the TextEditor project.
Building the dialog package
The pub packaging system is a great resource for sharing finished packages online.
If we want to keep a package local and private, we can create it locally and use it in
much the same manner.
32. Advancing the Editor
[ 28 ]
The package project structure
The package project is structured in a similar manner to a web application project,
with a pubspec.yaml file being the main project file. Instead of a web folder, there
is a lib folder containing the simple_dialog.dart file that declares our library and
defines what is exposed outside the project:
This file contains any classes, functions, and references to other files—in this case, the
two files in the src folder. The first line in simple_dialog.dart with the keyword
library states the name and declares that this is a library. Note that it is not
surrounded by any quotation marks:
library simple_dialog;
import 'dart:html';
part 'src/dialog_base.dart';
part 'src/prefabs.dart';
The next section contains the imports required for all the files that are being exposed
by this package declaration in the part declarations. Open either of the files in the
src folder and you will see part of simple_dialog declared on the first line.
33. Chapter 2
[ 29 ]
Adding a local package reference
To reference the library, go to the TextEditor project's pubspec.yaml and open it in
the editor. Click on the source tab to see the plain yaml text file. There is currently no
graphical interface for the local reference, so it has to be added by hand:
dependencies:
browser: any
intl: any
simple_dialog:
path: ..simple_dialog
The path is relative to the root project directory, and, as this is a local filesystem
reference, the path separator must match the operating system, so we use
(backslash) for Windows and / (forward slash) for Linux and Mac.
The package is then referenced in editor.dart with a package prefix:
import 'dart:convert';
import 'dart:html';
import 'package:simple_dialog/simple_dialog.dart';
It operates in exactly the same way as a remotely installed package, with the added
advantage that it automatically refreshes if changes are made.
To avoid any problems with relative paths (which make many
people's heads hurt!), if possible, keep projects in the same directory so
that the relative path is always the same. Alternatively, full paths can
be used, although this may introduce problems when the code is on
different computers.
To verify that the path is right, look in the Project tab, expand the
Packages folder, and the package should be listed with its source.
Path dependencies are useful for local development, but will not work
when sharing projects with the wider world.
34. Advancing the Editor
[ 30 ]
Understanding the package scope
Dart operates under a library scoping system. All items in a package are available
throughout—there are no private or protected assets at this level. However, items
inside the library can be kept private to external code.
To achieve the equivalent of a private field, a field of a class can be marked private
if it has a preceding _ (underscore) character. Any project referencing the library can
only use the assets that the package has exposed.
For example, the TextEditor project can use the Dialog class that is public by
default and access the content field, but not the _visible field.
Defining the base dialog box
The dialog core is defined in the Dialog class in the dialog_base.dart file. This will
contain all the foundational functionality, such as the dialog frame and the OK and
CANCEL buttons. More specialized dialog boxes will inherit (extend) this class and
modify it for their purposes.
The package will contain common dialogs for the following:
• A simple alert dialog box
• An application about dialog box
• Confirmation dialog from the user
The alert dialog box
This is the simplest of all the dialogs. It will show a line of text and allow the user to
press the OK button so that the dialog box is dismissed:
void alert(String dlgTitle, String prompt, int width, int height) {
Dialog dlg = new Dialog(dlgTitle, prompt, width, height, true,
false);
dlg.show();
}
The dialog box does not return any value, and to make this as easy as possible for
the user, it is a single function call. This will be used to display the result of the
word-count feature.
35. Chapter 2
[ 31 ]
The About dialog box
The standard About box for an application contains a small amount of information
and a link to a website. This dialog is visually identical to the Alert box apart from
the addition of the hyperlink, and as this involves changing the dialog interface
elements, this will be implemented in a new class called AboutDialog:
This is created from the showAbout method of the TextEditor object:
void showAbout(MouseEvent event) {
AboutDialog textEditorAbout = new AboutDialog(AppTitle,
"TextEditor for the Web", "http://www.packtpub.com", "Homepage",
300, 200);
textEditorAbout.show();
}
The AboutDialog box inherits from the Dialog class and calls the constructor of the
Dialog class via super, which calls the constructor to form the foundation of the
object:
AboutDialog(String titleText, String bodyText, this.linkUrl, this.
linkText, int width, int height)
: super(titleText, bodyText, width, height, true, false){
36. Advancing the Editor
[ 32 ]
The elements for the box are created and added to the nodes member of the content
DivElement:
content..nodes.insert(0, new BRElement())
..nodes.insert(0, new BRElement())
..append(new BRElement())
..append(new BRElement())
..append(link)
..style.textAlign = "center";
The cascade operator keeps the code compact and focused on setting up the
different components of the dialog.
Using the confirmation dialog box
This dialog presents OK and CANCEL options, and calls a specified function if the
former option is clicked. This is used in the TextEditor class clearEditor method:
This is implemented by using the base Dialog class directly:
void confirm(String dlgTitle, String prompt, int w, int h, Function
action) {
Dialog dlg = new Dialog(dlgTitle, prompt, w, h);
dlg.show(action);
}
37. Chapter 2
[ 33 ]
The application can configure and display this dialog with a single line:
confirm(AppTitle, "Are you sure you want to clear the text?",
400, 120,
performClear);
A function is passed to the show method that is performed if the user presses the
OK button.
Counting words using a list
Word count is an important feature for students, technical writers, and competition
entrants. Our customers see this as a required feature, too.
In the event handler, we want to calculate the word count and throw the dialog on
screen for the user to see. This is a simple, short-running task, so the implementation
can exist directly in the event handler. As the output is simple, the alert dialog can
be used.
To determine the word count, Dart's List data structure and String classes can
be used. The first step is to remove any punctuation characters that may affect our
count. This is declared in custom_dialogs.dart as an unmodifiable const string
as it can be used for other word-based features:
const String punctuation = ",.-!"";
This is used in the showWordCount method of the TextEditor class.
Once the punctuation is removed, the string can be split into a List. Dart supports
generics, so the types of general data structure can be optionally specified, in this
case with <String>. The list of words is then filtered to clean out any non-word
entries remaining.
Once we have obtained the list of words, the final word count can be obtained by
using the length property of the list.
38. Advancing the Editor
[ 34 ]
The Word Frequency feature
Our customers would like a feature to help with writing quality. Overuse of
particular words can make a text repetitive and hard to read. To determine the
frequency of word usage, Dart's Map (sometimes called an associative array or
dictionary), data structure class, and String features can be used:
Depending on the number of different words used, the content areas may be allowed
to scroll, as the dialog cannot grow to the size of any data.
Generics are used again to specify the types for the key and value; in this case,
String for the key and int for the value:
Map<String, int> wordFreqCounts = {};
String out = "";
for (var character in punctuation.split(''))
text = text.replaceAll(character, " ");
text = text.toLowerCase();
39. Chapter 2
[ 35 ]
List<String> words = text.split(" ");
words
..removeWhere((word) => word == " ")
..removeWhere((word) => word.length == 0)
..forEach((word) {
if (wordFreqCounts.containsKey(word))
wordFreqCounts[word] = wordFreqCounts[word] + 1;
else wordFreqCounts[word] = 1;
});
wordFreqCounts
.forEach((k, v) => out += ("<tr><td>$k</td><td>$v</td></tr>"));
The processing of the text is similar to the word count, where a list of individual
words is built up. Once the list is filtered, forEach is used to iterate through the list
and count the occurrences of each word. The forEach method is used again to build
the output HTML, with the map's key and value parameters being passed to the
function.
Understanding the typing of Dart code
The types used so far for the Map and List help the design-time tools, such as the
Dart Analyzer and WebStorm, which allows us to write code by providing the code
completion and validating assignments.
When run in Dartium with the checked mode enabled (the default setting), types
are checked at runtime. In the final environment, most likely a web browser such as
Firefox or Internet Explorer, the typing information is not used and does not affect
the execution speed of the application.
Dart coding recommendations advise using types on all public-facing code. For
example, a class in a package can use private var variables, but methods require and
return typed data. This aids developers calling the code in understanding what is
required, and helps create better documentation.
40. Advancing the Editor
[ 36 ]
The file download feature
It can be very useful to have an actual file, so we will add a feature to let the user
download and save the contents of the editor to their local device. This is possible
with the custom data attributes feature in HTML5, which supports text as one of the
formats:
void downloadFileToClient(String filename, String text) {
AnchorElement tempLink = document.createElement('a');
tempLink
..attributes['href'] =
'data:text/plain;charset=utf-8,' + Uri.encodeComponent(text)
..attributes['download'] = filename
..click();
}
The process is straightforward: an anchor element is created and its target is set as
the encoded text data. The click event is then fired and the download proceeds as if it
were being downloaded from a web server.
The clock feature
Everyone has deadlines, so keeping an eye on the clock is important. The dart:async
package can help with this task by using a Timer class to trigger and update. This can
be carried out in one line in main.dart file of the TextEditor project:
new Timer.periodic(newTimer.periodic(new Duration(seconds: 1),
(timer) => querySelector("#clock").text =
(new DateFormat('HH:mm'))
.format(new DateTime.now())
);
The Timer constructor being called here (Timer.periodic) is a specially named
constructor; in this case, the periodic version is being used. There are numerous
variations of Timer objects. Named constructors allow the classes to have instances
easily created for a particular purpose as they do not require additional initialization
configuration before they are ready to use.
A periodic Timer will fire an event every duration period; in this case, one second.
The remainder of the line declares the function that is called. Dart has a shorthand
of => for functions that are a single line (which are named arrow functions), thus
avoiding the use of curly brackets. The querySelector function is used to get a
reference to the element on the web page with an ID of clock where the time will be
displayed.
41. Chapter 2
[ 37 ]
The current time is obtained and formatted into hours and minutes for display.
As the clock will run for the lifetime of the application and does not require any
interaction, no variable is required to store a reference to the object.
That was a busy line of code, and very powerful, but we are not finished examining
it yet! There has been no extra thread or process created. This is not a user-initiated
event. We will take a look at the what and when of the Dart task queue.
Executing Dart code
The internal architecture of the Dart VM has a single-threaded execution model that
is event-driven. In Dart terminology, this is called an isolate. The execution of a Dart
program places each event (for example, a function call) into one of two queues. The
VM then takes the next event and executes it.
The first queue is the main event queue, and the second is called the microtask
queue. This second queue is a higher priority, but is reserved, as the name implies,
for short, small tasks, such as creating a new event or setting a value:
This execution detail is hidden from the Dart developer for the most part. However,
it is important to understand that execution of Dart code is highly asynchronous. The
aim of this is to allow applications to continue to be responsive, while still performing
longer tasks such as calculations or accessing remote resources.
42. Advancing the Editor
[ 38 ]
The advantage of such architecture is the complete removal of the need for any
locking or synchronization during program execution. Other virtual machines
have to do this, and this greatly affects complexity and performance. For example,
Python's GIL (Global Interpreter Lock) has been debated for years, with many
alternatives suggested and experimentally implemented.
Multi-processing the VM
The design of the Dart VM allows multiple isolates to run simultaneously, which
can be running across different threads, CPU cores, and, in the web browser, web
workers. They do not share any resources such as memory, and their sole form of
communication is through a messaging system.
The class designer
The customers want a feature that will appeal to programmers. They would like a
way for the user to quickly sketch out ideas for a class, including details such as the
class name, fields, and methods.
Building a more complicated dialog
To handle this feature, a custom dialog will be required—GenClassDialog in
custom_dialogs.dart. This will inherit (extend) the Dialog class, and handle
the OK button click event handler itself. Unlike the other dialogs so far in the
application, this dialog must return a piece of data back to the text editor:
43. Chapter 2
[ 39 ]
The input controls are one TextInputElement and two TextAreaElements. The
placeholder property, available in modern web browsers, will be used to guide the
user on what to enter, and, as a bonus, they are convenient space savers, as we do
need to add extra elements to label the inputs:
String className = name.value;
String fieldsSrc = "";
String methodsSrc = "";
List<String> classFields = fields.value.split("n");
List<String> classMethods = methods.value.split("n");
classFields.forEach((field) => fieldsSrc += " var $field;n");
classMethods.forEach((method) => methodsSrc += " $method(){};n");
The text is retrieved from the controls and split by line into lists. The method
forEach is then used to traverse the list and build the source code.
Constructing the class
The template of a simple class in the GenClassDialog makeClass method has
placeholders for the generated source code of the fields and methods. This class code
template is declared as a multi-line string using three double-quote characters. Dart
supports string interpolation, which helps when putting values of variables into
strings:
result = """ /// The $className Class.
class $className {
$fieldsSrc
$className(){}
$methodsSrc
}
""";
Variables can be embedded in strings prefixed by a $ sign. These are then replaced
with the actual value of the variable when the string is used.
It is also possible to insert more complicated code, such as an objects property, "The
word is ${text.length} characters long". Note the use of curly brackets
around the expression being evaluated.
44. Advancing the Editor
[ 40 ]
Understanding the flow of events
The dialog for creating the class source code is created and handled by the
TextEditor class located in the editor.dart source file.
The sequence of events to display the dialog display is as follows:
1. The showClassGen event handler constructs the class and puts it on screen,
and the function completes, leaving the dialog visible to the user.
2. The user fills in the details and hits the OK button. This event triggers the
OK pressed method on the ClassGenDialog.
3. The text is extracted from the fields and the source code in the
ClassGenDialog makeClass method. Then, the resultHandler is called.
4. The resultHandler is the createClassCode method on the editor that sets
the TextAreaElement as the constructed source code.
Launching the application
To launch the application and try the text editor application for yourself, select
index.html in the Project tab, right-click to bring up the context menu, and click on
Run 'index.html'. This Run command is also available in the Run menu on the main
WebStorm menu bar.
The command-line app for source code
statistics
Our customers like the software development angle of the text editor and has asked
for some source code statistics such as SLOC (source lines of code) to be made
accessible. This feature may be of use outside the web page, such as in a continuous
integration environment, so we will construct our first command-line application.
We will create the project in WebStorm from scratch, but a completed version is also
supplied in the sample code in a folder called dart_stats.
45. Chapter 2
[ 41 ]
The command-line project structure
Open WebStorm, click on Create New Project, and select Console application from
the Project Templates list. Choose a location for your project and call it dart_stats.
The structure of the application has a bin folder with main.dart, which is the entry
point for the application. This is where the main function is located. The project
template contains several other items. For this tool, the focus will be on the main
function.
Dart is cross-platform, and the majority of filesystems used by the OS
platforms are case-sensitive. It is a highly-recommended convention
that all filenames are lowercase.
Add the source code file sourcescan.dart to the project. This contains the code for
scanning the text and tallying up line counts for classes, code, comments, imports,
and whitespace.
Processing the source code
The SourceCodeScanner class contains five integer fields to store the counts and a
single method to perform the analysis:
void scan: (List<String> lines) {
totalLines = lines.length;
lines.forEach((line) {
line = line.trim();
if (line.startsWith("class")) classes++;
else if (line.startsWith("import")) imports++;
else if (line.startsWith("//")) comments++;
else if (line.length == 0) whitespace++;
});
}
The list of lines is iterated over and the trim method is used to remove extra
whitespace from the lines to aid in matching the keywords that trigger and
increment the count. The startsWith method makes sure that the keyword is not
appearing mid-line in another context.
46. Advancing the Editor
[ 42 ]
File handling with the dart:io package
The application will be passed a single command-line argument, which is the full file
path to a Dart source code file. The command-line arguments can be read from the
parameter passed to the main function in main.dart.
One aspect that we will not have to deal with in the browser is loading the source
code from a text file. A package that is not available to Dart in the web browser, due
to security, is the IO package, which contains direct file handling functionality:
import 'sourcescan.dart';
import 'dart:io';
main(List<String> arguments) {
print(arguments[0]);
SourceCodeScanner codeScan = new SourceCodeScanner();
File myFile = new File(arguments[0]);
myFile.readAsLines().then((List<String> Lines) {
codeScan.scan(Lines);
print("${codeScan.totalLines}");
print("${codeScan.classes}");
print("${codeScan.comments}");
print("${codeScan.imports}");
print("${codeScan.whitespace}");
});
}
Once the text file is in a string, it can be processed in the same manner as in the web
text editor.
The program can be run from the command-line, as shown here on Linux:
$ dart bin/main.dart lib/dartstats.dart
lib/dartstats.dart
9
0
3
0
2
The program can examine its own source code!
47. Chapter 2
[ 43 ]
For more advanced handling of command-line arguments, see the very
powerful args package on pub at https://pub.dartlang.org/
packages/args.
readAsLines is an asynchronous function that immediately returns a Future
object. A function is passed into the future object's then method. The timing of the
execution of this function is unknown to the developer. The flow of the program
continues straight away. When the file read operation is run and has completed, the
function passed to the then method is executed when the Dart VM schedules it.
To see this in action, move the print statements outside of the then function,
as shown, and run the program again:
...
myFile.readAsLines().then((List<String> Lines) {
codeScan.scan(Lines);
});
print("${codeScan.totalLines}");
print("${codeScan.classes}");
print("${codeScan.comments}");
print("${codeScan.imports}");
print("${codeScan.whitespace}");
...
The probable output is all zeros as the code lines have not been scanned yet; this is
because the print functions are being called first.
It is also possible that the program will run just as before. The key point is that the
overall program execution keeps moving forward even when the code is asked
to perform a potentially long-running task, allowing other tasks to continue and
keeping the application responsive.
Debugging the command-line program
If you launch the program as it is in WebStorm by using Run, then it will open up
the debugger with a RangeError exception. This is because the program is assuming
that a command-line argument has been passed and the program has been run
without any input.
48. Advancing the Editor
[ 44 ]
In WebStorm, launches of programs into debugging can be configured, including
a feature to set command-line arguments. In this case, a full file path to a Dart
source file should be put in the Program arguments field. Note that, by default,
no command-line arguments are passed. It is also possible to set multiple launches
with different sets of command-line options:
To configure launches, select the Edit Configurations option from the Run menu.
Select main.dart from the list and enter the full file path of any Dart source code file,
such as one for the sample code for this book or from the Dart SDK.
Once the program is run, the results are printed to standard output using the print
function.
50. MURPHY’S LANE.
The Lower Road From Belleville to Bloomfield.
THE VAN RIPER FLOWER GARDEN.
One who knew Murphy’s lane in years gone by would naturally begin
with Charlie Van Riper’s flower garden. When we were young,
Charlie Van Riper lived in a frame house, the northern windows of
which overlooked Second river. The foreground of his view was a
neglected expanse through which meandered Murphy’s lane, and
also a second cart track which, as I recall it, merely shortened the
distance a few feet for those seeking “Murphytown” from the south.
This cart track, which is now Sylvan avenue, west of Summer
avenue, ran close by the old-fashioned flower garden, which Charlie
knew so well how to encourage to do its best, with its marigolds and
hollyhocks, and all the old friends set out in little odd-shaped beds
bordered with box. Charlie was as generous with his flowers as his
flowers were generous to him, and many a child who stopped to
gaze through the picket fence into that wonderland of gorgeous
color went on his way with a bunch of blossoms given to him by the
kind old soul.
That portion of the wild land which was not interfered with by the
traffic of Murphy’s lane offered inducements to the youngsters that I
am inclined to think they rather preferred to the Van Riper flowers,
and these were the hazel bushes which grew in abundance, the
ripened fruit of which was a great attraction.
BIRD’S WOODS.
51. “Bird’s Woods”, where “The slant yellow beam down the wood-aisle
doth seem like a lane into Heaven that leads from a dream”, should
have had a Sidney Lanier to immortalize its cool and delicious
depths. It was the picnic resort of many a Sunday school, but picnics
in the early days were simple affairs and did not call for changes
that seriously marred the beauty of the forest. The growth was
almost wholly pine and hemlock, and the balsam-laden air is
refreshing even yet to think of. A few swings and a sheltered
platform, where lunch was served, were the only attempts of man to
improve on the situation.
Second river with its babbling waters, the ruins of the old paint mill,
and the old dam, with its waterfall at the woods’ end, all combined
with the forest to lend enchantment and to a child furnished
possibilities for entertainment that were inexhaustible. How well I
remember the rush of small feet when the Sunday school children
reached the entrance to the woods, and how they spread out like a
fan through its coverts of mystery, each one intent on finding
something new or re-discovering some old friendly spot.
The Waterfall On Second River At Bird’s Woods.
Picture taken in 1903, before all the beauty of
the region had been destroyed.
52. Then the woods were full of sound, and I can still recall the
infectious laugh of Mr. Hine, who, as superintendent of the school
and chief promoter of jollity, urged the children on to a full
enjoyment of the occasion and his call to a stray robin that might at
the moment be voicing his approval of the place, “That’s right, old
fellow. Go it!” and then he would whistle to the bird in the tree in a
way that started him all over again. We will never see the like of
“Bird’s Woods” again.
NAMES OF FORMER DWELLERS ON MURPHY’S LANE.
As nearly as can now be recalled the line of houses on Murphy’s lane
was in the following order: Joseph Johns (later John Tyner), William
T. Wauters (later John Beardsley), John Murphy, Thomas Murphy,
James Murphy, Pat Murphy (the chief ingredients of “Murphytown”),
Bill “Whitehead” Bennett, N. J. Crane and Alfred Keen (on the corner
of the old Bloomfield road).
The Shields Guards was, before the Civil War, one of the institutions
of Murphy’s lane. The armory in which the guns and accoutrements,
loaned by the state, were stored, was situated some distance back
from Charlie Van Riper’s house, near the present Mt. Prospect
avenue. There were many Irishmen in the neighborhood and they
formed this company as a rival to the Continental Blues, which
numbered Belleville’s best among its members.
THE FIRST SUNDAY SCHOOL IN WOODSIDE.
Among Mr. Hine’s papers is a note to the effect that about 1822 a
Sunday school was carried on in Woodside (for how long he could
not ascertain) in the house of Mr. Joseph Johns, on Murphy’s lane.
This was an old stone house containing two rooms on the ground
floor, in one of which, about fifteen feet square, the Sunday school
53. was held. The house stood at the lower end of Murphy’s lane, very
near Second river. It was torn down during the winter of 1886. Mr.
Hine says:—
“Mr. Johns himself does not appear to have been exactly a saint, but
his wife, Peggy, was a woman of exceptionally fine character and a
devoted Christian. She died thirty-three years ago (this was written
by Mr. Hine in 1887), and those who were children during her later
years speak of their visits to her house as among the bright spots in
their child life. From the best information I can obtain, it was she
who gathered the children of the neighborhood together for Sunday
instruction, but I learn also of students from a seminary in
Bloomfield who came down there to teach, and who also established
a school in Franklin; they called it Pobishon. Whether that was an
Indian name of the region or merely a local title, I do not know, but
children from Belleville used to go to both schools.
“I have not been able to find out whether this ancient Woodside
school was divided in classes or taught in a body by the person
conducting it; but the exercises were simple and now and then a
tract would be given to a child, who in those early days, set great
store by the simple gift. I only know of two persons now living who
attended this school of sixty-five or more years ago: they are Mr.
Henry Stimis, who lives on the River road in Woodside and his sister
Eliza, who are well known to many of us. Mr. William Wauters, who
was a cousin of Mrs. Peggy Johns, has for many years, and until
recently, been a resident of Woodside, and is the father of two
former faithful workers in this school, the Misses Lizzie and Lucy
Wauters.”
In view of the fact that the first Sunday school in Newark was held in
1814 (Daily Advertiser, Oct. 27, ’83.) it speaks well for this country
region that one was held here only eight years later.
AN EASY WAY TO DIVIDE EVEN.
54. As nearly as I can gather from current remark, Mr. Joseph Johns was
a remarkably fine specimen of an awful example for a temperance
lecture—certainly that appears to be the impression he left behind
among the neighbors. A story still survives which indicates that Mr.
Johns was also somewhat original in his method of doing things.
It seems that he once had a sum of money in shape like a parcel of
bills of tempting thickness, and Mrs. Johns, believing that it would be
rather more safe in her possession than in his, tried to persuade him
to give it up, but, failing in this, she firmly insisted that half of the
amount belonged to her, and that he should at least divide. To this
proposition he agreed and, taking the package to the chopping
block, with one whack of an axe he cut it in two and handed one
bundle to his wife, saying “there’s your half”.
When he came to and realized the destruction he had wrought, he
was at great pains to paste the bills together again, and in this
condition they were put into circulation. For some years it was a
common thing to find some of “old Johns’s money” among change
received at the Belleville stores.
WAUTERS—WAUTERSE.
Beyond the Johns house stood the dwelling of William T. Wauters—
Wauterse, as his Dutch forefathers spelled it. The house is shown on
the map of 1849, but could not have been erected a great while
before that date.
POLLY VAN WINKLE AGAIN.
It seems that Polly Van Winkle, mentioned in connection with the
River road, was an inhabitant of Bloomfield and used Murphy’s lane
as one of her routes to and from the water side. She left the same
general memory here that she did elsewhere—a little, old woman,
55. bent nearly double with years and the weight of an enormous pack,
which was her constant companion.
MURPHYTOWN.
Not much has been learned of the Murphys, who appear to have
been brought over to work in the calico mills, and who settled so
thickly about midway of the lane that the spot became known as
“Murphytown”.
A Bit Of Murphy’s Lane. As it was
twenty years ago.
THE GYPSIES DO BUSINESS.
56. Some time before the Civil War a small band of gypsies, headed by
one James Trail, who had been in the habit of camping in the woods
on the south side of the lane, purchased some of the Murphy
property for the purpose of establishing a winter home. In those
days this was an out of the way spot and quite suitable for the
nomads.
During the warm months these gypsies wandered over the country
and at one time, while in Tennesee, they came upon a gullible
person named Ferris. Him they induced to bury a pot of gold, or at
least to allow them to bury it, at an auspicious moment when the
moon and stars favored increase, on the theory that if left a certain
length of time, long enough to allow them to get well out of the
country, it would multiply the dollars to a marvellous extent.
At the proper time Mr. Ferris dug up the pot and found it heavily
laden with—lead, and was sorely vexed. So far the plans of the
gypsies had worked as they wished, but what they had not counted
on was the persistence of their victim, who managed to trail them to
their winter lair. He then sought out ’Squire Sandford of Belleville,
and offered him a reward if he would capture the thieves and get
the money back, which the ’Squire did in short order.
All who knew ’Squire Sandford in his active days know how useless it
was to attempt to bluff him, and it is hardly necessary to state that
the gypsies promptly came to terms. This resulted in their giving up
the property on Murphy’s lane in order to avoid further trouble, and
the ’Squire received half of the land in lieu of a money reward.
THE BENNETT PROPERTY.
On the far edge of Murphytown stood the home of Bill “Whitehead”
Bennett. There were many Bennetts in the neighborhood, and it was
necessary to distinguish one “Bill” from another—this one appears to
have been a blond. The records show that the heirs of Joseph Crane
sold this property to John P. Durand, and he to Simon Sainsimon, he
57. to Daniel Crane, he to Aaron I. Crane, he to William Bennett, he to
Abram S. Hewitt, and he to Dr. Grenville M. Weeks. The following
items in regard to the ownership of the property I have from Dr.
Weeks.
PETER COOPER OWNS LAND HERE.
Early in the fifties Peter Cooper and Abram S. Hewitt bought a tract
comprising about 38 acres just beyond “Murphytown”, their intention
being to make a homestead of it, but they did not build. In 1860 Dr.
Grenville M. Weeks who was then a young man, living in Bloomfield,
discovered the place and, liking it both for its beauty and for what
he thought would be its future possibilities as the city grew, saw Mr.
Cooper and asked if he would sell. The latter said no, as he had
purchased intending to make his home here, but that since then he
and his son-in-law had been looking at a place near Greenwood
Lake, and they might sell a year hence, if they decided on the latter
place, as Hewitt thought the city would crowd them out of this spot.
DR. GRENVILLE M. WEEKS COMES ON THE SCENE.
In ’61 the Doctor again called on Mr. Cooper, who said, “Well, are
you as hungry after that place as ever?” and when the young man
said yes, the owner wanted to know how much he would pay down.
The Doctor who was only twenty-one, had a half interest in a small
drug store in Bloomfield, which had netted him $500, a very
considerable sum to him, and when he said he had $500, Peter
Cooper said, “$500! Young man, have you any idea what the relation
of $500 is to a $10,000 place?” The Doctor then thought he could
raise another $500, and the owner said, “I will make a contract and
give you a deed when you can save another $1,000 and give me a
mortgage for $8,000.” The Doctor had by this time entered the Navy,
58. and was thus enabled to secure the second thousand and the deal
was consummated.
In the course of time John I. Briggs bargained for the property,
agreeing to pay $15,000, and paid $100 down to bind the contract,
but he never paid interest on the mortgage, and the Doctor was
compelled to foreclose.
MR. JAS. YEREANCE A RESIDENT.
Next came Jeremiah Counsellor, a conductor on the M. & E. R. R.,
and a well-known character, and he asked the Doctor for an
opportunity to sell the property, stating that he would sell it inside of
a month, and that he wanted as his commission half of all he could
get over $50,000. This was just before the panic of ’73, when prices
were largely inflated and the Doctor was naturally pleased, as,
having been attached to the government service most of the time,
he had not appreciated the rise in land values. Shortly thereafter the
sale was made to Mr. James Yereance, a New York business man, for
$57,000, $25,000 being paid down. The interest was paid for some
years, but Mr. Yereance was finally unable to meet the payments,
and an amicable arrangement was made whereby part of the
property was deeded to the father of Mr. Yereance and the
remainder was bought in by the Doctor at Sheriff’s sale. The Doctor
speaks very highly of the honest manner in which Mr. Yereance
treated him all through these transactions.
DR. WEEKS AND THE MONITOR.
Dr. Grenville M. Weeks carries with him a useless right arm as a
memento of the Civil War. He was surgeon on the Monitor when she
sank, and tells such an interesting story—not only of this event, but
also of the conception and building of the Monitor, many points of
59. which he says are not commonly known—that a brief outline of his
story is embodied here:—
DR. THEODORE RUGGLES TIMBY.
Dr. Theodore Ruggles Timby, who died November 10, 1909, at the
age of 91 was, the Doctor believes, the real inventor of the Monitor.
In 1843, Dr. Timby gave thought to the immense unprotected
stretch of coast which this country presented to an enemy, and
recognized how impossible it would be to construct forts that would
cover its vast extent. It then occurred to him that if floating forts
could be constructed which could be taken to any point threatened,
the difficulty would be met. It is said that the old circular fort on
Governor’s Island first suggested a revolving turret to him.
By much thinking he gradually evolved the Monitor type, and fifteen
years before the Civil War broke out had perfected his plans and
submitted them to the various European governments, even sending
them to China, but they all scouted his idea, some one of them
remarking that every inventor had his soft spot, and evidently that of
Dr. Timby was the thought that he could float an iron ship.
Dr. Timby returned home and continued to work over his plans,
placing airtight compartments in bow and stern, and in such other
ways as he could devise meeting the objections that had been
raised.
When the Civil War came the inventor managed to get his plans
before Mr. Lincoln, who immediately became interested, and who
used frequently to visit his workshop in Washington to discuss them.
Finally Mr. Lincoln, who had some knowledge that the Merrimac was
being constructed and knew that something must be done to meet
the emergency, sent Dr. Timby with his plans to three of the
wealthiest and most prominent men in New York, with a request that
they submit the plans to the best engineer they could find.
60. These took the model and plans to John Ericsson, then regarded as
the best engineer in the country, and he, after shutting himself up
with them for ten days, submitted a report in which he stated his
belief in the feasibility of the plan, and that he could construct the
vessel in one hundred days. The order was immediately given to go
ahead, and at the end of the one hundred days the “Monitor” was
floating on the waters of New York harbor, to all appearances a
success.
An interesting addition to this story, which belongs here, comes from
Mrs. Lucy Cate Abercrombie of Forest Hill, and, while it is not part of
the Doctor’s narrative, it helps to complete the history.
When Ericsson announced that the Monitor could be built, he was
called to Washington for consultation and, among other questions,
was asked where the plates necessary to armor the proposed vessel
could be secured. He responded that he did not know, that such
plates were only made in Glasgow, and that it was impossible to
secure them from there, but that there was a man in Baltimore who
had invented machinery for rolling large plates, and perhaps he
could do the work.
MR. HORACE ABBOTT MAKES THE MONITOR A POSSIBILITY.
This was Mr. Horace Abbott, the grandfather of Mrs. Abercrombie,
who had perfected a machine for rolling heavy plates, by the
invention of the third roll, but he had put his last dollar into the
invention and the stagnation of business due to the war was writing
ruin for him in very large letters. Mr. Abbott was sent for and a
contract was signed, and in forty-eight hours thereafter the first
plate had been rolled, and this led to other government work. Thus
the Monitor not only saved the fortunes of the Union, but also those
of one of its inventive citizens.
Mr. Abbott’s invention revolutionized the methods employed in rolling
heavy plates; it has never been materially changed and is in use to-
61. day in every rolling mill in the country.
THE MONITOR GOES TO HAMPTON ROADS.
Word was sent to Lincoln that the Monitor was afloat and he,
knowing that the Merrimac was almost ready, ordered it to proceed
immediately to Hampton Roads. Ericsson, however, responded that
this was impossible, that the vessel was intended only for harbor
defense and would not last in a sea, as she was merely an iron deck
set on a scow with an overhang at each end of twenty-five feet, and
that the force of the waves under this overhang would lift the upper
works from the hull. He had not followed Dr. Timby’s plans as to the
hull, which would have saved the vessel in the storm off Hatteras
referred to below. The only excuse for the twenty-five foot overhang
that can be thought of now is that the short hull was sufficient to
float the structure and cost less than a longer hull. The President,
however, sent peremptory orders that the Monitor should go, and we
all know the result.
TALE OF THE MERRIMAC’S ENGINEER.
Some years after the close of the war Dr. Weeks met the engineer of
the Merrimac in Dakota, and as the conversation drifted to the days
that had been, the engineer told how the Southerners were highly
elated at the first success of the Merrimac, and felt that nothing
could stop them, and when they came out of the James river on the
morning that the Monitor arrived, the captain was annoyed to see
what he supposed was a raft lying between him and his intended
prey, the Minnesota, and not realizing what it was or that it could
offer resistance, ordered full speed ahead, expecting to ram and
destroy the obstruction.
62. “You can imagine our amazement”, said the engineer, “at the shock
of the impact, which threw us to the deck; it was like running on a
ledge of rock. The iron prow of the Merrimac, which was made for
ramming, was bent and useless, and had we not struck a slanting
blow the result to the Merrimac would have been serious.
“But what finally overwhelmed us were the enormous balls, eleven
inches in diameter, which came thundering at our railroaded sides
until they began to make breaches. Finally one of these ripped
through us from stem to stern, killing or wounding seven or more,
upsetting gun carriages and causing terrible devastation. Then it was
that we realized that destruction awaited us unless we could
escape.”
DR. WEEKS TRANSFERRED TO THE MONITOR.
One of the mistakes made by Ericsson was the placing of the
conning tower, from which the vessel is fought, aft of the turret
instead of on its top, as the plans called for. Because of this the
officer in charge was compelled to swing the bow forty-five degrees
out of her course in order to see ahead. This delayed the fight
greatly and also caused Lieut. John L. Worden, who fought the
Monitor, to be almost blinded by smoke and burned powder. This
fact led to the transferring of Dr. Grenville M. Weeks to the Monitor,
as it was necessary to relieve Lieutenant Worden and the Monitor’s
surgeon, Dr. Daniel C. Logue, went with him to the Brandywine,
while Doctor Weeks, who was surgeon on the Brandywine, was
ordered to replace Dr. Logue.
CAPTAIN BANKHEAD IN COMMAND.
Captain Bankhead succeeded Lieutenant Worden in command of the
Monitor and, as the Doctor says, there was a certain poetical justice
63. in the succession of Captain Bankhead to this command. It seems
that a board consisting of General Bankhead, the Captain’s father,
and Colonel Thornton of the army, and Joe Smith of the navy, had
been appointed some years before to determine whether this was a
great piece of folly, as the Europeans thought, or whether it was of
value, as the inventor believed. Thornton and Smith reported against
the invention, while General Bankhead made a minority report in its
favor. The Bankheads were Southern men, but loyal when the Civil
War came.
SINKING OF THE MONITOR.
The Monitor was ordered to Charleston, S. C., and on December 29,
1862, was taken in tow by the Rhode Island, a powerful side-wheel
steamer. A West India hurricane was raging up the Atlantic Coast,
and two days after the start that very thing happened to the Monitor
that was predicted by Ericsson, the tremendous lift of the seas under
the long overhang of twenty-five feet caused the deck to break away
gradually from the hull, and soon the cabin was awash and the
heavy dining table was crashing into the stateroom doors and cabin
sides as the rolling of the clumsy little vessel rushed the water from
side to side.
At this point the Doctor went below for something and found an
engineer so sick in his stateroom that he did not realize their
perilous position, and when the man refused to move the Doctor
attempted to force him out, but now a wave swept over the deck
and the Doctor, supposing the Monitor was going down, sprang for
the companionway and had to fight his way up through a solid wall
of water.
Once outside he sought the top of the turret with the Captain; in the
meantime rockets had been set off to notify the Rhode Island that
her tow was sinking and the latter had cut her loose. By this time
the fires were nearly out and the Monitor was so waterlogged that
64. she did not rise to the seas, but dived into them, while her officers
and men could with difficulty hang on, shutting eyes and mouth until
the flood had swept astern.
The Rhode Island immediately proceeded to lower a boat on its port
quarter, but while this was being done one of the most desperate
situations of this desperate night occurred. In some way an end of
the immense tow rope which had been trailing astern became
entangled in one of the paddle wheels and stopped the machinery.
Thus she lay helpless for the time being. In the meantime the
Monitor, which was still slowly running under her own power, her
fires as yet not having been drowned out, was bearing down on the
Rhode Island. In the darkness the proximity of the two boats was
not discovered until the Monitor was on the point of ramming. Just
at this critical moment the paddle wheel was cleared and the Rhode
Island began slowly to forge ahead, and consequently the blow was
not severe enough to cause serious damage, but it was a heart-
rending moment to those on both of the vessels, who felt that they
were very close to eternity.
The collision smashed the boat which was being lowered but another
quickly took its place and, recognizing how easily it could be stove,
this was well guarded with rope fenders.
It was midnight and very dark, the two vessels had drifted apart
again, but finally the small boat was discovered close in on their
starboard quarter. It did not dare come alongside, however, for fear
of being smashed, and the men were compelled to jump.
The Doctor was one of the last to leave the Monitor, and by this time
the small boat had drifted so far off that he fell short into the icy
water, but those on board caught him by the hair and collar and he
was dragged to safety. The Doctor will never forget seeing one of
the engineers, who had been the life of the party and who was loved
by all, miss the boat by five feet as he jumped, and go down in the
darkness never to be seen again.
65. There were sixteen in the small boat, but it was staunch, and they
felt comparatively safe. The waves were tremendous; at one
moment the boat was riding the crest of a mountain, the next it was
engulfed in the depths. While thus momentarily between two great
seas they dimly saw the bow of a second boat from the Rhode
Island hanging above them, which the next moment would come
down athwartships and grind them to pulp. A shout of warning
enabled each helmsman to throw his tiller over and sheer off to
some extent, but what saved the situation from becoming a
catastrophe to all was the Doctor’s quick wit. He tells the story very
modestly himself. Springing up and bracing his feet he grasped the
bow of the oncoming boat as firmly as possible and pushed it to one
side and this, with the prompt action of the helmsman, just
prevented the impending collision, but, as the one boat came down
on the other, the Doctor’s arm was gripped between them and he
was pulled down to the water, his arm was dragged from its socket
and hung attached to his body by a few stretched muscles. The
intense pain caused him to faint, and had it not been that the cold
water revived him as his head went under he would have been
pulled overboard.
When the boat reached the Rhode Island they found a spar
extended from which depended ropes up which the sailors
scrambled as only a sailor can, and then the Doctor thought of
death, and it was not pleasant in spite of the intense pain he was
enduring. One sailor lost his grip and fell into the sea, never to be
seen again.
What could a man so maimed as the Doctor was do to save himself
under such circumstances? Nothing. There seemed no hope for him,
and he thought of descending into that watery grave and slowly
disintegrating in the ooze at the bottom of the ocean; and the horror
of it took hold on him, for he was a young man and wanted to live.
Finally all were out of the boat but the men at bow and stern, the
Doctor, and George W. Tichenor, when the latter shouted that they
must do something to save the man who had saved them all. A rope
66. was then thrown from the vessel and a bowline passed over the
Doctor’s right shoulder and under his left arm, and the poor, maimed
body was dragged on board as a bag of potatoes might have been,
but he was saved. It was good to feel the wooden deck under foot
once more.
NOTES ON THE CRANE FAMILY.
The last property on this old road was the Crane estate. The first of
the name to settle here was Jasper Crane (born 1680), and he is
supposed to have come here about 1730. The family genealogy goes
back to an earlier Jasper, born 1600, who is said to have been a son
of Gen. Josiah Crane, who was in the service of King James I. of
England. Jasper married in England, as his son John was born there
in 1635. Jasper came from England about 1639 and was one of the
early settlers of New Haven, Connecticut, where he was a magistrate
for several years. From there he removed to Branford and from the
latter place to Newark in 1665. Here he was a magistrate, was first
president of the Town Council and was first on the list of deputies to
the General Assembly of New Jersey for six years after the
settlement of Newark.
John Crane, born 1635, had a son Jasper, born 1680 (the first to
settle here). His son Joseph was born 1722; this Joseph had a son
Joseph, born 1767, and his son was Nathaniel Jonas Crane, born
1808.
67. Crane Homestead. Supposed to have been erected
about 1760. Picture taken in 1890. The barn which
stood back of this house was the one in which cattle
were slaughtered for the troops of General Anthony
Wayne.
The old Crane stone house is supposed to have been erected about
1760 by Joseph Crane; this was taken down about 1890. The small
wing at the right of the building is believed to have been the older
part of the house. Those now living remember that in the attic of
this part were several swords of various descriptions which Nathaniel
J. Crane has said were used by members of the family who fought in
the French and Indian War. The barn which stood in the rear of this
house is the one referred to elsewhere as having been used as a
slaughter-house when General Anthony Wayne was camped under
this ridge.
Beyond the Crane house is the Keen homestead, which is mentioned
in connection with the old Bloomfield road.
68. Note for page 126.—Information concerning the Sidman family
which was received after this book was in type and inserted at
the last minute, shows that Jasper Crane owned land here as
early as 1711. See page 100.
69. PART II.
C. C. Hine In 1895. “There may have
been men of greater and more beautiful
character than his, but I never knew any
and never read of any. I count it one of
70. the most fortunate things of my life to
have been for so many years so closely
associated with him. While it (the
portrait) does not do full Justice to the
subject (I do not think any photograph
could), it is a face I am glad to look at
and it recalls some of the pleasantest
memories of my whole life and some of
the things which, I am sure, have been
of the utmost value to me in many ways.
He left nothing but a trail of good
wherever he went. My memory is of a
life rather than of episodes; I only wish I
could describe it as it was lived. The only
two absolutely unselfish people I ever
knew were Mr. Hine and my own
mother.”
71. C. C. HINE AND HIS TIMES.
This second part is intended to cover as well as may be the period of
time beginning with the opening of Woodside as a residence section.
During these years Mr. Charles Cole Hine took such an active interest
in the welfare of the neighborhood and was so wrapped up in and
identified with its best interests that its history is his biography,
consequently I feel that it will be proper to give here a brief outline
of his life previous to the year 1867, when he settled in Woodside.
When women could lift their little children up to “take a last look at
the best friend they ever had”, as was done while the people passed
by the coffin of Mr. Hine as it lay in the church, such as did not come
in direct contact with the man may to some extent understand what
a feeling of love he inspired in those who knew him.
For me he had a living reality that death has never removed; it was
years before I could accept the situation. Concerning no one else
have I ever had the same feeling. Death has removed others and I
have accepted the condition as final, but for a long period after the
death of my father I had a feeling amounting to momentary
conviction that he had opened the office door and was coming
toward me, and have looked up from my desk many a time to
welcome him. This could not have been a matter of local association,
for I was occupying an office which he never saw. What it was I do
not know.
“Thy voice is on the rolling air,
I hear thee where the waters run;
Thou standest in the rising sun,
And in the setting thou art fair.”
72. CHARLES COLE HINE.
Charles Cole Hine was born in New Haven, Conn., December 21,
1825. When six years of age his parents removed to Hornellsville, N.
Y. His father was a carriage builder, but of nomadic tendencies, and
the boy had small opportunity for schooling, though as a matter of
fact he went to school all his life; he had an instinct for acquiring
knowledge that could not be suppressed, and as a result those who
knew him best in after life took it for granted that he was a college-
bred man.
With the versatility of many another self-made man he turned his
hand to many things in his youth while finding himself. He once went
on a concert tour with three other young men, driving from town to
town through Ohio and western Pennsylvania. At one time he turned
to art for a living and actually did support himself, after a fashion, for
a brief period, painting portraits. Mr. Hine’s father moved to
Massillon, Ohio, in 1837, and there the boy grew up and cast his first
vote. Once when clerking in a store in Massillon, among the
commodities of which was a line of books, the proprietor, who was
of a kindly disposition, allowed the young man to read as he liked,
and as a result he read every book in the place, including an
encyclopædia, some six hundred volumes in all.
When the telegraph was young he became interested in that and
established lines through parts of Ohio, Indiana and Illinois,
contracting for poles and their erection, selecting the local operators
and teaching them the Morse alphabet, and doing any other
missionary work that was needed. That he was something more in
this than ordinary is evidenced by the fact that in Reid’s “History of
the Telegraph in America” Mr. Hine’s name is frequently mentioned,
and always in complimentary terms. While in charge of the office in
Louisville, he invented a transmitter to repeat messages in order to
save the time of an operator, for in those days the electric fluid only
carried a message so far, and long distance messages must needs be
73. repeated by hand. Later some one invented and patented the same
thing and made, I believe, a fortune by it.
An operator in the early days of telegraphy was a more important
personage than at present. Mr. Hine has told how, when he was
stationed in St. Louis, 1848-9, P. T. Barnum was taking Jenny Lind
around the country and, upon reaching St. Louis, he insisted on
getting inside the telegraph office and making the acquaintance of
the operator. As a result he took Mr. Hine riding with him and gave
him two tickets for each concert, no mean gift when tickets were
selling at $20.00 each.
The year 1849 was the year of the cholera and of the “great fire” in
St. Louis. “The city was a charnel house; funerals were the principal
events and the chief business of the hour; hearses went on a trot
when they could not go faster.” Mr. Hine was convalescing from the
disease and had been carried from a room at Olive and Main streets
to his boarding house. That same night the “great fire” started on
the levee. Four hundred buildings in the business heart of the city,
which included Olive and Main streets, were destroyed.
While living in St. Louis Mr. Hine met Mary Hazard Avery, whose
parents had also removed from Connecticut, and was married to
Miss Avery in that city July 4, 1853. Before that time he had
established himself in New Albany, Ind., where in due course he
represented the Adams Express Company, and was secretary of a
plank road, notary for two banks and agent for several insurance
companies, fire and life.
While living here the New Albany Theological Seminary removed to
Chicago, leaving a splendid set of buildings vacant, and Mr. Hine
thought he saw the opportunity of his life in the establishment of a
girls’ seminary. The property was easily obtained, and he spent all
the money he had and all he could borrow fitting up the place but,
as he once put it, “the New Albany Female Seminary opened
simultaneously with the great panic of 1857”. He lost every cent he
had and came out of the crash many thousands of dollars in debt.
74. When Mr. Hine wished to enter active business again he bought up
the outstanding notes against him in order to protect himself and,
although his former creditors had no claim on him thereafter, he
gradually paid back every dollar of indebtedness with interest. In this
he followed the somewhat unique method of ascertaining who
among his old creditors were most in need, and paying these first.
As an insurance agent Mr. Hine had represented the Ætna Insurance
Company, whose western general agent had said to him: “Mr. Hine,
if ever you should want to go into insurance again, please let me
know first”, and after the crash Mr Hine promptly sent word to the
headquarters in Cincinnati that he wanted a position and as
promptly got it. Thereafter he was connected with the western office
of the Ætna until he removed to New York in 1865. Mr. Hine was
brought east by the offer of the secretaryship of the International
Insurance Company, but the methods adopted not being to his liking
he resigned. He was then practically offered the position of
Superintendent of the Insurance Department of the State of New
York, but preferring to be his own master and delighting in editorial
work, he purchased the Insurance Monitor in March, 1868, and that
became his life work.
MR. HINE IN SEARCH OF A HOME.
As soon as his work would permit he began to look about for a
home, and ultimately decided on Woodside, which was then
beginning to be exploited as a residence section for toilers in the
city. In this connection it can do no harm to tell a little story which
he often told of himself.
As a young man he spent many of his leisure hours painting, and in
1844 painted much with a certain man in Massillon, Ohio, who was
something of an artist, and during this time painted the man’s
portrait, but he had completely lost sight of his friend for more than
twenty years.
75. In 1866, when looking for a home site, Mr. Hine answered, among
others, an advertisement of a Mr. M., in Morrisania, and while
inspecting the house saw a portrait which he recognized as that of
his artist friend of 1844, and one which he had seen many times, but
which the lady of the house told him was Mr. M., an entirely different
name.
When the gentleman himself arrived Mr. Hine recognized him, but
neither gave any indication of the recognition and an appointment
was made for Mr. M. to call at the New York office of his prospective
customer the next day.
Home Of Mr. Henry J. Winser. House erected in
1866. Situated at 201 Washington Avenue. In
the foreground stands the old apple tree that
was used as a talking point by Mr. Ananias.
In the meantime Mr. Hine got out his old portrait of the man and
placed it in his office where the caller would see it, expecting a good
76. time in resuming the old acquaintance, but Mr. M. never came, and
inquiry showed that he had disappeared suddenly, leaving no
address, and that his house was vacant and in the hands of an
agent.
Mr. Hine’s portrait of the man hung for many years over a door in
the dining room at No. 209 Washington avenue, and he was fond of
relating an entirely new supposition accounting for the mysterious
disappearance of the gentleman, which was advanced by his pastor
who, on a certain occasion, was dining at the house when the story
was told, and who “looked up from his plate, gazed at the picture a
moment, and then looking me square in the eye said, in a calm,
deliberate voice: ‘Maybe he was afraid you would paint him again.’”
MR. HINE FIRST VISITS WOODSIDE.
Mr. Hine first visited Woodside in August, 1866; the house at 201
Washington avenue was for sale, having been erected by a Mr.
Babbitt, who was unable to occupy it. Mr. Hine concluded it could be
made to meet his requirements, and immediately closed the bargain;
but it seems that Mr. Henry J. Winser had before this discovered the
house and, being attracted by the great trees growing on the place,
secured the refusal of the property for a few days, and it was before
this time had expired that Mr. Hine made the purchase.
Here was a state of things which was unpleasant for all except Mr.
Babbitt, who had his money, and he referred Mr. Winser to Mr. Hine,
thus dismissing the matter so far as he was concerned. Mr. Winser
as city editor of the New York Times was then investigating the
Tweed Ring and could not attend to personal matters, hence it
devolved on Mrs. Winser to open the negotiations which resulted in
a sale to Mr. W. and the purchase of property adjoining on the north
by Mr. Hine.
THE FIRST HOUSES ERECTED ON WASHINGTON AVENUE.
77. The Winser family moved in on September 1, 1866. At this time
there were five detached houses on this (east) side of what was
then Belleville avenue; these were occupied by Messrs. Winser, Best,
Baldwin, Neumann and Daniel F. Tompkins. On the west side were
six houses, occupied (from south to north) by Messrs. Sommer, an
artist; Shannan, Mrs. Van Wyck, James Gamble, George B. Callen
and John P. Contrell. Between Elwood avenue and Carteret street the
foundations for four houses were laid, and on the hill above Carteret
street Mr. Charles D. Morrison who, with Mr. John I. Briggs,
composed the firm of Morrison & Briggs, builders, was erecting his
own dwelling. Below these groups on the south there was no
building until we came to the spacious house, embowered in trees,
of Mr. Horace H. Nichols, and across Washington avenue from Mr.
Nichols, at the point, the house built by Mr. A. P. Scharff, later
occupied by Dr. MacKie, Mr. James A. C. Van Rossam and one Flavel.
THE FIRST HOUSES ERECTED ON LINCOLN AVENUE.
On what was then known as the Back road were the houses of
Colonel Buck, Messrs. Samuel Royce, Miles I’Anson, E. A. Boyden,
John Scharff, John C. Bennett; the first house of C. D. Morrison,
present corner of May street and Summer place; the old Phillips farm
house and the house of James Swinnerton, Jr., on the northeast
corner of Elwood avenue, which was then Berkley street.
HOUSES ERECTED IN 1866-7.
Within the year there were built the houses of Mr. Hine, Mr. Harlan,
C. D. Morrison, Miss Teel, Mr. Pratt, Mr. Palmer, Mr. Faitoute, Mrs.
Jackson, Mr. F. F. Mercer, Mr. Blackwood, Mr. McDonald and Wm.
Chippendale, the latter a son of Richard Chippendale, who came to
this country on account of the Chartist troubles in England, and
78. about this time the house of Mr. Horace Carter on the Gully road was
built.
Several new houses were built on the River road near Grafton
avenue, and were occupied by Mr. Webster, Mr. Oliver Gordon,
formerly of Brooklyn, who had a large business with China and was
a colleague of the Lows; and Benjamin Brigg, son-in-law of Mr.
Gordon and the representative of the Brigg woolen mills in
Huddersfield, England.
HOMES OF AN EARLIER PERIOD.
Of the old settlers there were the houses of Sandford, Munn, Melius,
Colonel Cumming, Stimis, John McDonald, Coeyman and Weiler, on
the River road; Mr. Alfred Hardwick Gibbs on the high ground north
of the Gully road, known as “Thornhill”; the “Cedars”, built by Frank
Forester (H. W. Herbert), which had been bought by Mr. Sanchez y
Dolce, and was then occupied by him, and also a group of houses
about the junction of Washington and Grafton avenues and Halleck
Street, which is treated of elsewhere.
On the west side of Belleville avenue near Second river was the
interesting old house occupied by Mr. and Mrs. Jonathan Bird and
Mrs. Bird’s two sons by a former marriage, Lewis and George
Ashmun. This was a most delightful house, and the hospitality of the
Birds was renowned. Mrs. Bird was a daughter of the Rev. Dr.
Strong, of Massachusetts, and inherited her gracious manner and
charm of conversation from a long line of ancestors who were
among the best people of New England.
They entertained with the grace of the early part of the nineteenth
century, before the advent of that class of plutocrats that brought
ostentatious pomp and more or less bad manners into society. Mr.
Bird was a gentleman of the old school, and Mrs. Bird one of the
most gracious and beautiful of women. It was always a delight to
attend their evenings at home. One was sure of meeting all the
79. charming people of the surrounding country and Newark, and there
was no lack of brilliant conversation. When the gatherings were not
too large and the company could assemble around the hospitable
board the table-talk was sparkling with wit, while matters of graver
import were freely discussed.
It is impossible to say when this old house was erected; it bears
every evidence of having been a very fine place in its day. One
informant recalls having heard Mrs. Bird state that the house was
built before the Revolution by an Englishman who sympathized with
his king and was consequently compelled to leave the country when
war was declared. This information Mrs. Bird secured from a
daughter of Harry Coeyman, who had received it from her father.
Presumably this is Henry M. Coeyman, a son of Minard, who is said
to have served in the Revolution, and the son would thus have come
on the scene early enough to know the facts.
The records do not go beyond 1790. On July 5, 1790, James H.
Maxwell conveyed the property to Alexander McComb who, on May
21, 1792, conveyed it to Daniel McCormick who, on July 18, 1792,
conveyed to Thomas Bennett. The next transfer is a sheriff’s deed
dated June 24, 1812, to Jacob Stout, and on April 9, 1825, his
widow, Frances, conveyed to the President and Directors of the New
Jersey Bleaching, Printing & Dyeing Company. On September 10,
1829, a sheriff’s deed conveyed to Samuel Wright et als. Then follow
the names of owners as follows: Andrew Gray, Bolton et als., Edward
Dwight et als., American Print Works, 1835; James K. Mills, 1853;
George Bird, 1853, and Jonathan Bird, 1859.
During the time that the house was occupied by Mr. Bird the place
was approached from Mill street by a bridge across Second river just
above the present Washington avenue bridge.
INTRODUCING MR. ANANIAS.
80. 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!
ebookgate.com