avatar

Michaël Duerinckx

 

Posts Tagged ‘Coding’

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…)

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.

MVC – FuelPHP

Since I started working at Carswell Gould, I’ve learnt a lot more about web development—It’s amazing how much you learn once you start collaborating with other people—and among those things I learned is how to work with the MVC (Model-View-Controller) design pattern. The way I used to work was just by having the database operations inside classes as much as possible, and use those classes and their methods in the files for the actual pages. For example, A forum thread page (view.php or similar) would have all the code to load the posts and relevant info above the HTML part of the file, using classes like ForumThread and the like.

The MVC way to go for this would be having a controller that gets called when the URL for viewing a thread is requested. The controller would get an instance of a ForumThread Model. The Model describes the properties of a ForumThread and deals with related data (Forum posts, which would be another Model), and database operations, plus any additional behaviours. The data retrieved from the Model instance then gets passed on to a View, which takes care of sticking all the data in HTML. This way interpreting the request, dealing with data and displaying data is nicely separated.

Frameworks (FuelPHP)

This whole design pattern is all a very beautiful way to structure your web applications, however, if you have to set that all up from scratch, it would get very tiresome to get right. That’s where frameworks come in. The first PHP framework I got in touch with is FuelPHP, a quite young framework running on PHP 5.3+. According to their front page, it is based on the best ideas of other frameworks, with a fresh start. As this is the first framework I’ve used, I can’t really judge that former part, but by googling certain concepts used, I’ve found out that many of them are quite commonly accepted ones.

In my experience, it’s very simple to set up some new models and relate them, to quickly get going without all the design hassle you’d normally have. For the most part, you don’t get to write the database queries yourself, which is a good thing.

Validation

An unrelated part of FuelPHP (as in, it doesn’t really have anything to do with MVC) is its validation functionality. FuelPHP makes it really smooth to validate input. There are multiple ways to go for it, but my preferred way is to actually specify the validation rules in a Model’s properties array, then setting up a Validation Observer before save.

If that sounded confusing: An observer is a class that has a number of event-named methods. In a Model you can refer to an observer class and tell it which events to observe. FuelPHP takes care of the rest: When you let your model save its data to the database, any observers with ‘before_save’ enabled will be executed first. In the case of a Validation observer this will first run all the validation rules specified in the properties set-up, and throw an error (preventing the actual database save) in the case that some data does not validate.

Having gone through setting up a whole bunch of nested ifs for data validation in the past (Believe me, it’s tiresome and not elegant at all), I find this way of setting up validation simply beautiful. It’s all down to adding a few strings to an array, and it’ll validate. The way the framework is built allows for easy adding of your own validation functions too, so other than elegant, it’s very flexible.

Adopt FuelPHP!

Currently, the community surrounding FuelPHP is still fairly small, which means it’s often quite hard to google FuelPHP-related things. I would very much like the community for this framework to grow, as I feel it has a lot of potential. Their website (mostly docs section) is still quite incomplete in places, but that should improve as the community grows.

More information

I’ve only briefly touched upon many subjects in this post, so if I sparked your interest, these couple of links should get your started.

Obviously, if you are really interested in trying it out, I suggest downloading it and playing with it! You can get support on their forum and in their IRC channel.

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.