Prepared exclusively for james shahan Prepared exclusively for james shahan CoffeeScript Accelerated JavaScript Development, Second Edition Trevor Burnham The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina Prepared exclusively for james shahan Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade- marks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at https://pragprog.com. The team that produced this book includes: Michael Swaine (editor) Potomac Indexing (indexer) Cathleen Small (copyeditor) Dave Thomas (typesetter) Janet Furlow (producer) Ellie Callahan (support) For international rights, please contact [email protected]. Copyright © 2015 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-13: 978-1-94122-226-3 Encoded using the finest acid-free high-entropy binary digits. Book version: P1.0—February 2015 Prepared exclusively for james shahan Contents Foreword . . . . . . . . . . . . . . v Acknowledgments . . . . . . . . . . . vii Introduction . . . . . . . . . . . . . ix 1. Getting Started . . . . . . . . . . . . 1 Installing CoffeeScript 1 Running and Compiling CoffeeScript 4 Using Source Maps 5 Editing CoffeeScript 6 2. Functions, Scope, and Context . . . . . . . . 7 Functions 101 7 Variable Scope 11 Execution Context 14 Mini-Project: Checkbook Balancer 16 3. Collections, Iteration, and Destructuring . . . . . . 21 Objects as Hash Maps 21 Arrays 24 Iterating over Collections 27 Mini-Project: Refactored Checkbook Balancer 29 4. Classes, Prototypes, and Inheritance . . . . . . . 35 The Power of Prototypes 35 Classes: Giving Prototypes Structure 38 Inheritance: Classy Prototype Chains 40 Mini-Project: All-Purpose Checkbook Balancer 43 5. Web Applications with jQuery and Backbone.js . . . . 49 Building the Project with Grunt 50 Prepared exclusively for james shahan Contents • iv Managing Front-End Dependencies with Bower 52 Building the Page with Templates 54 Structuring Data for Persistence 56 Representing Data in Backbone Models and Collections 57 Presenting Data with Views 61 6. Web Servers with Node and Express . . . . . . . 69 What Is Node? 69 Writing Node Modules 70 Compiling a Node Project with Grunt 72 Creating a Web Server with Express and NeDB 76 Using a RESTful API in Backbone 79 7. Testing with Intern . . . . . . . . . . . 83 Getting Started with Intern 83 Mock-Testing Backbone with Sinon 86 Mock-Testing a Node Server with Supertest 92 Bibliography . . . . . . . . . . . . . 97 Index . . . . . . . . . . . . . . 99 Prepared exclusively for james shahan Foreword JavaScript was born free, but until recently it was in chains everywhere. JavaScript wasn’t always a very pleasant language to work in: it’s terribly slow, it’s implemented with different quirks in different browsers, and it’s been stuck fast in the amber of time since the late 1990s. Perhaps you used it in the past to implement a drop-down menu or a reorderable list, but you probably didn’t enjoy the experience. Fortunately for us, the JavaScript of today is enjoying a well-deserved renaissance. Thanks to the tireless efforts of browser implementers, JavaScript is now the fastest mainstream dynamic language. It’s present everywhere, from servers to Photoshop, and it’s the only language you can use to program all angles of the Web. CoffeeScript is a little language that aims to give you easy access to the good parts of JavaScript: the first-class functions, the hash-like objects, even the much-misunderstood prototype chain. If we do our job right, you’ll end up writing one-third less code to generate much the same JavaScript you would’ve written in the first place. CoffeeScript places a high value on the readability of code and the elimination of syntactic clutter. At the same time, there’s a fairly one-to-one correspon- dence between CoffeeScript and JavaScript, which means that there should be no performance penalty—in fact, many JavaScript libraries end up running faster after being ported to CoffeeScript, due to some of the optimizations the compiler can perform. You’re fortunate to have picked up this book, because Trevor has been an enthusiastic contributor to CoffeeScript since the early days. Few people know more about the ins and outs of the language or the history of the debate behind language features and omissions than he does. This book is a gentle introduction to CoffeeScript led by an expert guide. Prepared exclusively for james shahan report erratum • discuss Foreword • vi I’m looking forward to hearing about all of the exciting projects that I’m sure will come out of it, and—who knows—perhaps you’ll be inspired to create a little language of your very own. Jeremy Ashkenas, creator of CoffeeScript April 2011 Prepared exclusively for james shahan report erratum • discuss Acknowledgments My warmest thanks to Jeremy Ashkenas for creating the CoffeeScript language and serving as its steward for all these years. No one better embodies the hacker ethos: the curiosity to try new things, the drive to see them through, and the generosity to share the results with the world. Thanks also to Coffee- Script’s other contributors, who are too numerous to name here.1 Thanks to the technical reviewers and beta readers who provided valuable feedback for this edition: Vincent Bray, Javier Collado, Matthew Critchlow, Daniel Lamb, Rod Hilton, Scott Leberknight, Staphany Park, and Travis Swicegood. Some thanks from the first edition bear repeating. I’d like to thank technical reviewers Javier Collado, Kevin Gisi, Darcy Laycock, Scott Leberknight, Sam Stephenson, Travis Swicegood, Federico Tomassetti, Stefan Turalski, and Dr. Nic Williams. Special thanks to experts Jeremy Ashkenas, Brendan Eich, and Michael Ficarra for their assistance. Thanks to the Pragmatic Bookshelf for taking a chance all those years ago on a proposal from an unknown writer about a then-obscure language, and special thanks to the team that helped me produce this second edition. First and foremost to editor Michael Swaine, without whom I don’t know how I would have finished this. Thanks also to managing editor Susannah Pfalzer and to the Prags themselves, Dave Thomas and Andy Hunt. Thanks to my employer, HubSpot, for allowing me all the time I asked for to work on this edition. And for Panini Club. Thanks, finally, to my parents, Scott and Teresa Burnham. Their love and support made this book and so much more possible. 1. http://github.com/jashkenas/coffee-script/contributors Prepared exclusively for james shahan report erratum • discuss Introduction JavaScript was never meant to be the most important programming language in the world. It was hacked together in ten days, with ideas from Scheme and Self packed into a C-like syntax. Even its name was an awkward fit, referring to a language with little in common besides a few keywords. (For the story behind that, see Peter Seibel’s interview with Brendan Eich, the creator of JavaScript, in Coders at Work [Sei09].) But once JavaScript was released, there was no controlling it. As the only language understood by all major browsers, JavaScript quickly became the lingua franca of the Web. And with the introduction of Ajax in the early 2000s, what began as a humble scripting language for enhancing web pages suddenly became a full-fledged rich application development language. As JavaScript’s star rose, discontent came from all corners. Some pointed to its numerous little quirks and inconsistencies.1 Others complained about its lack of classes and inheritance. And a new generation of coders, who had cut their teeth on Ruby and Python, were stymied by its thickets of curly braces, parentheses, and semicolons. A brave few created frameworks for web application development that gener- ated JavaScript code from other languages, notably Google’s GWT and 280 North’s Objective-J. But few programmers wanted to add a thick layer of abstraction between themselves and the browser. No, they would press on, dealing with JavaScript’s flaws by limiting themselves to “the good parts” (as in the title of Douglas Crockford’s now-classic book). And then CoffeeScript came along. The New Kid in Town On Christmas Day 2009, Jeremy Ashkenas first released CoffeeScript, a little language he touted as “JavaScript’s less ostentatious kid brother.” The project 1. http://wtfjs.com/ Prepared exclusively for james shahan report erratum • discuss
Description: