PubSub in Javascript

If you’re working on a large app, it’s important that all your system remains flexible. Nothing is worse than coding yourself into a corner. One of my favorite Javascript design patterns is PubSub. Go ahead and say that out loud a few times. It’s got a nice flow to it doesn’t it?

Intro

PubSub, which is short of Publish Subscribe (which is not nearly as fun to say), is a way of “decoupling” your code. Basically one method publishes, messages such as objects, and another method subscribes to it. It’s beauty is in it’s simplicity.

“In software engineering, coupling or dependency is the degree to which each program module relies on each one of the other modules.”- Wikipedia

Try to avoid coupling in your Javascript applications. PubSub lets you send whatever message you wish to whatever listening, without having to sorry about scope. (The communication flow reminds me of an old fashioned radio broadcast).

pub("dance", "hustle");

var danceVar = sub('symbolMethod', function(obj) {
	if (obj === "hustle") alert ("Do the hustle!");
});

Whenever you broadcast on the “dance” channel, whatever is subscribed to that will receive it.

broadcast = (function() {  
    var topics = {};
    return {
        sub: function(topic, listener) {
            if (!topics[topic]) topics[topic] = {
                queue: []
            };
            var index = topics[topic].queue.push(listener) - 1;
            return {
                remove: function() {
                    delete topics[topic].queue[index];
                }
            }
        },
        pub: function(topic, info) {
            if (!topics[topic] || !topics[topic].queue.length) return;

            var items = topics[topic].queue;
            items.forEach(function(item) {
                item(info || {});
            });
        }
    };
})();

Is this like DOM events?

Similar in concept, but different. PubSub is similar in that it’s an action triggered by an event, but has nothing to do with the DOM or event methods. This makes it an extremely useful pattern if you’re working without a DOM like with Node.

More Recourses

There are a TON of PubSub libraries out there. I think it’s faster to write my own than to learn someone else’s library. But if you want more features, you have many to choose from.

For more Pub Sub, David Walsh has a great article here

If you have a half hour, …

Read More»

The Module Pattern

The great thing about JavaScript is you can make up your own structure. The awful thing about JavaScript is everyone makes up their own structure. (kidding).

One my my favorite design patterns for keeping things organized is what’s called the “Module Pattern”. I’m a fan of keeping things as simple as possible, and the Module Pattern let’s you write very clean, decoupled code, without over complicating things.

Creating a Module

Creating a Module begins with an IIFE or an immediately-invoked functional expression. It’s basically a function wrapped in an extra paren which lets the function execute itself. This is known as a function expression. Everything that happens inside of it are kept private from the parent scope. I’ll explain why thats awesome in a minute.

// an IIFE
(function(){
	// code
})()

To declare it as a module, simply give it a name space like this:

// a module function
var awesomeModule = (function(){
	// code
})()

Privacy

One of the fantastic things about the Module pattern is how easy it is to implement privacy in you object. Privacy basically means that what happens in your object, stays in your object, unless told otherwise.

var awesomeModule = (function(){
	var thisVar = "foo";
	function _privateMethod (){
		// code
	}
	return {
		var publicMethod = function(){
			return thisVar;
		}
	}
})()


alert(thisVar) // undefined
alert (awesomeModule.pubicMethod()) // foo

In the example above thisVar is not exposed outside of awesomeModule until the publicMethod() is ran. It’s encapsulated within the object, making it a Private variable.

Historically Javascript has not been given the same respect as some other languages associated with object-oriented programming. But when used properly, such as taking advantage of encapsulation, Javascript can be just as powerful as it’s peers.

The Module Pattern in Practice

I use the Module Pattern whenever I have data I don’t want to directly expose (such as values within a game). Traditionally encapsulation is synonymous with security but on client side Javascript everything you have to be careful what you calculate on the browser. In a more secure environment (like on a server), the security …

Read More»

WordPress allows for “status” posts. My “status” with WordPress: It’s complicated. …