background preloader

JavaScript Module Pattern: In-Depth

JavaScript Module Pattern: In-Depth
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 best feature of JavaScript. (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 implied globals. Luckily, our anonymous function provides an easy alternative. (function ($, YAHOO) { // now have access to globals jQuery (as $) and YAHOO in this code }(jQuery, YAHOO));

Learning JavaScript Design Patterns 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. This can be significantly simpler than describing syntax and semantics when we're attempting to convey a way of structuring a solution in code form to others. 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. Acknowledgments Credits Reading We already use patterns everyday

dojo.setObject Set a property from a dot-separated string, such as “A.B.C”. In javascript, a dot separated string like obj.parent.child refers to an item called child inside an object called parent inside of obj. setObject will let you set the value of child, creating the intermediate parent object(s) if they don’t exist. Without dojo.setObject, we often see code like this: // ensure that intermediate objects are availableif(! // ensure that intermediate objects are available if(! Wheras with dojo.setObject, we can shorten that to: // Dojo 1.7 (AMD)require(["dojo/_base/lang"], function(lang){ lang.setObject("parent.child.prop", "some value", obj);});// Dojo < 1.7dojo.setObject("parent.child.prop", "some value", obj); // Dojo 1.7 (AMD) require(["dojo/_base/lang"], function(lang){ lang.setObject("parent.child.prop", "some value", obj); }); // Dojo < 1.7 dojo.setObject("parent.child.prop", "some value", obj);

JavaScript: Function Invocation Patterns JavaScript has been described as a Functional Oriented Language (this as opposed to Object Oriented Language). The reason is because functions in JavaScript do more than just separate logic into execution units, functions are first class citizens that also provide scope and the ability to create objects. Having such a heavy reliance upon functions is both a blessing and a curse: It's a blessing because it makes the language light weight and fast (the main goal of its original development), but it is a curse because you can very easily shoot yourself in the foot if you don't know what you are doing. One concern with JavaScript functions is how different invocation patterns can produce vastly different results. This post explains the four patterns, how to use them and what to watch out for. The four invocation patterns are: Method InvocationFunction InvocationConstructor InvocationApply And Call Invocation Unfortunately, there is more than one pattern that can be used to invoke functions.

Partial Application in JavaScript Partially applying a function is a, particularly, interesting technique in which you can pre-fill-in arguments to a function before it is ever executed. In effect, partially applying a function returns a new function which you can call. This is best understood through an example: String.prototype.csv = String.prototype.split.partial(/,\s*/); var results = "John, Resig, Boston".csv(); alert( (results[1] == "Resig") + " The text values were split properly" ); In the above case we’ve taken a common function – a String’s .split() method – and have pre-filled-in the regular expression upon which to split. Function.prototype.curry = function() { var fn = this, args = Array.prototype.slice.call(arguments); return function() { return fn.apply(this, args.concat( Array.prototype.slice.call(arguments))); }; }; This is a good case of using a closure to remember state. Now, this style of partial application is perfectly useful, but we can do better.

Detect rotation of Android phone in the browser with javascript Using Objects to Organize Your Code This is a reprint of an article that originally appeared in the March 2009 issue of JSMag. When you move beyond simple snippets of jQuery and start developing more complex user interactions, your code can quickly become unwieldy and difficult to debug. This article shows you how to start thinking about these interactions in terms of the bits of behavior the feature comprises, using the object literal pattern. In the past few years, JavaScript libraries have given beginning developers the ability to add elaborate interactions to their sites. But wait. Introducing the Object Literal pattern The object literal pattern offers a way to organize code by the behaviors it comprises. As an artificially simplistic example, suppose you had the jQuery shown in Listing 2 for showing and hiding content when a list item was clicked. Because the initial example was incredibly simplistic, the object literal incarnation is longer. An in-depth example Step 1: Crafting the HTML Step 2: Scaffolding the Object

Strategy Design Pattern in Javascript - Trifling Whims I love the Strategy design pattern. I try to use it as much as I can. In its essence, the Strategy pattern uses delegation to decouple algorithms from the classes that use them. There are a few benefits to this. It prevents using big conditionals to decide which algorithm to use for the given type of object. It separates concerns, thus reducing the complexity of the clients and it promotes composition over subclassing. To implement Strategy, there are usually two participants: The Strategy an object that encapsulates an algorithm. The Client (or Context) an object that can use any Strategy, in a plug-and-play manner. Here is how I use the Strategy pattern in Javascript, and how it is used in the wild to break libraries into small, plug-and-play packages. Strategy as a function A function provides a great way to encapsulate an algorithm and can be used as a Strategy. Let's illustrate this with an example. In the example above, Greeter is the Client, and there are three Strategies. Reflection

Stop Writing Slow Javascript - I Like Kill Nerds As Alfred Pennyworth once profoundly said in The Dark Knight Rises: Some front-end developers just want to watch the world burn.Alfred Pennyworth, The Dark Knight Rises As developers we are constantly learning, always growing and sometimes whether we realise it at the time or not, we are always making mistakes. Here are a few tips, most of which you might already have read elsewhere on how to write performant Javascript and just even thinking about some of the things you might be doing in your applications. Getting off the jQuery pony I’ll admit it. Stay home and use jQuery for everything, KipNapoleon Dynamite Are you guilty of doing things like this for the sake of convenience? $('#somediv').hide(); instead of element.style.display = 'none';$('#somediv').show(); instead of element.style.display = '';$('#myinput').val(); instead of element.value Don’t feel bad, we have all been there. I am not saying you should abandon jQuery entirely, but you shouldn’t use it for everything. The jQuery way

3 ways to define a JavaScript class Introduction JavaScript is a very flexible object-oriented language when it comes to syntax. In this article you can find three ways of defining and instantiating an object. Even if you have already picked your favorite way of doing it, it helps to know some alternatives in order to read other people's code. It's important to note that there are no classes in JavaScript. 1. This is probably one of the most common ways. function Apple (type) { this.type = type; this.color = "red"; this.getInfo = getAppleInfo; } function getAppleInfo() { return this.color + ' ' + this.type + ' apple'; } To instantiate an object using the Apple constructor function, set some properties and call methods you can do the following: var apple = new Apple('macintosh'); apple.color = "reddish"; alert(apple.getInfo()); 1.1. In the example above you see that the method getInfo() of the Apple "class" was defined in a separate function getAppleInfo(). 1.2. 2. apple.color = "reddish"; alert(apple.getInfo()); 3. Summary

Learning JavaScript Design Patterns 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

Spring-cleaning Unused CSS With Grunt, Gulp, Broccoli or Brunch [caption id="attachment_6609" align="aligncenter" width="640"] The tough economic times on Tatooine hit everyone hard, including the Jawas.[/caption] Delivering a fast experience on the web usually involves reducing server response time, minification of CSS/JS/HTML and an optimisation of images and above-the-fold content. We can further minimize the latency caused by stylesheet loading by removing unused CSS rules delivered to the client. In this write-up, we'll take a look at build tasks you can use to remove unused CSS in your pages. Unused CSS is a particular problem when working with a heavy modern UI framework such as Twitter Bootstrap, Zurb Foundation or Adobe TopCoat. This is a problem that’s been previously highlighted by the PageSpeed team, who include removing unused CSS as part of their speed recommendations for the web: "Before a browser can begin to render a web page, it must download and parse any stylesheets that are required to lay out the page. UnCSS Using grunt-uncss

Related: