JavaScript: The Module Pattern
May 28, 2008
I had a question from one of my coworkers a few weeks back about some basic OO techniques in JavaScript. Seeing as this is a key question from most people getting into JS from a classical OO background I thought I might just share a powerful little concept called the “Module Pattern” to get you all started.
The module pattern (first identified by Douglas Crockford) exploits the fact that JS only has one kind of scope: function scope. Forget blocks, or any other kind of scope resoultion techniques you might know from other programming languages – it ain’t here. JS allows you create functions within functions (i.e. nest them), and hence function scope is also nested. Any nested function can see anything in the parent function and so on up the tree. It does this through the use of closures which is far to big a topic for this short article, you’ll just have to accept the fact that it works.
Okay so why is this important? Well JS has a major flaw (some would say feature) in that it doesn’t have any sort of PPP (public, private, protected) functionality. Everything is public. Everything. So how do we achieve any sort of meaningful encapsulation you ask? Isn’t information hiding critical to the design principle “open for extension, closed for modification”? Well the module pattern is one solution to this problem.
Here’s how it works:
MyObject = function() {
var myPrivateField;
function myPrivateMethod(someValue) {
// look ma I'm a closure
myPrivateField = someValue;
// assigning a private member to a public one
pub.myPublicField = myPrivateField;
return "I'm a private method";
}
/*
* this is where we define the object's public
* interface using another bit of JS
* magic: the object literal
*/
var pub = {
myPublicField: null,
myPublicMethod: function() {
return "Hello World!";
},
myPrivateMethodWrapper: function(someValue) {
// calling a private/hidden method
return myPrivateMethod(someValue);
}
}
// here we override the constructor's return value
// with our public interface object
return pub;
}
var o = new MyObject();
o.myPrivateMethod(); // wont work it's private/hidden
o.myPublicMethod(); // works!
I know that this will completely weird out some of you OO purists, but when JS is the only thing you’ve got (e.g. in the browser) it’s a pretty useful technique for gaining some sort of PPP control over your objects API.
Ever wondered how Gmail/Facebook chat works?
May 28, 2008
Web based IM clients are seem to be the flavour of the month at the moment. Gmail has had one for a little while now and more recently Facebook has added this to their already impressive stable of features. These are really cool, and rip all over the old form based chat rooms, but how do they do it without using any plugins, flash or the dreaded ActiveX componets?
Typically they use a combination of things:
Server
At the heart of the system is a Jabber IM server such as Openfire. The server performs real-time communications with clients via the Extensible Messaging and Presence Protocol (XMPP). XMPP is an open XML based protocol that works on a concept similar to email. That is, anyone with a server open to the internet can create a Jabber IM server and become part of the wider decentralized IM network.
It’s worth noting that XMPP places no restrictions whatsoever on what the client should be. Much of the effort and complexity of developing a Jabber IM network goes into the server itself. Given that there are already a number of perfectly good OSS Jabber servers out there it makes the Web Developers job relatively easy.
Client
Gmail and Facebook use clients written in JavaScript (no plugins!) which communicates can communicate either directly with the server, or via a server-side proxy. There are generally two accepted methods communicating with the server from the browser; HTTP binding (BOSH) or HTTP polling (now deprecated).
Binding universally preferred as it virtually eliminates the number of round trips to the server (the majority of which yield no result) by using keep-alives to hold connections open to the server. What does that all mean? It means that the Jabber server is able to push messages back down to the browser rather than the client checking at set intervals for new messages. Cool huh? The only drawback seems to be that you need to be able to manage a large number of open connections concurrently. The fact that Openfire is built on Jetty helps because of their use of the Continuation Pattern to suspend blocked polling requests and free the worker thread.
Going direct
Communicating with the jabber server directly saves a lot a lot of hassle as opposed to proxying the requests via a servlet or something similar. It also avoids the problem of having to move your existing web server over to something more scalable like Jetty. But how do you do this when JavaScript can only make requests to its own domain? Well if you’re using Apache you’re in luck! Mod_rewrite is your friend here and adding the following to your http.conf file should have to talking to your Jabber servers http-bind service in no time at all:
<VirtualHost *:80>
Servername yourdomain.com
DocumentRoot /var/www
AddDefaultCharset UTF-8
RewriteEngine On
RewriteRule ^/http-bind/ http://jabber.yourdomain.com:5280/http-bind/ [P]
</VirtualHost>
Viola! All requests to http://www.yourdomain.com/http-bind/ will be automatically forwarded to your chat server.
Talking XMPP
Okay so we’ve solved the cross-domain request problem, but how to we talk to the server. You’re probably asking yourself “Do I now have to actually parse all those XML messages myself in JavaScript?”. Fortunately no. JSJaC is a freely available, washed in the blood open source GPL JavaScript library, that handles all those icky details for you. It works on an event based model so you can just register your event handler callback functions, and get on with writing your very own IM client.
Speaking of which I’m going to do just that right now!
Free File Hosting
May 26, 2008
Today I thought I’d put up a few Joomla! extensions that I’ve been working on over the past few days. I thought I could just upload them directly to wordpress but it I can only upload media stuff, if I want to post anything else I have to host them elsewhere. Given that my hosting arrangement has just expired and I’m not willing to renew it I set out to try find a free file hosting site.
As it turns out it was surprisingly easy to find a good one. For now I’ve got all my stuff being hosted by Media Fire which seems like a pretty sweet deal. They’ve got a really clean no fuss UI (sprinkled with just the right amount of AJAX to make things easier) and it’s all pretty straight forward. Nice work guys.
