Programming large scripts in javascript using object orientated style coding

November 12, 2010    object orientated javascript

This week whilst coding a large javascript / jQuery script for one of our online games which started to grow to an unmanageable size and needed to be compartmentalized I decided to review my techniques.

Previously for scripts which were quite large I would create an object which contained lots of different methods like so. As you should already know in js its all about scope.

So here's what I used to do:

function page(){
this.funcName = function(param){
alert("hey man this is a cool little function);
}
}

I'd then go and call this function into the page like so.


var mypage = null;
function init(){
mypage = new page();
}

$(document).ready(function(){
init();
});

Which then gives you full access to call objects of page via access of the mypage var.

This works fine, but meant that all of my code was inside one very big ass object. Not so great. 2000 lines later, even less great. 2000 lines later and finding out I need to use aspects of it for one page and not another, awful.

So I set out to find a change in practise and this is what I came up with. This is not a new technique, nor do I personally claim I came up with it. Just my take on things I read.

My new plan was to create a base script, which was then interfaced by several smaller scripts dependant on the view.


Post={
newmsg: function(){
alert("hey there man, how goes it?");
}
};
pgAjax={
request: function(options){
//could add some extension of the defaults for a jquery ajax call here
}
}

Hopefully from the above you can start to see its benefits. By compartmentalising it, I made it much easier for me to keep code housed in segments, the objects can also be called via inline commands like onclick="Posts.newmsg();"

I interface the base with a series of smaller files based on the view, similar to this.

leadview.js
$(function(){
$("input[type='button']").click(function(){
Posts.newmsg();
});
});

Obviously this is massively simplified, hopefully this might help though. Feel free to leave a comment if you wish for me to expand on this.


blog comments powered by Disqus