Single Page Application from scratch. Part 1: Simple Event Emitter on JavaScript

I am .Net developer for more than 4 years, I was working with almost all aspects of .Net development from Console applications to Web, Windows Phone, WPF, WWF and services. And all that time I was bad in JavaScript. Only a few days ago I understand that I need to change it as too many interesting things currently happen around Web.

This will be my first blog from the series in which I will build MVC like Single Page Application (SPA) from scratch using native JavaScript, HTML 5 and CSS.

I will start from building basic blocks and discussing architecture after that I will gather it all and push to the GitHub. As I already mentioned my application will be based on MVC pattern, and will contain three main layers, lets start from the first one

View layer

Each view(html page or part of the page) will have it’s own javascript which will be responsible for manipulation with UI, show/hide elements, handle buttons and links, selection changes and updating UI in general. BUT it will be as simple as possible for example when User clicks LogIn button our javascript will only fire up this event and Controller will be responsible for handling it, at the same time our View doesn’t know anything about controller.

Controller

Controller in our case will be responsible for handling events from UI(our UI javascript) and calling events on UI. So it will know a lot about Views also it will implement some basic validation logic.

Model

Model in our case is the simplest part as it should be. It’s just simple objects that store information.

By now it’s enough, now lets build something basic that will be the core of our application, Event Emitter. Main responsibility is to be the single point of communication between main parts(View and Controller) of our application.

As I want to develop application in a few iterations, our Event Emitter will be just a few methods in html file that allow us to subscribe for some event and rise it. In the future we will update it and do it as it should be.

Here is how the final page should look like:

image

and here is the code:

<!DOCTYPE html>
<html>

<head>
 <title>Even Emitter Demo</title>
</head>

<body>
 <div>
 <h1>Simple Event Emitter on JavaScript</h1>
 <button type="submit">Subscribe</button>
 <button type="submit">Execute</button>
 </div>
</body>

</html>

Yes it simple by now.

var _events = {};

var onEvent = function (eventName, fn, ctx){
	if (typeof _events[eventName] === &quot;undefined&quot;)
	{
		_events[eventName] = [];
	}

	_events[eventName].push(
	{
		fn : fn,
		ctx : ctx || window
	});
};

This small js code is responsible for our subscribing for an event. var _events, from a start creates empty object that will be used to store our events and their subscribers. Function onEvent just checks if _events object has an variable called as the data that come to us in variable from outer space, if it doesn’t than it creates one, if we have some array with the name that is in eventName than it just add to it new object which has method that it should call, and context.

If you don’t understand how it might work you should go and check really cool course on http://www.codecademy.com/tracks/javascript , it gives nice understanding how javascript works.

Next method is rising events:

var emitEvent = function(eventName, data)
{
	if (typeof _events[eventName] !== undefined)
	{
		for(var i = 0; i &lt; _events[eventName].length; i++) {
				_events[eventName][i].fn.call(_events[eventName][i].ctx, i);
		};
	}
};

It’s even simpler than previous one. Here we just check if we have such kind of event in our _events variable, and if we have we one by one extracting objects that were added to collection. From that objects we get all the information we need, method and context in which it should be executed. By the way I have used call method, as it allows us to execute method with custom scope, here is more information about method itself: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

Final version of the page should look like follows:

<!DOCTYPE html>
<html>

<head>
 <title>Even Emitter Demo</title>
</head>

<body>
 <div>
 <h1>Simple Event Emitter on JavaScript</h1>
 <button type="submit" ionclick="subscribe()">Subscribe</button>

 <button type="submit" onclick="execute()">Execute</button>
 </div>
</body>
<script type="text/javascript">

var _events = {};

var onEvent = function (eventName, fn, ctx){
 if (typeof _events[eventName] === "undefined")
 {
 _events[eventName] = [];
 }

 _events[eventName].push(
 {
 fn : fn,
 ctx : ctx || window
 });
};

var emitEvent = function(eventName, data)
{
 if (typeof _events[eventName] !== undefined)
 {
 for(var i = 0; i < _events[eventName].length; i++) {
 _events[eventName][i].fn.call(_events[eventName][i].ctx, i);
 };
 }
};

var subscribe = function(){
 onEvent("send", function(data){
 console.log("Subscribed " + data);
 })
}

var execute = function(){
 emitEvent("send");
}

</script>
</html>

I have added two more method just to call the our event emitter methods, and bind it to buttons.

Every time you press “Subscribe” button method will be added to the list of subscribers and every time when you press execute all the methods that have subscribed to event will be executed. in our case it’s anonymous method which prints to the Developers Console.

image

Next post will be about inheritance and how to organize it in JavaScript.

Cheers

Advertisements

One thought on “Single Page Application from scratch. Part 1: Simple Event Emitter on JavaScript

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s