Transcript
Page 1: Write Better Javascript code

Write Better JavascriptEvent #4

Aymeric Gaurat Apelli Senior Developer

Page 2: Write Better Javascript code

Who am I? Why a “Who am I?”

• Aymeric Gaurat-Apelli• .NET developer/consultant since first beta• Worked in France, Australia (Readify) and Thailand• Web entrepreneur • Facebook games (1M users/day)• http://taskarmy.com• http://weekplan.net (knockout.js SPA)

• Principal developer at Jetabroad (Thailand)

Page 3: Write Better Javascript code

“Classes”Yes you can… kind of.

Want inheritance? http://ejohn.org/blog/simple-javascript-inheritance/

Page 4: Write Better Javascript code

Coding principles

DRYDon’t repeat yourself

KISSSimplicity (and avoiding complexity) should always be a key goal.

YAGNIYou aren’t going to need it.

They apply to Javascript too!

Page 5: Write Better Javascript code

Coding principles

LAW OF DEMETERCode components should only communicate with their direct relations

SRPA component of code (e.g. class or function) should perform a single well defined task.

DEPENDENCY INJECTIONDepend upon Abstractions. Do not depend upon Concretions.

Page 6: Write Better Javascript code

Suggestion:http://jsfiddle.net/XejEY/1/

How would you rewrite this code?

Page 7: Write Better Javascript code

JavascriptFrameworksMore structure for your code

Check outhttp://todomvc.com/

Page 8: Write Better Javascript code

Templatingengines

Choose a template engine

http://jsfiddle.net/aPv9H/1/

Allow you to reuse snippets of HTML and to bind it to your data

Fast templating engine.

Page 9: Write Better Javascript code

ScopeA bit different from C# http://madebyknight.com/javascript-scope/

http://jsfiddle.net/Ukv2R/1/

There is no block level scope.

Page 10: Write Better Javascript code

ModulesThe solution to spaghetti code

Page 11: Write Better Javascript code

Sample home grown module

Page 12: Write Better Javascript code

AMD, the standard.

Popular AMD module loader: requirejs

Page 13: Write Better Javascript code

Dependencies versus events

Page 14: Write Better Javascript code

Dependencies versus eventsAfter refactoring

Router.js module

Page 15: Write Better Javascript code

Unit testinghttp://qunitjs.com/intro/

http://pivotal.github.io/jasmine/

Page 16: Write Better Javascript code

Random tips

1. Link to your javascript code at the end of your HTML document

2. Bundle and minify

3. Work with css classes instead of working with styling/animations

Example

Page 17: Write Better Javascript code

Resourcesto learn

http://microjs.com/Fantastic micro libraries to use and learn from

http://dailyjs.comBlog about new stuff in the Javascript world

http://github.comSearch for javascript projects

http://terrariumjs.wiselabs.net

Page 18: Write Better Javascript code

Thank you


Top Related