Coffeescript Accelerated Javascript Development.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
Download from Wow! eBook <www.wowebook.com> What readers are saying about CoffeeScript: Accelerated JavaScript Development It’s hard to imagine a new web application today that doesn’t make heavy use of JavaScript, but if you’re used to something like Ruby, it feels like a significant step down to deal with JavaScript, more of a chore than a joy. Enter CoffeeScript: a pre-compiler that removes all the unnecessary verbosity of JavaScript and simply makes it a pleasure to write and read. Go, go, Coffee! This book is a great introduction to the world of CoffeeScript. ➤ David Heinemeier Hansson Creator, Rails Just like CoffeeScript itself, Trevor gets straight to the point and shows you the benefits of CoffeeScript and how to write concise, clear CoffeeScript code. ➤ Scott Leberknight Chief Architect, Near Infinity Though CoffeeScript is a new language, you can already find it almost everywhere. This book will show you just how powerful and fun CoffeeScript can be. ➤ Stan Angeloff Managing Director, PSP WebTech Bulgaria Download from Wow! eBook <www.wowebook.com> This book helps readers become better JavaScripters in the process of learning CoffeeScript. What’s more, it’s a blast to read, especially if you are new to Coffee- Script and ready to learn. ➤ Brendan Eich Creator, JavaScript CoffeeScript may turn out to be one of the great innovations in web application development; since I first discovered it, I’ve never had to write a line of pure JavaScript. I hope the readers of this wonderful book will be able to say the same. ➤ Dr. Nic Williams CEO/Founder, Mocra CoffeeScript: Accelerated JavaScript Development is an excellent guide to Coffee- Script from one of the community’s most esteemed members. It’ll help you get up to speed with the language in no time, whether you write code that runs in the browser or on the server. Trevor’s book belongs on every CoffeeScript developer’s shelf. ➤ Sam Stephenson Creator, Prototype JavaScript framework Download from Wow! eBook <www.wowebook.com> CoffeeScript is one of the most interesting developments in the world of program- ming languages in the last few years. Taking the lessons learned over the last decade from languages like Ruby and Python, it is a language with immense ex- pressive power. CoffeeScript: Accelerated JavaScript Development is your guide to this new language and a must-read for those interested in being productive in JavaScript. ➤ Travis Swicegood Author, Pragmatic Version Control Using Git Trevor serves up a rich blend of language overview and real-world examples, showcasing why I consider CoffeeScript my secret weapon for iOS, Android, and WebOS mobile development. ➤ Wynn Netherland Co-host, The Changelog Fasten your seat belt and enjoy the ride with Trevor Burnham from JavaScript to CoffeeScript and have fun with web development again. ➤ Javier Collado QA Automation Engineer, Canonical Ltd. Download from Wow! eBook <www.wowebook.com> CoffeeScript Accelerated JavaScript Development Trevor Burnham The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina Download from Wow! eBook <www.wowebook.com> 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 http://pragprog.com. The team that produced this book includes: Michael Swaine (editor) Potomac Indexing, LLC (indexer) Kim Wimpsett (copyeditor) David Kelly (typesetter) Janet Furlow (producer) Juliet Benda (rights) Ellie Callahan (support) Copyright © 2011 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-934356-78-4 Printed on acid-free paper. Book version: P1.0—July 2011 Download from Wow! eBook <www.wowebook.com> Contents Foreword . xi Acknowledgments . xiii Preface . xv 1. Getting Started . 1 1.1 Installing CoffeeScript 1 1.2 Text Editors for CoffeeScript 5 1.3 Meet ’coffee’ 6 1.4 Debugging CoffeeScript 9 2. Functions, Scope, and Context . 13 2.1 Functions 101 13 2.2 Scope: Where You See ’Em 18 2.3 Context (or, “What Is ’this’?”) 21 2.4 Property Arguments (@arg) 24 2.5 Default Arguments (arg =) 25 2.6 Splats (...) 28 2.7 Project: 5x5 Input Parser 29 2.9 Exercises 34 3. Collections and Iteration . 37 3.1 Objects as Hashes 37 3.2 Arrays 40 3.3 Iterating over Collections 43 3.4 Conditional Iteration 46 3.5 Comprehensions 47 3.6 Pattern Matching (or, Destructuring Assignment) 48 3.7 Project: 5x5 Solitaire 50 3.9 Exercises 56 Download from Wow! eBook <www.wowebook.com> • viii 4. Modules and Classes . 59 4.1 Modules: Splitting Up Apps 60 4.2 The Power of Prototypes 61 4.3 Classes: Functions with Prototypes 63 4.4 Inheritance with ’extends’ 65 4.5 Project: Refactoring 5x5 68 4.7 Exercises 72 5. Web Interactivity with jQuery . 75 5.1 The Tao of jQuery 76 5.2 Manipulating the DOM 76 5.3 Getting Selective 77 5.4 Reacting to Events 79 5.5 Project: Browser-Based 5x5 80 5.7 Exercises 88 6. Server-Side Apps with Node.js . 91 6.1 What Is Node.js? 91 6.2 Modularizing Code with ’exports’ and ’require’ 92 6.3 Thinking Asynchronously 93 6.4 Project: Multiplayer 5x5 97 6.6 Exercises 105 A1. Answers to Exercises . 107 A 1 . 1 Functions, Scope, and Context 107 A 1 . 2 Collections and Iteration 109 A 1 . 3 Modules and Classes 111 A 1 . 4 Web Interactivity with jQuery 112 A 1 . 5 Server-Side Apps with Node.js 113 A2. Ways of Running CoffeeScript . 115 A 2 . 1 Web Consoles 115 A 2 . 2 Running CoffeeScript in Your Web App 116 A 2 . 3 CoffeeScript on Rails 116 A 2 . 4 CoffeeScript via Middleware 117 A 2 . 5 CoffeeScript on Node.js 117 A 2 . 6 Rapid Websites with Middleman 118 A 2 . 7 CoffeeScript for System Scripts 119 Download from Wow! eBook <www.wowebook.com> • ix A3. Cheat Sheet for JavaScripters . 121 A 3 . 1 Boolean Operators 121 A 3 . 2 The Existential Operator 121 A 3 . 3 Context and Prototype Accessors 122 A 3 . 4 Function Definitions 122 A 3 . 5 Conditionals 122 A 3 . 6 Property Existence 122 A 3 . 7 Iteration 123 A4. Bibliography . 125 Index . 127 Download from Wow! eBook <www.wowebook.com> • x Download from Wow! eBook <www.wowebook.com> Foreword JavaScript is born free, but until recently, everywhere it was in chains. JavaScript had never been a very pleasant language to work in: terribly slow, implemented with different quirks in different browsers, stuck fast in the amber of time since the late 1990s. Perhaps you used it in the past to implement a dropdown 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 re- naissance. Thanks to the tireless efforts of browser implementers, it’s now the fastest mainstream dynamic language; it’s present everywhere, from servers to Photoshop, and it’s the only possible 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 in order to generate much the same JavaScript you would have 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 run- ning 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. Download from Wow! eBook <www.wowebook.com> report erratum • discuss • xii 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 Download from Wow! eBook <www.wowebook.com> report erratum • discuss Acknowledgments CoffeeScript is a young language. But from the start, it’s drawn an excep- tionally diverse and spirited crowd. That wonderful energy—on IRC, GitHub, Hacker News, blogs, Twitter, and elsewhere—is what inspired me to write this book.