Tuesday, June 12, 2007

A bit more javascript

Actually this little snippet sums up quite a bit of what I am doing these days...

function ensure_package(package_name, package_block) {
var package_parts = package_name.split(".");
var package_so_far = this;
for(var i=0; i<package_parts.length; i++) {
var package_part = package_parts[i];
if( ! package_so_far[ package_part ] ) {
package_so_far[ package_part ] = {};
}
package_so_far = package_so_far[ package_part ];
}
if( package_block ) {
package_block( package_so_far );
}
return package_so_far;
}


The above function ensures that there is a 'package' (global variable) with the path specified by package_name.

It returns the package ready to add some objects or functions to, or you can even pass in a function that receives the package as a parameter.

The following demonstrates some tests/usage of the above function


ensure_package("tiest");
tiest.id = 89
ensure_package("tiest");
alert( tiest.id );

ensure_package("tiest.vilee");
tiest.vilee.rocks = true;
ensure_package("tiest.vilee", function(public_interface) {

var private_interface = {};
private_interface.private_method = function() {
return 'private method';
}

public_interface.public_method = function() {
return 'public method:' + private_interface.private_method();
}
});
alert( tiest.vilee.rocks + ' ' + tiest.vilee.public_method() );


I really like to use packages to namespace my stuff, and I really like to use the public/private objects within my object definition bit to differentiate between the different function/variable types. Makes it all very clear and easy to read. Now if only javascript weren't so verbose....

0 Comments:

Post a Comment

<< Home