avatar

Michaël Duerinckx

 

Posts Tagged ‘JavaScript’

Event-driven JavaScript: a simple event dispatcher

One of the more valuable lessons that I’ve learned in the years I’ve been programming is that loose coupling will make your life better. A very good way to achieve loose coupling in your projects is by dividing functionality in self-sufficient modules that communicate merely by subscribing to and triggering events. To work with these events, you need one component that is relatively tightly coupled with all your modules. This little bit of coupling is definitely worth it though.

Before diving into specifics, let’s talk about just what I mean.

Loose coupling

When the code base for a project gets sizeable, one thing that can make it a nightmare to work with is tight coupling. When modules are tightly coupled in a project, it means that changing one method in module A may require you to change the way certain things are implemented in module D, F and G. In order to make any modifications, you need to be well aware of how other modules rely on the module you wish to modify.

Since having a single module in your head can be taxing enough for the mind, considering basically the whole project when making a local change is awful; oversights are bound to occur.

To ensure you do not need to wrap your head around the entire code base at all time, you’ll want to make sure your modules are loosely coupled. You can safely change the modules’ internals without having to worry about how other modules have to interact with this module. You need to consciously engineer your modules to be entirely agnostic of the inner workings of others.

You’ll find that employing this method makes it much less of a daunting task to change some functionality around.

Bring on event-driven programming

Event-driven programming is a fairly simple pattern where component subscribe to events and trigger them. A variant of the pattern is the observer pattern; the difference however lies in where the event dispatching happens.

In an observer pattern, you can register observers (subscribers) to event a certain module emits. This way you can subscribe to, for example, an after-save event, which is emitted every time an object’s data is saved. The observer subscribing to this event will be triggered every time that happens, and a function can then be run.

In this case, we move the subscribing facilities away from the modules to a dedicated event dispatcher module. This provides one central location where modules sign up to be notified when a certain event occurs, as well as where modules go to broadcast an event they want to make the application aware of.

Doing this, all each module is concerned with if it comes to communicating with the rest of the application is 2 uniform things: Emitting events and responding to events emitted elsewhere. The modules do their thing, throw out some information whenever there is something that may concern the rest of the application, and they remain alert for external events pertaining to the module in question.

Responsibilities of the event dispatcher

The event dispatcher module that drives this whole pattern has only few responsibilities:

  • Keeping track of event subscriptions
  • Dispatching incoming events to all the subscribers of that event

(more…)

JavaScript forEach Object, Array and String

In many programming languages, you have a simple for each construct available to quickly go over the contents of just about anything iterable. In JavaScript it isn’t so straightforward. To rectify this, I’ve written up a function that provides a single interface to iterate over the elements of an array, the values in an object, and “even” the characters in a string.

It works with a callback function that takes index/key and value as parameters. This callback function is executed for every item in the collection passed.

The benefit of using this is that you have very readable code; most programmers will intuitively know how it works because of the familiar collection, index and value interface.

To the code!


(more…)

Selectbox / dropdown replacements

The <select> element is hard to style properly and is something that easily ruins sleek designs. Many people have already realised this, which is why there are a couple of JavaScript replacements out there.

Here’s a quick list of those that I’m aware of—in no particular order.

This post is mostly as a reference, so I don’t need to look up all the options (no pun intended) every time this situation arises. I hope it can help you quickly select (pun definitely intended this time) which one’s best for you.

Update 05 April 2014: Removed “jQuery SelectBox plugin” as both links had died.

Minecraft design tool

TL;DR: I made this thing: Minecraft design tool

My girlfriend bought me the ever-so-popular indie game ‘Minecraft’ for my birthday, even though I kept saying I would never play it. I tend to get obsessive over certain thing; mostly things that involve creating, building, which is all Minecraft is about. After having seen her play it for quite a while however, I decided to give it a go anyway, as it looked like far too much fun to be left alone. As expected, I did start to obsess over it, once I got everything down properly (which was rather soon since the game is really easy to play).

Since Minecraft also has a multiplayer mode, my girlfriend and I were soon playing together in our own virtual world. After a while we started building things together, which was and still is endless fun. However, when you just explain your idea of what you want to build, there sometimes is a bit of miscommunication, and one or the other starts building things in a way that wasn’t intended, because they misunderstood. Needless to say, this happened a couple of times, with mutual frustration as a result.

A simple drawing on a grid can greatly help explain what you mean, I thought; thus, I got to work. I decided to quickly throw together a tool that lets you draw things in 2D, with Minecraft material sprites. I built it with the tools I’m most experienced with; namely HTML, CSS and JavaScript.

ScreenshotThe tool simply uses a table as its grid. I realize that a drawing isn’t quite tabular data,  but it seemed the best way to go for it. Since I used HTML5 to make it, I know I could just have used the <canvas> tag, but I’m afraid I don’t have quite enough experience with that one to build something with it quickly—which was mostly the goal here. That and the fact that canvas is one of the things that can’t really be used in older browsers, so it would effectively NOT work there, made me decide to use a table.

I kept the tool very simple and to the point, because all I really wanted was a quick design tool that let you share your designs with others. It isn’t quite the prettiest as it is, but it’s functional, and that’s what matters… to me, at least.

The first version I put up did not have a save button, as it was pure HTML, CSS and JavaScript. To share a design, you had to use the export function, paste the exported data (which is in JSON-format, for those interested), copy the output to your Minecraft partner(s), and have them import it again. Since this is a rather tedious way of sharing designs, I built the PHP part later, which saves a design under an 8-character ID. This way, you can just copy an url the conventional way, and the design will be loaded straight away. For those who still have an exported design sitting around somewhere, you can still import it and save it online.

Seeing as there is no account system or anything, you can’t save to the same ID; you always save to a new one. This prevents people from vandalizing others’ designs. (Or griefing, if you prefer the popular Minecraft term).

Future ideas

Since I made a PHP part for it, I’m planning to expand on that. One nice idea I have is to build an actual image generator; PHP would simply combine the sprites into a single image and make it available for download as a PNG.

Another handy feature would be to have a little list of latest designs, so you don’t need to bookmark everything. I might use a cookie to have a list of the latest designs you made, which makes it easier to find your own designs, rather than just the latest few. I’ll keep you updated.

JavaScript: getChildNodesByTagName()

If you’ve ever used JavaScript’s getElementsByTagName(), you may have noticed something annoying about its behaviour. (Well, it’s only annoying depending on your application.)

getElementsByTagName returns every element matching the tag name given, regardless of its position in the document tree. This is annoying if you only want to use the elements that are direct descendants of the element you’re calling it from.

So anyway, to cut this short, I wrote  a quick but effective function that works just the same as getElementsByTagName, with the difference that it only returns direct descendants. Just add in this snippet of code and you can start using the function just as you would use getElementsByTagName.

Object.prototype.getChildNodesByTagName = function (tagName) {
    var byTagName = this.getElementsByTagName(tagName);
    var outArr = [];
    for(a=0;a<byTagName.length;a++) {
        if(byTagName[a].parentNode == this) {
            outArr[outArr.length] = byTagName[a];
        }
    }
    return outArr;
}

Here’s how it works:
The function uses the typical getElementsByTagName, and then iterates over all the elements found. For each element it checks whether the element’s parentNode equals this, which is the node that should be the parent of any elements we want to return.
When the comparison is positive, the element is added to the array, which is later returned.

I hope you can put it to good use!

Leave me a comment if this was helpful to you, or if there’s anything wrong, please.