background preloader

A JavaScript Module Pattern

A JavaScript Module Pattern
Eric Miraglia (@miraglia) is an engineering manager for the YUI project at Yahoo. Eric has been at Yahoo since 2003, working on projects ranging from Yahoo Sports to YUI. For the past several years, Eric and his colleagues on the YUI team have worked to establish YUI as the foundation for Yahoo’s frontend engineering work while open-sourcing the project and sharing it with the world under a liberal BSD license. Eric is an editor and frequent contributor to YUIBlog; his personal blog is at ericmiraglia.com. Prior to working at Yahoo, Eric taught writing at Stanford and elsewhere and led frontend engineering teams at several startups. Global variables are evil. Douglas Crockford has been teaching a useful singleton pattern for achieving this discipline, and I thought his pattern might be of interest to those of you building on top of YUI. 1. YAHOO.namespace("myProject"); This assigns an empty object myProject as a member of YAHOO (but doesn’t overwrite myProject if it already exists). 2.

Google Closure: How not to write JavaScript At the Edge of the Web conference in Perth last week I got to catch up with Dmitry Baranovskiy, the creator of the Raphaël and gRaphaël JavaScript libraries. Perhaps the most important thing these libraries do is make sophisticated vector graphics possible in Internet Explorer, where JavaScript performance is relatively poor. Dmitry, therefore, has little patience for poorly-written JavaScript like the code he found in Google’s just-released Closure Library. Having delivered a talk on how to write your own JavaScript library (detailed notes) at the conference, Dmitry shared his thoughts on the new library over breakfast the next morning. “Just what the world needs—another sucky JavaScript library,” he said. For the rest of the day, to anyone who would listen, Dmitry cited example after example of the terrible code he had found when he went digging through Closure. “I’ll make you a deal,” I told him. The Slow Loop From array.js, line 63: for (var i = fromIndex; i < arr.length; i++) {

Adequately Good - JavaScript Module Pattern: In-Depth - by Ben Cherry The module pattern is a common JavaScript coding pattern. It's generally well understood, but there are a number of advanced uses that have not gotten a lot of attention. In this article, I'll review the basics and cover some truly remarkable advanced topics, including one which I think is original. The Basics We'll start out with a simple overview of the module pattern, which has been well-known since Eric Miraglia (of YUI) first blogged about it three years ago. Anonymous Closures This is the fundamental construct that makes it all possible, and really is the single . (function () { // ... all vars and functions are in this scope only // still maintains access to all globals }()); Notice the () around the anonymous function. Global Import JavaScript has a feature known as . Luckily, our anonymous function provides an easy alternative. (function ($, YAHOO) { // now have access to globals jQuery (as $) and YAHOO in this code }(jQuery, YAHOO)); Module Export Advanced Patterns Augmentation

jquery - Examples of practical javascript object oriented design patterns css3-mediaqueries-js - Project Hosting on Google Code css3-mediaqueries.js by Wouter van der Graaf is a JavaScript library to make IE 5+, Firefox 1+ and Safari 2 transparently parse, test and apply CSS3 Media Queries. Firefox 3.5+, Opera 7+, Safari 3+ and Chrome already offer native support. UPDATE: Google discontinued the downloads section. Download newest version 1.0 from here: Usage: just include the script in your pages. (And you should combine and compress with other scripts and include it just before </body> for better page speed - but you already knew that). Write your media queries like you would for browsers with native support. Note: Doesn't work on @import'ed stylesheets (which you shouldn't use anyway for performance reasons). Happy media querying!

The Module Pattern, A Little More Detail - macwright.org Once you’ve read this, read the update which has more detailed information about the module pattern’s performance profile! This is an article on the module pattern for Javascript, and some of its neat properties when used for instances. I’ve been using it recently for projects like mapbox.js, and think it’s a neat way to structure code and avoid some of the less likable parts of the language. For those already doing Javascript: here’s why you should care. You can mostly avoid the problem of tracking the meaning of Javascript’s pesky this keyword, and the associated problem of rebinding functions to another this value.You can keep truly internal ‘states’ of your code private while exposing minimal APIs that you know will stay stable.Often this yields code that’s more friendly to Javascript compression, like I wrote about in Writing Javascript For SizeYou can avoid the sneaky problems of users forgetting the new keyword, and the workarounds people use to dodge them Let’s Begin A Quick Summary

Learning JavaScript Design Patterns A book by Addy Osmani [Pdf] Design patterns are reusable solutions to commonly occurring problems in software design. They are both exciting and a fascinating topic to explore in any programming language. One reason for this is that they help us build upon the combined experience of many developers that came before us and ensure we structure our code in an optimized way, meeting the needs of problems we're attempting to solve. Design patterns also provide us a common vocabulary to describe solutions. In this book we will explore applying both classical and modern design patterns to the JavaScript programming language. Target Audience This book is targeted at professional developers wishing to improve their knowledge of design patterns and how they can be applied to the JavaScript programming language. Some of the concepts covered (closures, prototypal inheritance) will assume a level of basic prior knowledge and understanding. Acknowledgments Credits Reading Patterns are not an exact solution. Creational Design Patterns

Understanding JavaScript’s this keyword | JavaScript, JavaScript (In Portugese) The JavaScript this keyword is ubiquitous yet misconceptions abound. What you need to know Every execution context has an associated ThisBinding whose lifespan is equal to that of the execution context and whose value is constant. There are three types of execution context: global, function and evaluation. Here’s a tabular summary followed by a little more detail, and some examples: 1. 2. a) Invoke as a methodthis is the baseValue of the property reference b) Invoke as baseless function callthis is the global object (or undefined in strict mode) The same applies to self invoking functions: c) Invoke using Function.prototype.callthisis passed by argument d) Invoke using Function.prototype.applythis is passed by argument e) Invoke a constructor using newthis is the newly created object 3. What you might want to know This section explores the process by which this gets its value in the functional context – using ECMA-262 version 5.1 as a reference. from ECMA 5.1, 11.1.1 1. 1. In full…

JavaScript Design Patterns: Composite | Joe Zim's JavaScript BlogJoe Zim's JavaScript Blog My last post was about the Bridge Design Pattern, which continued the JavaScript Design Patterns series that started off with the Singleton. Today we’ve moved onto the Composite Pattern. Composites are quite useful. By definition of the word “composite”, Composites are composed of multiple parts to create one whole entity. These are the two main benefits that the Composite pattern provides: You can treat the whole collection of objects the same way you would treat any of the individual objects in the collection. It organizes the objects into a tree structure, and since each composite object contains a method to get its children, you can hide the implementation and organize the children in any way you wish. Structure of the composite pattern In the Composite patterns hierarchy, there are two types of objects: leaf and composite. Examples of the Composite Pattern There a number of somewhat common examples of the Composite pattern. If you look around, I’m sure you’ll see some more examples.

Writing functions General syntax Pre-alpha versions of Tkhtml Hv3 do not correctly interpret the Function class constructor. Functions group together script code; control structures, operations, method calls, etc. in the same way as a normal script. These functions can then be called when needed, and the code contained within them will be run. This makes it very easy to reuse code without having to repeat it within your script. Functions are defined using one of these constructs: Normal function construct function nameOfFunction(listOfVariableNames) { function code should be written here } Anonymous function, assigned to a variable Using this syntax for object methods in early Netscape 4 versions will cause problems with the 'this' keyword due to bugs. nameOfFunction = function (listOfVariableNames) { function code should be written here }; Normal function construct, assigned to a variable nameOfFunction = function anotherNameForTheFunction(listOfVariableNames) { function code should be written here }; Fade!

base2 - Project Hosting on Google Code Because this library is standards-based it means that you don’t have to learn a new API. It uses standard (DOM, ECMAScript) properties and methods throughout which also means that there is no need for a lot of accompanying documentation. base2 is a lightweight library that irons out all the annoying differences in JavaScript implementations. It provides the additional functionality from JavaScript 1.6+ that only Mozilla browsers implement. It also adds some features from ES4. A fast implementation of the Selectors API Fixes broken browser implementations of the DOM events module including document.createEvent(), dispatchEvent(), addEventListener(), etc Supports DOMContentLoaded Fixes getAttribute()/setAttribute()/hasAttribute() (Internet Explorer) Implements getElementsByClassName() Implements a few other useful DOM methods like getComputedStyle() and compareDocumentPosition() Supports a variety of browsers including ancient browsers like IE5.0 (Windows and Mac) Current version: 1.0.2

JavaScript Design Patterns: Singleton | Joe Zim's JavaScript BlogJoe Zim's JavaScript Blog This is the first in what should be a pretty long series about JavaScript design patterns. In 1995, Erich Game, Richard Helm, Ralph Johnson and John Vlissides (known as the Gang of Four) published Design Patterns: Elements of Reusable Object-Oriented Software, a book cataloging recurring solutions to common dilemmas in software architecture and design. It also started a common vocabulary for referring to these solutions. If you’d like to know more you can find it on Wikipedia. That book’s example implementations of each of the solutions were written in C++ and Smalltalk, which are quite different than JavaScript. Another book – Pro JavaScript Design Patterns – was written to bring many of those patterns into the context of JavaScript. In JavaScript, the singleton is extremely simple and could possibly be excluded from the designation of singleton, but it does technically work similarly to a singleton, so it’s still useful to know. A Basic Singleton JavaScript Namespacing About the Author

Creating objects Netscape 4, IE 4 on Windows and Mac, and IE 5 on Mac do not support the operator. Any function in JavaScript can be used to create custom object classes, simply by calling it using the keyword new . When called in this way, the special variable inside the function references the new object that is being constructed (it normally refers to the 'current' object, which is usually , except inside methods). The function should not return a value. The following function can be used as demonstrated to create an object of class : function myobject() { this.containedValue = 0; this.othercontainedValue = 0; this.anothercontainedValue = 0; } var mything = new myobject(); And there you go, is now an instance of class . You could also now write this: myobject.prototype.newContainedValue = someValue; This will cause all instances of class will have the property with value . Use the instanceof operator to find out if your object is an instance of a given object class: Creating an object with methods

Related: