Namespacing in JavaScript. Global variables should be reserved for objects that have system-wide relevance and they should be named to avoid ambiguity and minimize the risk of naming collisions. In practice this means you should avoid creating global objects unless they are absolutely necessary. But, hey, you already knew all that….. So what do you do about it? Conventional wisdom tells us that the best global abatement strategy is to create a small number of global objects which will serve as de facto namespaces for underlying modules and subsystems. Static Namespacing I’m using static namespacing as an umbrella term for solutions in which the namespace label is effectively hard coded. 1. The most basic approach. You could make future maintenance a little easier by using this to reference sibling properties – but this is a little risky since there is nothing to stop your namespaced functions from being reassigned: 2. 3.
I find myself using the module pattern more often these days. Dynamic Namespacing 4. 5. My Favorite JavaScript Design Pattern. I thought it might be interesting to look at a JavaScript design pattern that I use a great deal. I settled on it gradually, over a period of time, absorbing and adapting influences from various sources, until reaching a pattern that offers the flexibility I need. Let me show you an overview, and then look at how it comes together: As you can see from that sample code, the overall structure is a function literal (function() { ... })(); A function literal is essentially a self-executing scope, equivalent to defining a named function and then calling it immediately: function doSomething() { ... } doSomething(); I originally started using function literals for the sake of encapsulation —any script in any format can be wrapped in that enclosure, and it effectively “seals” it into a private scope, preventing it from conflicting with other scripts in the same scope, or with data in the global scope.
The Beauty Within public data with each other. var THIS = this; We’ve created a private variable Wrapped Up! Design Patterns for JavaScript Applications. Writing Modular JavaScript With AMD, CommonJS & ES Harmony. When we say an application is modular, we generally mean it's composed of a set of highly decoupled, distinct pieces of functionality stored in modules. As you probably know, loose coupling facilitates easier maintainability of apps by removing dependencies where possible. When this is implemented efficiently, its quite easy to see how changes to one part of a system may affect another. Unlike some more traditional programming languages however, the current iteration of JavaScript (ECMA-262) doesn't provide developers with the means to import such modules of code in a clean, organized manner. It's one of the concerns with specifications that haven't required great thought until more recent years where the need for more organized JavaScript applications became apparent.
Instead, developers at present are left to fall back on variations of the module or object literal patterns. Today it's embraced by projects including Dojo (1.7), MooTools (2.0), Firebug (1.8) and even jQuery (1.7). App.js. Brian Ford. AngularJS is like the missing Batarang on your utility belt of web development awesomeness.
It gives you two-way data binding that's both easy to use and fast, a powerful directive system that lets you use create reusable custom components, plus a lot more. Express is an excellent webserver for Node.js that provides routing, middleware, and sessions. Incidentally, the two work quite well together! In this tutorial, I'm going to walk through writing a simple blog app with Angular and Express. If you'd rather skip to the end and see the finished product, you can grab the finished product from Github, or take a look at a live demo here. Anatomy of the App This application is really divided into two parts: client, and server.
Getting the Angular Express Seed To kick start the process of writing an AngularJS app, I've created the Angular Express Seed, based on the Express web server (which runs on Node.js) and the Angular Seed. or download it as a zip. λ → npm install λ → node app.js <! Conclusion. Climb That Mountain: JavaScript Testing with Mocha.
JavaScript is a neat and powerful language. Sure it has its flaws, but serious software can be developed with it. The way I prefer developing JavaScript applications is by test driving the code with some kind of testing tool. And I am not thinking about hitting the browser's refresh button. No, I mean executing the specs right in the terminal. I recently started playing with Visionmedia's mocha testing framework. The code is well maintained and the authors are responding fairly fast to pull requests or issues. I would recommend it as an alternative to Jasmine. This blog post will show you the first couple of steps you need to take to test drive your JavaScript code with mocha in the CLI.
First of all, you need node.js to run JavaScript code in the terminal. At the time of this writing my current node version is 0.6.6. Next you need node's package management tool (npm). With these two steps you're ready to roll. Curl -L | sh ✔ 1 tests complete (1ms) Enjoy! Sur la route d'Oxiane » Blog Archive Application AngularJS avec Yeoman, Express et JewelryBox sous Mac OS X. Yeoman a été créé dans l’optique de faciliter l’initialisation de web apps JavaScript, en regroupant un ensemble de 3 utilitaires tournant sous Node.js : Yo : initialise la structure de la web app.Grunt : déclenche les phases de test, preview et build de la web app.Bower : assure la gestion des dépendances. Express est un framework d’application web fonctionnant lui aussi sous Node.js.
Lorsque l’on génère le squelette d’une web app angular, Yo propose de gérer le design avec Twitter Bootstrap et des feuilles de style SASS. Les feuilles de style SASS, bien que très pratiques, doivent être compilées en CSS. Un framework open-source Ruby fait ça très bien et se nomme Compass. Ruby est installé par défaut sous OS X, mais il est préférable, comme sous d’autres OS d’avoir recours à RVM, un outil en ligne de commande qui installe, gère et permet de travailler facilement avec plusieurs environnements Ruby différents. Mise à jour de XCode Installation de JewerlyBox Installation de Compass. CoffeeScript vs. TypeScript by Paul Oliver on Prezi. Popline - An HTML5 Rich-Text-Editor Toolbar. React | Why did we build React?
There are a lot of JavaScript MVC frameworks out there. Why did we build React and why would you want to use it? React isn't an MVC framework. # React is a library for building composable user interfaces. It encourages the creation of reusable UI components which present data that changes over time. React doesn't use templates Traditionally, web application UIs are built using templates or HTML directives.
React approaches building user interfaces differently by breaking them into components. JavaScript is a flexible, powerful programming language with the ability to build abstractions. We've also created JSX, an optional syntax extension, in case you prefer the readability of HTML to raw JavaScript. Reactive updates are dead simple React really shines when your data changes over time. In a traditional JavaScript application, you need to look at what data changed and imperatively make changes to the DOM to keep it up-to-date.
React takes a different approach. HTML is just the beginning. Popline - An HTML5 Rich-Text-Editor Toolbar. A plain english guide to JavaScript prototypes - Sebastian's Blog. When I first started learning about JavaScript object model my reaction was of horror and disbelief. I was totally puzzled by its prototype nature as it was my first encounter with a prototype based language. I didn’t help that JavaScript has a unique take on prototypes as it adds the concept of function constructors. I bet that many of you have had similar experience. But as I used JavaScript more I didn’t just learn to understand its object model but also started love parts of it. Thanks to JavaScript I have find out the elegance and flexibility of prototypes languages. I am now quite fond of prototype languages because they have a simpler and more flexible object model than class based languages.
Prototypes in Javascript Most guides / tutorials start explaining JavaScript objects by going directly to ‘constructor functions’, I think this is a mistake, as they introduce a fairly complex concept early on making Javascript look difficult and confusing from the start. The __proto__ object. Drive SDK: New Undo feature for the Realtime API. 01-core.js. TraceGL.
Airbnb/javascript. Infinity.js. A ListView is a container that moves content in and out of the DOM on the scroll event. ListViews help keep repaint times of expensive pages down (and scrolling smooth) by making sure that there are never too many elements onscreen at a single time. ListViews excel at speeding up long lists of complex HTML elements, where new content is frequently appended to the end and existing content is rarely removed. ListViews are simple, and have several caveats: they can't be nested inside each other, and they can't have heights set via CSS. Additionally, ListViews can't easily change sizes except by appending or removing elements, and so list items that need to slide open or change their sizing will be difficult to implement.
Our First Node.js App: Backbone on the Client and Server. Here at Airbnb, we’ve been looking curiously at Node.js for a long time now. We’ve used it for odds and ends, such as the build process for some of our libraries, but we hadn’t built anything production-scale. Until now. The Problem There’s a disconnect in the way we build rich web apps these days. In order to provide a snappy, fluid UI, more and more of the application logic is moving to the client. In some cases, this promotes a nice, clean separation of concerns, with the server merely being a set of JSON endpoints and a place to host static files. This is the approach we’ve taken recently, using Backbone.js + Rails.
But all too often, it’s not so clean; application logic is somewhat arbitrarily split between client and server, or in some cases needs to be duplicated on both sides. If you’ve seen my tech talk or last blog post, then all this should sound familiar. Our Solution I’m proud to announce that we’ve launched our first Holy Grail app into production! Gimme the Deets! Views. Location.hash is dead. Long live HTML5 pushState! For a long time, location.hash was a way for AJAX applications to get back button and bookmarking support, and libraries like jQuery BBQ from Ben Alman made dealing with it cross browser a cinch.
Now, with HTML5 coming of age, there is a new feature that aims to replace the use of location.hash with a better solution: pushState. Over on the Spoiled Milk blog, Jamie Appleseed describes the API as “a way to change the URL displayed in the browser through JavaScript without reloading the page.” It works on the history object like this: window.history.pushState(data, "Title", "/new-url"); The last argument is the new URL. In order to support the back and forward buttons you must be notified when they are clicked. Currently, pushState has support from the latest versions of Safari and Chrome, and Firefox 4 will be supporting it as well. If you’d like to read a more in depth overview of these new features, you should check out the aforementioned blog post by Jamie Appleseed.
Demander confirmation à la fermeture d’un onglet en javascript. Votre utilisateur est en train d’écrire un commentaire, upload un ficher ou fait un truc quelconque qui n’est pas terminé. Puis il clique sur “fermer l’onglet”. Dans certains cas, vous voulez lui demander confirmation pour éviter qu’il perde tout son travail. var confirmOnLeave = function(msg) { window.onbeforeunload = function (e) { e = e || window.event; msg = msg || ''; // For IE and Firefox if (e) {e.returnValue = msg;} // For Chrome and Safari return msg; }; }; // message de confirmation générique du navigateur confirmOnLeave(); // message de confirmation personnalisé confirmOnLeave('Vous allez perdre votre travail, êtes vous sûr(e) de vouloir quitter la page ? '); Quand vous appelez la fonction confirmOnLeave(), le callback de l’événement ‘onbeforeunload’ va être remplacé par une nouvelle fonction. Vous pouvez appeler cette fonction n’importe quand, l’événement ne se déclenche que quand l’utilisateur quitte la page de toute façon.
La navigateur va réagir ainsi: No related posts. Making Use of jQuery UI’s Widget Factory. For a long time, the only way to write custom controls in jQuery was to extend the $.fn namespace. This works well for simple widgets, however, as you start building more stateful widgets, it quickly becomes cumbersome. To aid in the process of building widgets, the jQuery UI team introduced the Widget Factory, which removes most of the boilerplate that is typically associated with managing a widget. The widget factory, part of the jQuery UI Core, provides an object-oriented way to manage the lifecycle of a widget.
These lifecycle activities include: Creating and destroying a widgetChanging widget options Making "super" calls in subclassed widgetsEvent notifications Let's explore this API, as we build a simple bullet chart widget. The Bullet Chart Widget Before we build this widget, let's understand some of the building blocks of the widget. The chart consists of a set of bars and markers overlaid on each other to indicate relative performance. The HTML for this chart looks like so: Summary. A Few New Things Coming To JavaScript. I believe the day-to-day practice of writing JavaScript is going to change dramatically for the better when ECMAScript.next arrives.
The coming year is going to be an exciting time for developers as features proposed or finalised for the next versions of the language start to become more widely available. In this post, I will review some of the features I'm personally looking forward to landing and being used in 2013 and beyond. ES.next implementation status Be sure to look at Juriy Zaytsev's ECMAScript 6 compatibility table, Mozilla's ES6 status page as well as the bleeding edge versions of modern browsers (e.g Chrome Canary, Firefox Aurora) to find out what ES.next features are available to play with right now.
In Canary, remember that to enable all of the latest JavaScript experiments you should navigate to chrome:flags and use the 'Enable Experimental JavaScript' option. Modules We're used to separating our code into manageable blocks of functionality. We can just import drive(): Maps Sets. AngularJS and SEO. Turns out it is possible to have your AngularJS application indexed AngularJS and just about all JavaScript MVC frameworks modify the contents of your HTML structure which make the pre-rendered HTML invalid for search engines. Luckily there is a way to get around this and to have full SEO support for your AngularJS application by using some special URL routing and a headless browser to retrieve the HTML for you.
Continue reading this article to figure out how to make this amazing framework work well with your favourite search engines. This page was first published on November 7th 2012 and was last updated on January 21st 2013. To best follow along with this article, be sure to clone the repo, yearofmoo/AngularJS-SEO-Article and look through the code and compare it to what's on the blog to get a better idea of how everything works. Git clone cd . . Truly amazing! Airbnb/javascript. Plupload - A tool for uploading files using Flash, Silverlight, Google Gears, HTML5 or Browserplus. Désactiver le WiFi de la Freebox à certaines heures | Armetiz. Flip Clock. ෴ browserver: a node.js HTTP server in your browser ෴ Twitter Bootstrap Notifications, from Nijiko Yonskai. Le Programmeur Moderne - Le JavaScript moderne. Chroniques jQuery, billet 71. Datavisualization.ch Selected Tools.
Google JavaScript Style Guide. Closures: Front to Back.
3D in Apps Script.