<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title> &#187; Javascript</title>
	<atom:link href="http://www.anzaan.com/category/software-development/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.anzaan.com</link>
	<description></description>
	<lastBuildDate>Sat, 26 Jun 2010 03:29:01 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Javascript variable scope, private protected and public</title>
		<link>http://www.anzaan.com/2009/05/javascript-variable-scope-private-protected-and-public/</link>
		<comments>http://www.anzaan.com/2009/05/javascript-variable-scope-private-protected-and-public/#comments</comments>
		<pubDate>Wed, 27 May 2009 13:30:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[front end]]></category>
		<category><![CDATA[closure]]></category>
		<category><![CDATA[javascript varaible scope]]></category>
		<category><![CDATA[module pattern]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=77</guid>
		<description><![CDATA[Private ,public and protected/privileged access of variables and functions in javascript]]></description>
			<content:encoded><![CDATA[<p>Javascript is a tricky language. Since I learned programming with Java, I always find myself trying to find its equivalence in other languages I come across.</p>
<p>I know its bad in that in that it kind of stops me from exploring the potentials provided by other languages in full. Its like going to a Chinese restaurant and eating fried rice everytime because fried rice is the only dish that is close to what I&#8217;m used to eating daily.<br />
There&#8217;s such variety in Chinese food, and yet if I go there and I eat fried-rice evertyime Its a sign I have a bit of a problem opening myself up to new things. And that&#8217;s a big problem.</p>
<p>The world has such diversity in every-aspect imaginable, ( with the exception of mob-justice and mob-mentality which seem to cross all cultural and geographical boundary as it seems), and not being able to appreciate the diversity and learn for it is a great pity.</p>
<p>Back to programming, not all constructs  found in languages are sole property of a  given language. They are  generally abstractions provided by languages to solve problems effectively and those abstractions can be applied in other languages even if they don&#8217;t provide such explicit constructs.</p>
<p>There was a time when I treated javascript like lepers, something to avoid at all cost, except when it was really unavoidable.<br />
But then I had a change of perspective, at a philosophical level -dare I day. &#8216;If I avoid something to such length then I must be shit-scared of it for some reason&#8217;.<br />
And by nature I hate to admit my fears for the fear of being tagged a wussy, a chicken.<br />
Of course I can find things to justify my avoidance of javascript to others without admitting my fear, but how about myself?<br />
What do I tell myself when I go to sleep??<br />
And since I couldn&#8217;t find reasonable arguments to fool myself into good sleep because my rational self always counter-argued that &#8216;you  fear what you don&#8217;t understand&#8217;, and  my arguments against javascript were just my lame attempt to hide my fears , I decided to deal with my fears for once and for good.</p>
<p>And since then I have been quite happy with my javascript experience.</p>
<p>Since I&#8217;m still a Java fan-boy, though I have a feeling that it won&#8217;t be for  too long, Scala! here I come,  I tried to find solution to variable scoping in javascript so that I have more control over objects I create and the API&#8217;s I expose. This has been a big issue due to the need for me to use at least 3-4 third-party libraries to get my job done for the current project I&#8217;m rewriting.<br />
And the project has a massive javascript code-base.</p>
<p>Looking back at the code I did last year makes me cringe. There was no modularity and there was too much interdependency between components and objects.</p>
<p>(Hmm&#8230; component decoupling is entirely another topic for another sleepless night.)</p>
<p>And this time around I decided to do thing the right way &#8211; at least to my best knowledge.</p>
<p>After long hours prowling the internet, finally I managed to understand the trick to accomplish what I wanted.</p>
<p>So here&#8217;s an example of an object with everything pubic, the dumbest example.</p>
<pre class="brush: javascript;">

var Person= function(name ,surname, sex, dob){

this.name=name;
this.surname=surname;
this.sex=sex;
this.dob=dob;

this.getFullName=function(){

return this.surname+&quot;,&quot;+this.name;
}

this.getAge=function(){

return (new Date().getYear() - this.dob.getYear()) ) ;// I'm being lazy here

}

}

// another a little less dumb-looking flavor with prototyping but dumb nonetheless
var Person= function(name ,surname, sex, dob){

this.name=name;
this.surname=surname;
this.sex=sex;
this.dob=dob;
}

Person.prototype.getFullName=function(){
return this.surname+&quot;,&quot;+this.name;
}
Person.prototype.getAge=function(){
return (new Date().getYear() - this.dob.getYear()) ) ;
}
</pre>
<p>All the properties in of the object are accessible to any function/code that instantiates Person object. And getFullName() is nothing more but a handy method for getting both name and surname.<br />
And the calling code can access dob and compute age by itself.<br />
So everything is accessible.</p>
<pre class="brush: javascript;">
var person = new Person('inny', 'minny', 'yes please', new Date(1901, 0, 1) );

var fullname= person.surname+&quot;,&quot;+person.name;

var age=  (new Date().getYear() - person .dob.getYear()) ) ;
</pre>
<p>Of course one can argue that we can differentiate the difference between private and public by using underscore for private properties such as _dob ( as a lot of people insist on doing).</p>
<p>But who are we fooling? That&#8217;s just a convention we use, and if you work in a large team there&#8217;s no guarantee that someone else will not get smart and start mutating the underscored variable and shit might hit the fan depending on how critical the property is.</p>
<p>Instead of developing ad-hoc convention I believe its more ideal to use the best of what a language provides without having to define our own rule which can be broken by anyone who cares to break it. Sometimes I don&#8217;t trust myself,let alone trust others.</p>
<p>So if we need to hide the DOB for privacy reason and only expose the age,  and we need to hide the individual name and surname for some reason, here&#8217;s how its done:</p>
<pre class="brush: javascript;">
var Person= function(name ,surname, sex, dob){

this.sex=sex;

this.getFullName=function(){

return surname+&quot;,&quot;+name;
}

this.getAge=function(){

return  (new Date().getYear() - .dob.getYear()) ) ;

}
}
Person.prototype.getGender=function(){
var sex=this.sex,tolowerCase();
if( sex=='male' || sex=='m' )
return 'male';
else if( sex=='female' || sex=='f' )
rerturn 'female';
else
return 'god knows';

}

Person.prototype.getSpecies=function(){

return 'mammal';
}
</pre>
<p>In the above example, any instantiating code has only access to getFullName() , getAge() functions and &#8217;sex&#8217; variable of person object.<br />
But we allow &#8217;sex&#8217; variable to be declared in two forms, long and short. And we return &#8217;sex&#8217; in  long format with the help o getGender()  helper function.</p>
<p>The above example can be broken down as following;</p>
<p>All variables except sex are private as they are constructor-scoped.<br />
getFullName() and getAge() are privilaged function that have access to private variables name, surname and sex and thus are privileged/protected functions.</p>
<p>getGender() is a public function that has access to public variable sex.<br />
the new getSpecies() is a public function that returns a value that&#8217;s entirely in its own scope.</p>
<p>So, there we have it, private, privileged and public access in javascript.</p>
<p>If we want to use module pattern the above can be modified to:</p>
<pre class="brush: javascript;">
var Person= function(name ,surname, sex, dob){

this.sex=sex;
return{

getFullName:function(){

return surname+&quot;,&quot;+name;
},

getAge:function(){

return  (new Date().getYear() - this.dob.getYear()) ) ;

},
getSpecies:function(){

return 'mammal';
}

}
}
</pre>
<p>An example of creating static object with private and public scope:</p>
<pre class="brush: javascript;">
var Human = function() {

var species = &quot;mammal&quot;;

return {

alert: function(){alert(species);}

};
}();

Human.alert();//displays 'mammal'
</pre>
<p>Here the variable species is private.<br />
The function gets executed immediately due to () at the end of the function definition and will return a public static method alert()</p>
<p>That sums up variable scopes in javascript.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2009/05/javascript-variable-scope-private-protected-and-public/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>using java style  import to include javascript  files</title>
		<link>http://www.anzaan.com/2009/05/using-java-style-import-to-include-javascript-files/</link>
		<comments>http://www.anzaan.com/2009/05/using-java-style-import-to-include-javascript-files/#comments</comments>
		<pubDate>Sat, 23 May 2009 12:27:02 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[front end]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[java style package import]]></category>
		<category><![CDATA[javascript import]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=43</guid>
		<description><![CDATA[Simple way to import javascript files and package using java like conventions. Allows importing single file of all files in a package.]]></description>
			<content:encoded><![CDATA[<p>I had used a function and a little bootstrapping trick to solve my problem with including files in PHP and I was happy with it.<br />
But recently while working on a project that has a heavy javascript codebase, I started having trouble managing  all javascript file imports and all those script tags made pages look really ugly.<br />
And also I really longed for java&#8217;s clas importing capabilities in javascript such that I could import a single file based on package name or I could import a whole package.<br />
Since some of the pages I&#8217;m working requires over 15 script imports, some third-party libraries and some of our own files.<br />
And importing scripts one by one suffers from latency problems as it increases page load time and can contribute to user annoyances.<br />
So I longed for  java&#8217;s style of package and class  import and  decided to try my hand on writing some script to emulate imports based on packages.</p>
<p>I jsut used the  similar principle I used with php, but the problem is importing all files in a package isn&#8217;t possible in javascript because  javascript cannot read files form disk let alone iterate through a folder and read file content.<br />
For that there was nothing I could do except use some server-side help.</p>
<p>here&#8217;s the js file code with  function for importing js file and js files contained in a package(folder).</p>
<pre class="brush: javascript;">

//create namespace to aviod any present/ future  variable/object/funciton conflicts

if (typeof Anzaan == &quot;undefined&quot; || !Anzaan) {

Anzaan = {};
}

// array to hold all imported files so as not to import them twice
Anzaan.imports = [];

//server side URL for loading whole package content
Anzaan.packageLoaderURL='/Framework/packageLoader/';

//set the base folder for importing files
Anzaan.importBase='js/';

/**
* import a class using the java naming syntax for a class name.
*@param module the module to import
*@param  config object literal with two properties-
* config.packageLoaderURL - the server url for loading all files in a folder/package as a stream
* config.importBase - the base path for importing files
* use config only if necessary otherwise just modify Anzaan.packageLoaderURL and Anzaan.importBase
* of course you can use a different namespace or just use no namespace
*/
function Import(module, config) { //com.anzaan.framework.*

if(config){
if(config.packageLoaderURL)
Anzaan.packageLoaderURL=config.packageLoaderURL;

if(config.importBase)
Anzaan.importBase=config.importBase;
}

// if this import has already happened, don't bother,
if (Anzaan.imports[module] )
return ;

var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';

var src='';
var folders=module.split(&quot;.&quot;);
for(var i=0;i&lt;folders.length;i++){

if(folders[i].indexOf('*') &lt; 0)
src+=folders[i]+&quot;/&quot;;
}
src=src.substring(0,src.length-1);//remove the last slash

if (module.indexOf('*') &lt; 0) { //if not package import
src=Anzaan.importBase+src+&quot;.js&quot;;
script.src=src;

} else {
script.src=Anzaan.packageLoaderURL+&quot;?package=&quot;+Anzaan.importBase+src;
}

head.appendChild(script);
Anzaan.imports[module] = module;
}
</pre>
<p>The config parameter is optional. It shouldn&#8217;t really be used unless you want to load files from locations other tahn the default location of your application and want to use other URL for loading script files.</p>
<p>Just modify the global variables Anzaan.packageLoaderURL and Anzaan.importBase to set the base path and the serverside URL for loading scripts in folder.<br />
And of course rename Anzaan to something more meaningful for you.</p>
<p>Now on the server side here&#8217;s a simple php script that services the script file requests.<br />
It loads contents from js flies that reside in folder specified by &#8216;package&#8217;  variable.</p>
<p>packageLoader.php<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</p>
<pre class="brush: php;">
&lt;?php

$folder=$_GET[&quot;package&quot;]; // get the package name

$dir = opendir($folder); //open directory

while (($file = readdir($dir)) !== false) {
if (strrpos($file, '.js')) {

echo file_get_contents($folder.'/'.$file); //printout the content of file

}
}

?&gt;
</pre>
<p>and here&#8217;s a Java Servlet for doing the same thing:</p>
<pre>JSPackageLoaderServlet.java</pre>
<pre class="brush: java;">

public class JSPackageLoaderServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

response.setContentType(&quot;text/plain&quot;);
ServletOutputStream out = response.getOutputStream();

String packagePath = request.getParameter(&quot;package&quot;);

StringBuilder sb = new StringBuilder();

File myDir = new File(getServletContext().getRealPath(packagePath));
if (myDir.exists() &amp;&amp; myDir.isDirectory()) {
File[] files = myDir.listFiles();
for (int y = 0; y &lt; files.length; y++) {

String line = &quot;&quot;;
BufferedReader in = new BufferedReader(new FileReader(files[y]));

while ((line = in.readLine()) != null) {
sb.append(line);

}

}

}
out.print(sb.toString());
}
}
</pre>
<p>Here&#8217;s the usage:</p>
<pre class="brush: javascript;">
Import('anzaan.event.EvenHandler');
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2009/05/using-java-style-import-to-include-javascript-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Displaying Open Street Map (OSM) tiles inside Google Map</title>
		<link>http://www.anzaan.com/2009/05/displaying-open-street-map-osm-tiles-inside-google-map/</link>
		<comments>http://www.anzaan.com/2009/05/displaying-open-street-map-osm-tiles-inside-google-map/#comments</comments>
		<pubDate>Thu, 21 May 2009 00:58:06 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[mapping]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=14</guid>
		<description><![CDATA[I have been developing  vehicle-tracking system at work  for the past 1 year  or so and we use google for mapping.
Their enterprise license isn’t cheap and we didn’t  have  a viable alternative. I looked into OSM and found their coverage of Australia  not quite upto what we needed. We thought google has all  we needed [...]]]></description>
			<content:encoded><![CDATA[<p>I have been developing  vehicle-tracking system at work  for the past 1 year  or so and we use google for mapping.<br />
Their enterprise license isn’t cheap and we didn’t  have  a viable alternative. I looked into OSM and found their coverage of Australia  not quite upto what we needed. We thought google has all  we needed and settled for it.<br />
Few months back  a security company from Fiji showed keen  interest in buying our product as well as acting as our distributor in Fiji.<br />
That’s where the problem began. You see, Google’s coverage of Fiji is next to nothing, no roads, just a few zoom levels and that was it.</p>
<p>Like all good customers, their patience on the two months timeframe i had given them to get Fiji’s map up and running ran out before the deadline  and last week I promised them I’ll show them at least something within a week.  And of course I had no clue how I was going to keep that promise.</p>
<p>I tried my hand on all sorts of things, I tried to configure and run our own map server to spit our tiles for Fiji,  I tried overlaying Fiji’s map data (which the client provided as shapefiles and it only covered a part of Fiji) on google map, I used good-old Firebug to debug OpenGTS’s<br />
tracking website to see how they did their tracking using Open Street Map.</p>
<p>I had two plans.<br />
Plan A: whatever it takes get the fiji’s map to load inside google map so I can use the existing javascript codebase that relies on google’s api.<br />
Plan B: Use OSM for Fiji and google for rest,  and rewrite javascript code and use OpenLayer  javascript  library as the main library to allow users to switch ebtween providers easily.</p>
<p>Since Plan A is less painful, I tried to find ways to accomplish it. And Plan A  indeed turned out to be extremely painless if there’s such a thing.</p>
<p>I won’t go detail out all the things that failed, but I’ll definitely detail out what worked.</p>
<p>So, to all my fellow colleagues, cursing themselves in their little office cubicle, tearing their hair our trying to integrate OSM in google map,<br />
here’s the solution:</p>
<p>We’ll create a new map type and point google to OSM ’s tile provider to get map tiles from OSM instead of fetching them from google’s servers.</p>
<p>Firstly, We’ll create a new GTileLayer for osm.</p>
<pre class="brush: javascript;">

var osmTileLayer= new GTileLayer(new GCopyrightCollection(”&quot;),1,17);
osmLayer.myLayers=’osm’;
osmLayer.myFormat=’image/jpeg’;
</pre>
<p>This is where we define a custom function for fetchng tiles from OSM map server.<br />
This function will be user by google to fetch tiles from OSM everytime there’s request for tiles.</p>
<pre class="brush: javascript;">

osmLayer.getTileUrl=function(a,b,c) {

return ‘http://c.tile.openstreetmap.org/’+b+’/'+a.x+’/'+a.y+’.png’;

}
</pre>
<p>Then we create a map type and add it to our good old google map.</p>
<pre class="brush: javascript;">
var osmLayer=[osmTileLayer];
var OSMMap = new GMapType(osmLayer, G_SATELLITE_MAP.getProjection(), “OSM”, G_SATELLITE_MAP);
map.addMapType(OSMMap );
</pre>
<p>And that’s it !!<br />
That’s all it takes to add Open Street Map as a new map type in google map.</p>
<p>here’s the complete code:<br />
————————————————</p>
<pre class="brush: javascript;">

var osmTileLayer= new GTileLayer(new GCopyrightCollection(”&quot;),1,17);
osmLayer.myLayers=’osm’;
osmLayer.myFormat=’image/jpeg’;
osmLayer.getTileUrl=function(a,b,c) {

return ‘http://c.tile.openstreetmap.org/’+b+’/'+a.x+’/'+a.y+’.png’;

}

var osmLayer=[osmTileLayer];
var OSMMap = new GMapType(osmLayer, G_SATELLITE_MAP.getProjection(), “OSM”, G_SATELLITE_MAP);
map.addMapType(OSMMap );
</pre>
<p>—————————————————–</p>
<p>and here’s the final result:</p>
<p><img class="alignnone size-full wp-image-9" title="s640x4801" src="http://www.anzaan.com/wp-content/uploads/2009/05/s640x4801.png" alt="s640x4801" width="477" height="480" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2009/05/displaying-open-street-map-osm-tiles-inside-google-map/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
