Appendix B. Refactor: JavaScript Globals, Objects, and Closures

You know globals are wrong, don’t you? The prim and proper computer science types tell us that. But they just make life so much easier! No messing about passing long parameter lists (or refactoring long parameter lists into a single object parameter, which then doubles the length of the body code to use). No worrying about scope: they are just there (well, in JavaScript and many languages they are; in PHP you have to either use the globals keyword to declare which globals to use, or use the $_GLOBALS[] superglobal). When you need to modify them, no worrying about having to return values or reference parameters. So what were the good reasons for not using globals? Testing. Yawn. Encapsulation. Side effects. Blah, blah, blah.

But, in the context of data push applications, there is one situation where globals are going to trip us up: when you need to make two or more connections.

Note

This appendix just talks about refactoring the JavaScript to not use globals. It is an appendix because it shows general-purpose JavaScript techniques: there is nothing specifically about data push here (except the example code, of course). Basically, it is an appendix because it got a bit too big for a sidebar in the main text!

Introducing the Example

I will use a stripped-down SSE example. This code won’t have interesting data, and it won’t have the fallback code for the older browsers. None of that affects the decision of which approach is ...

Get Data Push Apps with HTML5 SSE now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.