JavaScript Classes and Events

23 Jan

Every so often I like to check out Microjs and browse the micro frameworks for JavaScript. I always stumble upon something new and interesting. Most recently, I found chic.js – a class like interface – and minivents.js – a small event system.

I started by following the examples for each framework and had a class example and a button that triggered events. Neat, but nothing special. I remembered a design pattern called observer – read Learning JavaScript Design Patterns free online – and thought I could combine the two to implement this pattern.

I started by writing a class, and extending it with another. The parent class has three function: init, eat and sleep. The child class overrides init and inherits eat and sleep. The init function takes the minivents.js Event object as a parameter.

var Class = chic.Class;
var Animal = Class.extend({
init: function (eventSender) { = “I am a 22 year old Animal. I like toys and chasing my tail”;
this.eventSender.on(“talk”, function(){
eat: function () { return “yummy” },
sleep: function () { return “zzzzzzz” }

var Cat = Animal.extend({
init: function (eventSender) {
this.eventSender.on(“talk”, function(){alert(“MEOW!”);});}

Next, I hooked up each function to a button in HTML

<button onclick=”trigger()”>Trigger Event</button>
<button onclick=”e()”>Eat</button>
<button onclick=”s()”>Sleep</button>

function trigger(){changed.emit(“talk”);}
function e(){alert(“Fluffy says: “”\nPaws says: “;}
function s(){alert(“fluffy sleeps: “+fluffy.sleep()+”\nPaws sleeps: “+paws.sleep());}

Lastly, I created the Event object and two classes – passing the Event object to them.

var changed = new Events();
var fluffy = new Animal(changed);
var paws= new Cat(changed);

When an event is triggered, each animal responds differently. I do not need to tell them to respond, nor do I need to keep track of how many objects. When I call eat or sleep, I have to tell each object to do so – With the observer pattern, the objects react on their own. The observer pattern is similar to the Pub/Sub pattern.

As your applications become more advanced, you may find yourself implementing existing patterns without even knowing. The patterns exist for a reason – they are the best solution to a common problem. I will spend more time this year learning design patterns.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: