<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Keith Chadwick &#8211; Occasional Moments of Clarity</title>
	<atom:link href="https://keithchadwick.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://keithchadwick.wordpress.com</link>
	<description>musings on technology and other bits and bites</description>
	<lastBuildDate>Fri, 23 Nov 2012 14:54:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='keithchadwick.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>https://secure.gravatar.com/blavatar/9c875f787bfe2bebe4ec685f1efac997029252026d98d6c7db1a39827df1a168?s=96&#038;d=https%3A%2F%2Fs0.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Keith Chadwick &#8211; Occasional Moments of Clarity</title>
		<link>https://keithchadwick.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="https://keithchadwick.wordpress.com/osd.xml" title="Keith Chadwick - Occasional Moments of Clarity" />
	<atom:link rel='hub' href='https://keithchadwick.wordpress.com/?pushpress=hub'/>
	<item>
		<title>mf Object Methods Part 2 {mf.object}</title>
		<link>https://keithchadwick.wordpress.com/2012/10/26/mf-object-methods-part-2-mf-object/</link>
					<comments>https://keithchadwick.wordpress.com/2012/10/26/mf-object-methods-part-2-mf-object/#comments</comments>
		
		<dc:creator><![CDATA[Keith Chadwick]]></dc:creator>
		<pubDate>Fri, 26 Oct 2012 16:17:28 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[mf]]></category>
		<category><![CDATA[Advanced JavaScript Application Development]]></category>
		<category><![CDATA[code structures]]></category>
		<category><![CDATA[JavaScriot]]></category>
		<category><![CDATA[javascript developers]]></category>
		<category><![CDATA[mf framework]]></category>
		<category><![CDATA[object search]]></category>
		<guid isPermaLink="false">http://keithchadwick.wordpress.com/?p=438</guid>

					<description><![CDATA[This is a series of posts that explains some of the fundamental rules for developing complex JavaScript applications and the mf framework. In my previous post on the mf object methods I discussed several methods that act against a single object. In this next series of object methods I will begin demonstrating some of the [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><em>This is a series of posts that explains some of the fundamental rules for developing complex JavaScript applications and the mf framework.</em></p>
<p>In my previous post on the m<em>f</em> object methods I discussed several methods that act against a single object. In this next series of object methods I will begin demonstrating some of the m<em>f</em> object methods that deal with arrays of objects. When we look at applications within the business sphere we in most cases have to deal with large amounts of data that is displayed in grids and other standard user interface implementations. When dealing with this type of data you need to envision, in regards to a grid, what types of behaviour and functionality you need to provide to the consumer. There are some obvious features like sorting and search plus filter. As such we need to provide these types of methods as part of the object methods. In the future of m<em>f</em> I will be developing a store object which will make significant use of these methods. In this post I will discuss the following methods&#8230;</p>
<ul>
<li><span style="color:#c0c0c0;"><em>mf.object.exec</em></span></li>
<li><span style="color:#c0c0c0;"><em>mf.object.normalize</em></span></li>
<li><span style="color:#c0c0c0;"><em>mf.object.merge</em></span></li>
<li><span style="color:#c0c0c0;"><em>mf.object.sort</em></span></li>
<li><span style="color:#c0c0c0;"><em>mf.object.search</em></span></li>
<li><span style="color:#c0c0c0;"><em>mf.object.difSearch</em></span></li>
</ul>
<h3><span id="more-438"></span><br />
<span style="color:#c0c0c0;"><strong>mf.object.exec (mixed, function, <em>deep</em>, <em>desctructive</em>)</strong></span></h3>
<p>The <em>object.exex</em> method allows you to enumerate through an array of objects or a single object and place the result of the provided function as the value of the property. The function is passed three arguments as the enumeration of the object is run. The value of the property, property namespace and the root object instance. You can optionally pass the deep boolean which defaults to false if you require deep object enumeration. The final parameter destructive is also optional boolean that defaults to true. When set to false the passed object or object array is first cloned and then returned. For example..</p>
<pre>var myObject = [
{z:1,x:'a',b:undefined},
{
    a:{
        aa:1,
        bb:2
    },
    f: 1
}]
mf.object.exec(myObject,function(val){return mf.isNumber(val)?val*10:val},true,false)</pre>
<p>The result of the exec method would return an array which has been cloned with the following values:</p>
<pre>{z:10,x:'a',b:undefined},
{
    a:{
        aa:10,
        bb:20
    },
    f: 10
}]</pre>
<p>Since the destructive argument was set to false the original <em>myObject</em> has not been modified.</p>
<h3><span style="color:#c0c0c0;"><strong>mf.object.normalize(array, <em>value</em>)</strong></span></h3>
<p>The <em>normalize</em> object method takes and array object mixed objects and ensures that each object all have the same properties. For example given the following call:</p>
<pre>var myObject = [
{z:1, x:'a', b:'z'},
{
    z:2,
    a:{aa:1,bb:2},
    f: 1
}]
mf.object.normalize(myObject);
The result would be:
[
 {
    z:1, 
    x:'a', 
    b:'z',
    a:{aa:null,bb:null},
    f:null
 },
 {
    z:2,
    x:null,
    a:{aa:1,bb:2},
    b:null,
    f: 1
 }
]</pre>
<p>As can bee seen both objects now share all of the same properties. The optional second parameter <em>value</em> is the default value to assign to properties that are created in each object in order to normalize. By default the <em>value </em>argument is <em>Null</em>.</p>
<p>When we dealing with large datasets being pulled via AJAX requests one of our goals is to reduce the size of this request as much as possible.  When dealing with these large sets most often all of the object definitions match on properties in the JSON requests even specific fields are null. On these large requests returning that a field is <em>Null</em> is wasteful on the request pipe. By using the <em>mf.object.normalize</em> method you can retrieve your data optimized for transport then use normalize it within the client. It should be taken into account however that running the normalize method against very large datasets is not recommended as it takes several passes on the data in order to normalize. Like any implementation a balanced approach needs to be taken by testing the performance versus request time.</p>
<h3><strong><span style="color:#c0c0c0;">mf.object.merge(array, function, <em>deep</em>)</span></strong></h3>
<p>Merges an array of objects into a single object allowing the ability to do things such as summed sets. For example:</p>
<pre>var data=[
{a:1,b:6},
{a:4,c:{y:2}},
{a:2,b:1,c:{x:1,y:1}}
];
mf.object.merge(data,function(prop,obj,ns,depth,mergeObjVal,mergeObj){obj[prop]+=mergeObjVal},true)</pre>
<p>The method would then return</p>
<pre>{
  a:7,
  b:7,
  c:{
     x:3,
     y:3
   }
}</pre>
<p>The merge method initially clones and normalizes the passed array of data so it is not destructive. The deep parameter is optional and is true by default. The function argument is passed several parameters to allow for direct changes to the both the current object and the resulting object. The function is passed the present object property along with the object root the current namespace as a string and the namespace depth.  The function is also passed the current value for the matching namespace in the merge object and the root of the merge object as well. The result of this function is always the merge object itself.</p>
<h3><strong><span style="color:#c0c0c0;">mf.object.sort(array, key, <em>ascending</em>)</span></strong></h3>
<p>Sorts an array of objects based on the provided key and its subsequent value. This method does NOT do a deep enumeration of each object so the key/property as string must exist at the root of each object. The boolean ascending is true by default to sort in descending order pass false. For example:</p>
<pre>var data=[
{a:1,b:6},
{a:4,b:3,c:{y:2}},
{a:2,b:1,c:{x:1,y:1}}
];
mf.object.sort(data,'a')</pre>
<p>The passed data will now be sorted ascending by the value contained in the root a property of the objects. This method does NOT do any data normalization to ensure that the provided property key exists in each object.</p>
<h3><span style="color:#c0c0c0;"><strong>mf.object.search(propertySet, array)</strong></span></h3>
<p>Search an array of objects and returns an array of those objects matching the propertySet. This method does not support deep object enumeration, use intersect for deep enumeration. The property set is by definition a simple object that allows for matching of property values. For example:</p>
<pre>var data=[
{a:1,b:6},
{a:4,b:3,c:{y:2}},
{a:2,b:1,c:{x:1,y:1}}
];
mf.object.search({a:4},data)</pre>
<p>This would return an array containing one object from data whose <em>a</em> property was equal to 4. The property set parameter can also contain functions that must return true or false. Consider the following scenario:</p>
<pre>var data = [
 {title:'Welcome to my framework'},
 {title:'Using Object Methods',b:2},
 {title:'Object.intersect Method in Detail',b:1}
];
mf.object.search({b:2,title:function(val){return val.match('Object')}},data)</pre>
<p>In this case we are checking the title to see if the value contains the word object and also is its <em>b</em> property is equal to 2. The result would be the second object from the array. This is a not a descructive method and the passed objects are NOT cloned into the resulting array so all pointers would still remain intact.</p>
<h3><strong><span style="color:#c0c0c0;">mf.object.difSearch(propertySet,array)</span></strong></h3>
<p>The <em>difSearch</em> method is identical in nature to <em>search</em> but returns an array of objects that do <strong>not</strong> meet the search requirements. As an example:</p>
<pre>var data = [
 {title:'Welcome to my framework'},
 {title:'Using Object Methods',b:2},
 {title:'Object.intersect Method in Detail',b:1}
];
mf.object.difSearch({b:2,title:function(val){return val.match('Object')}},data)</pre>
<p>This call would result in only the first array object being returned as both the 2nd and 3rd objects fail on one or more of the tests.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://keithchadwick.wordpress.com/2012/10/26/mf-object-methods-part-2-mf-object/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/9dcf35ae769cdd4c4ba1ee89bc27974a960d5e247b60340c10a2cacb746ccff1?s=96&#38;d=https%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Chady</media:title>
		</media:content>
	</item>
		<item>
		<title>mf Object Methods Part 1 {mf.object}</title>
		<link>https://keithchadwick.wordpress.com/2012/10/18/mf-object-methods-part-1-mf-object/</link>
					<comments>https://keithchadwick.wordpress.com/2012/10/18/mf-object-methods-part-1-mf-object/#respond</comments>
		
		<dc:creator><![CDATA[Keith Chadwick]]></dc:creator>
		<pubDate>Thu, 18 Oct 2012 15:54:34 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[mf]]></category>
		<category><![CDATA[JavaScript Object Methods]]></category>
		<category><![CDATA[mf framework]]></category>
		<category><![CDATA[mf.object]]></category>
		<category><![CDATA[mf.object.clense]]></category>
		<category><![CDATA[mf.object.containsKeys]]></category>
		<category><![CDATA[mf.object.containsVals]]></category>
		<category><![CDATA[mf.object.deepEach]]></category>
		<category><![CDATA[mf.object.each]]></category>
		<category><![CDATA[mf.object.typeMap]]></category>
		<guid isPermaLink="false">http://keithchadwick.wordpress.com/?p=359</guid>

					<description><![CDATA[This post discusses some the base methods available in the mf.object namespace including each, deepEach, clense, typeMap, containsKeys and containsVals.]]></description>
										<content:encoded><![CDATA[<p><em>This is a series of posts that explains some of the fundamental rules for developing complex JavaScript applications and the mf framework.</em></p>
<p>It has been a few weeks since I wrote a post on m<em>f</em> but this has most been due to the time it took to complete all of the object methods available.  Object methods along with array methods are some of the most important methods that any framework can have and as such taking some extra time is required. At present there are 28 methods written and fully tested. Given this number it would obviously be far to much for one single blog post. As a result I will be writing several blog posts each covering several methods at a time. In this post I will discuss the following methods:<i><br />
</i></p>
<ul>
<li><em><span style="color:#993300;">mf.object.each</span></em></li>
<li><em><span style="color:#993300;">mf.object.deepEach</span></em></li>
<li><em><span style="color:#993300;">mf.object.clense</span></em></li>
<li><em><span style="color:#993300;">mf.object.typeMap</span></em></li>
<li><em><span style="color:#993300;">mf.object.containsKeys</span></em></li>
<li><em><span style="color:#993300;">mf.object.containsVals</span></em></li>
</ul>
<p><span id="more-359"></span></p>
<h3><span style="color:#993300;">mf.object.each (object, function, <em>scope</em>)</span></h3>
<p>The each method is used to enumerate through each attribute of an object at a shallow level under the optionally passed scope. On each attribute of the object the provided function is called under the provided scope and passed the name of the attribute as a string, the value of attribute along with the original object passed. For example:</p>
<pre>var myObject = {a:1,b:2,c:['a','b','c'],d:{aa:1,bb:2}};
var testFunction = function(key,val,o){
     console.write(key,typeof val, val, o)
};
mf.object.each(myObject,testFunction)

Result:
a, number, 1, {a:1,b:2,c:['a','b','c'],d:{aa:1,bb:2}}
b, number, 2, {a:1,b:2,c:['a','b','c'],d:{aa:1,bb:2}}
c, array, ['a','b','c'], {a:1,b:2,c:['a','b','c'],d:{aa:1,bb:2}}
d, object, {aa:1,bb:2}, {a:1,b:2,c:['a','b','c'],d:{aa:1,bb:2}}</pre>
<p>As you can see it is fairly simple in its behaviour. If you wanted to break out of the enumeration of the passed object all you need to is return false from your test function. This function is non destructive in nature. It should be remember however that the method does NOT test for has <em>hasOwnProperty</em>. This is a deliberate decision on my part to allow for the enumeration of prototyped methods and also remove any condition of enumeration for improved performance.</p>
<p>One of the problems however with the <em>object.each</em> method can be seen in the last result of the example which returns <em>d</em> which is an <em>object</em> itself. Basically the <em>each</em> method does not do &#8216;deep&#8217; enumeration of the passed object. Certainly you could do this with an test and iterative call within your passed function, such as:</p>
<pre>var testFunction = function(key,val,o){
  if(mf.isObject(val)){
     mf.object.each(o[key],testFunction)
  }else{
     // do something
  }
}</pre>
<p>However this would get very tiresome having to write this in your code all of the time and two points here. In many circumstances you need to do deep object enumeration and secondly, the point of a framework is to streamline your code. The <em>each</em> method returns the passed object in order to allow for chaining.</p>
<h3><span style="color:#993300;">mf.object.deepEach(object,function,<em>scope</em>)</span></h3>
<p>The <em>deepEach</em> method works in the exact same fashion as the <em>each</em> method where returning false will exit the enumeration. However it enumerates the object deeply. Given our example above running the same testFunction on myObject with the <em>deepEach</em> method would result in the following output:</p>
<pre>Result:
a, number, 1, {a:1,b:2,c:['a','b','c'],d:{aa:1,bb:2}}
b, number, 2, {a:1,b:2,c:['a','b','c'],d:{aa:1,bb:2}}
c, array, ['a','b','c'], {a:1,b:2,c:['a','b','c'],d:{aa:1,bb:2}}
d, object, {aa:1,bb:2}, {a:1,b:2,c:['a','b','c'],d:{aa:1,bb:2}}
aa, number, 1, {aa:1,bb:2}
bb, number, 2, {aa:1,bb:2}</pre>
<p>As you can see the call would result in the attributes on the <em>d</em> object being passed as well to the function as well as the original <em>d</em> object itself. Note however, when the provided function is passed the attributes of the <em>d</em> object that the passed object changes to <em>d</em> rather than the original root object.  This allows you do things like o[key] in your function and be guaranteed that the key exists within the passed objects scope.</p>
<p>When working with the <em>deepEach</em> method the passed function is also passed two extra parameters, namespace as string and depth as a number. To understand how these can be used lets look at the following example:</p>
<pre>var testFunction = function(key,val,o,ns,depth){
	console.log(key,typeof val, val, o, ns, depth)
}
var myObject = {
a:1,
b:{
	aa:{
		aaa:1,
		bbb:2,
		ccc:{
			aaaa:'a',
			bbbb:'b'
		}
	}
}}
mf.object.deepEach(myObject,testFunction)

Result:
a,number, 1, [object Object], , 0
b,object, [object Object], [object Object], , 0
aa,object, [object Object], [object Object], b, 1
aaa,number, 1, [object Object], b.aa, 2
bbb,number, 2, [object Object], b.aa, 2
ccc,object, [object Object], [object Object], b.aa, 2
aaaa,string, a, [object Object], b.aa.ccc, 3
bbbb,string, b, [object Object], b.aa.ccc, 3</pre>
<p>Note the result on our <em>deepEach</em> call  for namespace and depth. When we method is at the root of the passed object no namespace is passed and the depth is zero. When we hit the attribute <em>aa</em> within the <em>b </em>object the namespace is passed as the string <em>b</em> and the depth is 1. This allows you to make test conditions within your function when looking for a specific condition/attribute within a specific namespace or depth. Consider for a moment this object:</p>
<pre>var myObject = {a:{aa:1,bb:2},b:{aa:1,bb:2}}
var testFunction = function(key,val,o,ns,depth){
    if(ns==='a' and key==='aa'}{
        o[key]=null
    }
}
mf.object.deepEach(myObject,testFunction)</pre>
<p>In this example if the <em>deepEach</em> method did not provide the namespace as string there would be no way to differentiate between the <em>aa</em> attribute in <em>a</em> or <em>b</em> which would not be very useful. Like the <em>each</em> method the <em>deepEach</em> method is non destructive and also returns the passed object to allow for chaining.</p>
<h3><span style="color:#993300;">mf.object.clense(object, <em>value</em>,<em> deep</em>)</span></h3>
<p>This methods resets an objects attribute values to the optionally provided value. You can also specify if the enumeration should be deep on the object. If the value is not provided is not provided it is defaulted to <em>null. </em>If deep is not provided it will be defaulted to false. Given the following:</p>
<pre>var myObject = {a:1,b:2,c:{aa:1,bb:1}
mf.object.clense(myObject,null,true)
Result:
{a:null, b:null ,c:{aa:null, bb:null}</pre>
<p>If deep had been set to false only the root attributes of <em>a </em>and <em>b </em>would have been set to<em> null </em>and <em>aa </em>and <em>bb</em> would still be 1.</p>
<h3><span style="color:#993300;">mf.object.typeMap (object, <em>deep</em>)</span></h3>
<p>The <em>typeMap </em>method is a convenience function that returns an object describing the types of of objects contained with the object. It can be used to easily find specific types of data based on namespaces within the object. The deep parameter is optional and defaults to true. For Example:</p>
<pre>var myObject = {
    a:{
        aa:1,
        bb:2,
        cc:[1,2,4],
        dd:null
    },
    b:[1,2,3,4],
    c: undefined,
    d: function(){return true},
    f: 1,
    g: 'abc'    
};
mf.object.typeMap(myObject,true)

Result:
{
  array : ['a.cc','b'],
  function : ['d'],
  null : ['a.dd'],
  number : ['a.aa','a.bb','f'],
  object : ['a'],
  string : ['g'],
  undefined : ['c']
}</pre>
<p>The result of the call always returns the exact same properties but if for example no arrays where present in the object the the array attribute would have an empty array.  This <em>typeMap</em> method can be useful when you need to set specific types of information in the object to a value. For example consider if we had an unknown object but needed to ensure that it did NOT contain any attributes assigned to functions and all number attributes where set to 0. This could easily be done within m<em>f</em> with the following code.</p>
<pre>var myMap = mf.object.typeMap(myObject,true);
mf.each(myMap['function'],function(val){
    mf.ns.remove(val,myObject)
});
mf.each(myMap['number'],function(val){
    mf.ns.set(val,myObject,0);
})</pre>
<p>You will notice in the above code I have touched on a couple of other methods <em>mf.each, mf.ns.remove</em> and <em>mf.ns.set</em>. I will be discussing these methods in a future post.</p>
<h3><span style="color:#993300;">mf.object.containsKeys(object, keys, <em>deep</em>)</span></h3>
<p>This method accepts an object and an array of namespace keys, a string of comma delimited keys or a single key and returns true if the key(s) are found within the object. The deep parameter is optional and defaults to false. Any of the following calls would be valid</p>
<pre>mf.object.containsKeys(myObject,['a','a.bb','cc']);
mf.object.containsKeys(myObject,'a,a.bb,cc');
mf.object.containsKeys(myObject,'a');</pre>
<p>If more than one namespace/key is passed they ALL must be found in order for the method to return true.</p>
<h3><span style="color:#993300;">mf.object.containsVals(object, vals, <em>deep</em>)</span></h3>
<p>This method is identical to contains keys but the comparison is done against the values rather than the keys and if found returns true. As with the <em>containsKeys </em>method if an array of values are passed all must be found in order for the method to return true.</p>
<hr />
<p>In my next post I will discuss further methods in the object class of m<em>f. </em>These methods will focus more on arrays objects and provide methods for sorting, normalizing, searching, comparison along with many more very cool methods for manipulated arrays of object.</p>
<p>When I have completed the blog posts on the <em>mf.object</em> methods I will be adding them to the m<em>f</em> API documentation at the top of the blog along with other base methods. Until then enjoy.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://keithchadwick.wordpress.com/2012/10/18/mf-object-methods-part-1-mf-object/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/9dcf35ae769cdd4c4ba1ee89bc27974a960d5e247b60340c10a2cacb746ccff1?s=96&#38;d=https%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Chady</media:title>
		</media:content>
	</item>
		<item>
		<title>Making a Browser Sniffer for mf</title>
		<link>https://keithchadwick.wordpress.com/2012/09/20/making-a-browser-sniffer-for-mf/</link>
					<comments>https://keithchadwick.wordpress.com/2012/09/20/making-a-browser-sniffer-for-mf/#respond</comments>
		
		<dc:creator><![CDATA[Keith Chadwick]]></dc:creator>
		<pubDate>Thu, 20 Sep 2012 16:00:29 +0000</pubDate>
				<category><![CDATA[Advanced JS AppDev]]></category>
		<category><![CDATA[mf]]></category>
		<category><![CDATA[Advanced JavaScript Application Development]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[javascript developers]]></category>
		<category><![CDATA[Singleton]]></category>
		<guid isPermaLink="false">http://keithchadwick.wordpress.com/?p=322</guid>

					<description><![CDATA[Creating a browser version sniffer is a key component to any JavaScript framework]]></description>
										<content:encoded><![CDATA[<p><em>This is a series of posts that explains some of the fundamental rules for developing complex JavaScript applications and the mf framework.</em></p>
<p>One of the first key things that is required in any JavaScript framework is a browser sniffer. Browser sniffers are easy to create and as with all of the modules that will be placed into <strong>m<em>f</em></strong> it uses my standard design pattern. Here is the code:</p>
<pre>var browser = Object.freeze((function(){
     var app = new String(navigator.userAgent),
     mode = document.documentMode,
     isIE = app.match('MSIE')!==null,
     isSafari = app.match('Safari')!==null &amp;&amp; app.match('Chrome')===null,
     isChrome = app.match('Safari')!==null &amp;&amp; app.match('Chrome')!==null,
     isFireFox = app.match('Firefox')!==null,
     tests = {
           isSafari : isSafari,
           isChrome : isChrome,
           isFireFox : isFireFox,
           isIE : isIE,
           isIE5 : isIE &amp;&amp; mode===5,
           isIE6 : isIE &amp;&amp; mode===6,
           isIE7 : isIE &amp;&amp; mode===7,
           isIE8 : isIE &amp;&amp; mode===8,
           isIE9 : isIE &amp;&amp; mode===9,
           isIE10 : isIE &amp;&amp; mode===10,
           version : 0,
           isWin : navigator.platform.toLowerCase()==='win32',
           isMac : navigator.platform.toLowerCase()!=='win32',
           isSecure : (window.location.protocol).toLowerCase().substr(0,5)==='https'
     },
     Public = {};
     <em>// get browser version
</em>     if(isFireFox){
           tests.version = parseInt(/Firefox\/(\d+\.)/.exec(app)[1],10)
     }else if(isChrome){
           tests.version = parseInt(/Chrome\/(\d+\.)/.exec(app)[1],10)
     }else if(isSafari){
           tests.version = parseInt(/Version\/(\d+\.)/.exec(app)[1],10)
     }else if(isIE) {
           tests.version = parseInt(/MSIE (\d+\.)/.exec(app)[1],10)
     };                             
     tests.mfCompliant = (isSafari &amp;&amp; test.version&gt;4) || (isIE &amp;&amp; tests.version &gt;8 &amp;&amp; mode&gt;8) || (isChrome &amp;&amp; tests.version&gt;20) || (isFireFox &amp;&amp; tests.version&gt;14);
     <em>// convert results into anonymous function calls
</em>     for(prop in tests){
           Public[prop]=new Function('return '+tests[prop]+';')
     };
     return Public;                                    
}()));</pre>
<p>Note that I am adding the mfCompliant property onto the tests object and setting my browser minimum requirements.  I am also not testing for Opera although that certainly could be added in very easily at any point in the future.  Finally I enumerate through the tests object and create anonymous functions within the Public object that return the values of the subsequent property in the tests object.  Note also the the public returned by the outer anonymous function is passed to the Object.freeze method in order to freeze the resulting object. This will prevent users from overriding existing methods or removing them.</p>
<p>In the case of IE9 it does not support the Object.freeze method.  As a result I had to place the following code above this module.</p>
<pre><em>// Ensure we have freeze method on Object for IE9
</em>if((typeof Object.freeze).toLowerCase()!=='function'){
       Object.prototype.freeze = function(o){
              return o
       }
}</pre>
<p>Sine the freeze method returns the object being frozen this little override does the same thing in order to ensure when running the framework in IE9 it does not blow up on you.  Freezing is certainly handy on objects but does not add any direct functionality to the framework.</p>
<p>The mf global variable browser is then returned as belonging as a child object to the framework.  This then allows external users to make calls such as<em> mf.browser.isIE()</em> or <em>mf.browser.isSecure()</em>. Certainly over time there may be other items to add under the browser module but these are the basics.</p>
<p>In my next post I will be fleshing out some other core methods for Objects, Arrays along with some base prototyping of core JavaScript objects such as String and Number.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://keithchadwick.wordpress.com/2012/09/20/making-a-browser-sniffer-for-mf/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/9dcf35ae769cdd4c4ba1ee89bc27974a960d5e247b60340c10a2cacb746ccff1?s=96&#38;d=https%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Chady</media:title>
		</media:content>
	</item>
		<item>
		<title>Why am I writing the mf Framework</title>
		<link>https://keithchadwick.wordpress.com/2012/09/05/why-am-i-writing-the-mf-framework/</link>
					<comments>https://keithchadwick.wordpress.com/2012/09/05/why-am-i-writing-the-mf-framework/#respond</comments>
		
		<dc:creator><![CDATA[Keith Chadwick]]></dc:creator>
		<pubDate>Wed, 05 Sep 2012 14:54:44 +0000</pubDate>
				<category><![CDATA[Advanced JS AppDev]]></category>
		<category><![CDATA[mf]]></category>
		<category><![CDATA[Advanced JavaScript Application Development]]></category>
		<category><![CDATA[Javascript]]></category>
		<guid isPermaLink="false">http://keithchadwick.wordpress.com/?p=155</guid>

					<description><![CDATA[I suppose the question of why write yet another framework should be answered to some degree. Over the many years of working with JavaScript developers from junior to senior I have noted a common theme. In almost every case the developer indicates that they know this framework or another framework yet none of them seem [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I suppose the question of why write yet another framework should be answered to some degree. Over the many years of working with JavaScript developers from junior to senior I have noted a common theme. In almost every case the developer indicates that they know this framework or another framework yet none of them seem to understand how it is written. It is akin to knowing how to drive a car yet not understanding how it works. I think that is a dangerous mindset for both driving and writing JavaScript.</p>
<p>All JavaScript frameworks have common methods each with its&#8217; own unique slant on implementation. All frameworks consist of browser sniffers, DOM normalization plus Event and Component Management along with methods to make life a little easier for the programmer. Each of these concepts offer the same or similar implementation yet there seems to be a gross lack of understanding on how they work.</p>
<p>So the goal of creating the <sup>m</sup><em>f</em> framework is to demonstrate to JavaScript developers the basic concepts of how frameworks are put together in order to further their understanding of other frameworks. So like driving a car you should have some idea of how the engine actually works!</p>
<p>So, in the next several months I will be building up the framework piece by piece with one or more blog posts on each of the components that will constitute the end product.  Once I have the framework developed to a certain point I will also be placing it up on Google code for people to play with, enhance or throw mean reviews back at me.</p>
<p>Cheers<br />
Keith</p>
]]></content:encoded>
					
					<wfw:commentRss>https://keithchadwick.wordpress.com/2012/09/05/why-am-i-writing-the-mf-framework/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/9dcf35ae769cdd4c4ba1ee89bc27974a960d5e247b60340c10a2cacb746ccff1?s=96&#38;d=https%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Chady</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating Object Properties {the dangling participle of JS Objects}</title>
		<link>https://keithchadwick.wordpress.com/2012/08/28/creating-object-properties-the-dangling-participle-of-js-objects/</link>
					<comments>https://keithchadwick.wordpress.com/2012/08/28/creating-object-properties-the-dangling-participle-of-js-objects/#respond</comments>
		
		<dc:creator><![CDATA[Keith Chadwick]]></dc:creator>
		<pubDate>Tue, 28 Aug 2012 15:28:01 +0000</pubDate>
				<category><![CDATA[Advanced JS AppDev]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Advanced JavaScript Application Development]]></category>
		<category><![CDATA[code structures]]></category>
		<category><![CDATA[javascript developers]]></category>
		<guid isPermaLink="false">http://keithchadwick.wordpress.com/?p=217</guid>

					<description><![CDATA[This is a series of posts that explains some of the fundamental rules for developing complex JavaScript applications. As most of us know, well I would hope most of us that is, properties in objects have some fundamental flaws in them, that, like many situations in JavaScript our bits and bites are left hanging out!  [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><em>This is a series of posts that explains some of the fundamental rules for developing complex JavaScript applications.</em></p>
<p>As most of us know, well I would hope most of us that is, properties in objects have some fundamental flaws in them, that, like many situations in JavaScript our bits and bites are left hanging out!  Object properties that are exposed publicly, whether in a module pattern or an instance have absolutely zero control over them.</p>
<p>If one does some research however you will dig up the <em>Object.defineProperty</em> method and supporting methods that as of IE9 are now common across all modern browsers.  If you are interested in reading up on the defineProperty Object method I have found the best documentation to be over at <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty">Mozilla </a>. While Object.defineProperty does provide us enhancements such as read only, freezing and preventing deletion is certainly does not, in my opinion, provide much power. A property should provide the following:</p>
<ul>
<li>Verbose setters and getter methods,</li>
<li>Conditional checking on setters,</li>
<li>Chaining of base object setters,</li>
<li>Watches and events.</li>
</ul>
<p><span id="more-217"></span></p>
<p>So let’s go through each of these concepts. Verbose setter and getter methods are in essence methods to set and get the property value while protected the actually base value. So assuming we have an object entitled <em>myLittleObject</em> with a property called <em>height</em> I should be able to say <em>myLittleObject.height.set(10)</em> or <em>myLittleObject.height.get()</em>. Now a very good argument can be made for simple having a single method on <em>height</em> which either returns the value or takes a value, thusly <em>myLittleObject.height(10) </em>sets the value to 10 and <em>myLittleObject.height()</em> returns 10. While I have nothing against this, I simply prefer my code to be extremely verbose, hence my preference for property.set/get.  It also helps that I am an extremely fast typist, so perhaps that helps!</p>
<p>Conditional Checking of setter refers to the ability to apply a test to value being assigned to a property. One of the general weaknesses of JavaScript is its’ base data types. Let’s face it Number() really does not cut it for numeric values. Most languages, in fact I cannot think of any that do not support Int, Long, Double etc. I recognize that there is argument that there is no point to creating other base types as they will all be based against the browser engine data type so there is no memory or speed enhancement. However from a pure programmatic point of view being able to apply tests against a value being passed in provides for much greater control.</p>
<p>Chaining is a key part of todays’ JavaScript frameworks. Chaining is the process of returning the base object on calling the setter method of that object’s property. For example, if we have an object with two properties we should be able to do, <em>myObject.x.set(1).y.set(2)</em> rather than having to make two separate statements on <em>myObject</em>. In this case the set method of each property returns <em>myObject</em>.</p>
<p>Watches and events are an extremely important aspect of a property object. Many years ago Mozilla introduced watches on variables which in essence allowed you to create binders to the watch to ‘watch’ for certain conditions.  This could be viewed at its core level as an event style paradigm. For the purpose of this blog post I will not cover creating the watch/event object as that is beyond the scope of this post. I will however discuss the creation of an event object in the next post.</p>
<p>Now that we have gone through the requirements let’s look at the basics for the method.</p>
<pre><em>/**
  * @method createProp
  * @description Creations a property on the passed object and property based on the provided config.
  * @param scope [object] The location within the object to create property
  * @param prop [string] The name of the property to create
  * @param config [object] Mixed object declaring the details of the property, see defaults.
  * @return null
  **/
 </em>createProperty = function (scope,prop,config){
                 var defaults = {
                                 <em>// @prop verbose (bool) When true properties are given declaritive set and get methods rather
 </em>                                <em>// than a single method that tests for the existence of a passed value.
 </em>                                verbose : false,

                                 <em>//@prop writeable (bool) indicates if the property will have a setter method
</em>                                 writeable : true,

                                 <em>//@prop value (mixed) value of the property
 </em>                                value : null,

                                 <em>//@prop allowNull (bool) When true property may be null
                 </em>                allowNull : true,

                                 <em>//@prop allowUndefined (bool) When true property may be undefined
</em>                                 allowUndefined : false,

                                 <em>//@prop valueCondition (function) A function passed the value being provided to the setter method. If false is returned  the property value will not be changed
                                 </em>valueCondition:function(){return true},

                                 <em>// @prop setterErrorThrow (object) Object containing booleans on whether to throw errors on setter failuers. For example if  the config property allowNull is false have a setterErrorThrow of null true will throw an error when the property is attempting to be set to null. If the properties root sibling is true then the sibling throw property will be ignored.
 </em>                                setterErrorThrow : {
                                                 allowNull : false,
                                                 allowUndefined : false,
                                                 valueCondition : false
                                 },

                                 <em>// @prop chain (bool) When true the scope object is returned on the setter method allowing for the chaining of objects 
 </em>                                chain : true,

                                 <em>// @prop scope (mixed) object to return on setter when chain is true, defaults to passed scope on function
 </em>                                scope : scope
                 };
                 config = applyIf(config,defaults);
 };</pre>
<p>If we remember back to my previous post ‘<a href="https://keithchadwick.wordpress.com/2012/07/22/writing-flexible-javascript-functions/">Writing Flexible JavaScript Functions’</a> I introduced the <em>applyIf</em> method that allows for the assignment of properties in an object. As can be seen by the above code I have set up a set of default properties along with explanations of what each will do.</p>
<p>Now that we have this set up lets write the actual code to return the object following the <em>applyIf</em> line.</p>
<pre>var propObject = (function(config){
                 var currentValue=config.value,
                 propConfig = config,
                 methods = {
                                 get : function(){
                                                 return currentValue;
                                 }
                 };
                 if(propConfig.writeable){
                                 methods.set = function(value){
                                                 if(value === undefined &amp;&amp; !propConfig.allowUndefined){
                                                                 if(propConfig.setterErrorThrow.allowUndefined){
                                                                                 throw('undefined not allowed');
                                                                 }
                                                 }else if(value === null &amp;&amp; !propConfig.allowNull){
                                                                 if(propConfig.setterErrorThrow.allowNull){
                                                                                 throw('null not allowed');
                                                                 }              
                                                 }else if(!propConfig.valueCondition(value)){
                                                                 if(propConfig.setterErrorThrow.valueCondition){
                                                                                 throw('value condition fail');
                                                                 }                                                                              
                                                 }else{
                                                                 currentValue=value;
                                                 };
                                                 return propConfig.chain?propConfig.scope:value;
                                 }
                 }
                 return methods;
 }(config));

 if(config.verbose){
                 scope[prop]=Object.freeze(propObject);
 }else{
                 scope[prop]=Object.freeze(function(value){
                                 if(value!==undefined &amp;&amp; propObject.set!==undefined){
                                                 return propObject.set(value);
                                 }else if(value===undefined){
                                                 return propObject.get();
                                 }
                 })
 }</pre>
<p>As you can see this is a fairly simple implementation. I create an internal object called <em>propObject</em> with the required methods along with a copy of the passed <em>config</em>. Once the object is created I check the <em>config.verbose</em> setting to decide how to assign the object to the passed scope and property.</p>
<p>The first thing that you will most likely be thinking at this moment is why not use the prototype model as most likely we would have a fair number of these properties created.  You would of course be 100% correct; using the prototype model would be more efficient.  But herein lies the key issue with the prototype model. Any prototyped method can only use the <em>this</em> keyword to refer to the instance on the object that is calling the method.  This being the cased how do you get the <em>protected </em>value since it is not exposed within the object.  To use the prototype model you would have to expose the value within the instance which defeats the very purpose of creating setters and getters in the first place.  Although I love the prototype patter I see the issue of closures on the instance being the most significant drawback to the implementation.</p>
<p>Over the past several posts I have introduced some key ideas for design patters, function implementations etc. In my next post I will be putting them into a framework entitled <em>mf</em>.  I choose <em>mf</em> not to reflect Mr. Purple and his Sexy Mf but rather it stands for <em>my framework</em>.  Although in times of frustration one could use the other definition! Once we have the basic framework set out I will be introducing how to write your own event component followed by some other key components you need to have in a custom framework.</p>
<p>Until then…cheers</p>
]]></content:encoded>
					
					<wfw:commentRss>https://keithchadwick.wordpress.com/2012/08/28/creating-object-properties-the-dangling-participle-of-js-objects/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/9dcf35ae769cdd4c4ba1ee89bc27974a960d5e247b60340c10a2cacb746ccff1?s=96&#38;d=https%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Chady</media:title>
		</media:content>
	</item>
		<item>
		<title>Singleton to Prototype Design Guidelines</title>
		<link>https://keithchadwick.wordpress.com/2012/08/18/singleton-to-prototype-design-guidelines/</link>
					<comments>https://keithchadwick.wordpress.com/2012/08/18/singleton-to-prototype-design-guidelines/#respond</comments>
		
		<dc:creator><![CDATA[Keith Chadwick]]></dc:creator>
		<pubDate>Sat, 18 Aug 2012 17:58:14 +0000</pubDate>
				<category><![CDATA[Advanced JS AppDev]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Advanced JavaScript Application Development]]></category>
		<category><![CDATA[code structures]]></category>
		<category><![CDATA[JavaScriot]]></category>
		<category><![CDATA[javascript applications]]></category>
		<category><![CDATA[javascript developers]]></category>
		<category><![CDATA[Prototype]]></category>
		<category><![CDATA[Singleton]]></category>
		<category><![CDATA[singleton pattern]]></category>
		<guid isPermaLink="false">http://keithchadwick.wordpress.com/?p=201</guid>

					<description><![CDATA[This is a series of posts that explains some of the fundamental rules for developing complex JavaScript applications. I am a real bugger when it comes to how my code is organized. Given the advanced user interfaces that we have today I have often noticed that JavaScript developers have become, for lack of a better [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><em>This is a series of posts that explains some of the fundamental rules for developing complex JavaScript applications.</em></p>
<p>I am a real bugger when it comes to how my code is organized. Given the advanced user interfaces that we have today I have often noticed that JavaScript developers have become, for lack of a better adjective, bloody lazy!  Before we get into the singleton design patter a short discussion is warranted on when a singleton should be used versus a class that supports instantiation.</p>
<p>The most common examples of a singleton are existing JavaScript frameworks such as ExtJs, jQuery, etc. In essence we would only ever have a single instance of each of these frameworks each represented by its own unique namespace Ext and $ respectively. The other most common example of the singleton pattern is the root namespace that represents your JavaScript application because you would under most circumstances only have one. Note I said most circumstances.  There is often the case in the real world where a requirement initially requires a singleton pattern but over time it becomes evident that a class instance would be better.  The golden rule of ‘the only constant is change’ should always be kept in mind when designing your code structures. The purpose of this post is to demonstrate how to effectively use the singleton pattern properly and in such a way as to allow for the easy migration to a class pattern. The secondary goal is to show how writing your singletons in this fashion leads to consistency of code which is something we should all strive for!</p>
<p>First let’s look at the basic singleton design pattern that I often see exemplified on the web.</p>
<pre>var mySingleton = {
                 globalVar1 : null,
                 globalVar2 : null,
                 myMethod1 : function(){},
                 myMethod2 : function(){}
 }</pre>
<p>So I will state this very clearly and strongly, the above is NOT a singleton.  In my opinion this is a simple object that does nothing more provide a hierarchical structure of variables and methods under a root namespace.  For starters this pattern does NOT use closures and does not have the concept of private/protected vs public methods and variables. At a minimum the singleton design pattern should be written as follows.</p>
<p><span id="more-201"></span></p>
<pre>var mySingleton = ( function(){

                 // private/protected variables and methods
                 var myVar1 = null,
                 myVar2 = null,
                 method1 = function(){…}
                 method2 = function()(){…};

                 // public variables and methods
                 return {
                                 publicVar1 : null,
                                 publicVar2 : null,
                                 publicMethod1 : function(){…},
                                 publicMethod2 : function(){…}
                 }
 }());</pre>
<p>As we can see the singleton is wrapped in an out closure with an inner function that immediately executes upon load.  Methods and variables that need to be exposed to a consumer are defined within the return statement. So far so good, but nowhere good enough for me. At the beginning of this post I said I was a real bugger about code design.  In my humble opinion with a touch of ego a singleton or for that matter an instantiable class has the following basic namespaces.</p>
<p><a href="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture2.png"><img data-attachment-id="203" data-permalink="https://keithchadwick.wordpress.com/2012/08/18/singleton-to-prototype-design-guidelines/capture-4/" data-orig-file="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture2.png" data-orig-size="565,188" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="Capture" data-image-description="" data-image-caption="" data-medium-file="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture2.png?w=300" data-large-file="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture2.png?w=549" class="aligncenter size-full wp-image-203" title="Capture" src="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture2.png?w=549&#038;h=182" alt="" width="549" height="182" srcset="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture2.png?w=549&amp;h=183 549w, https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture2.png?w=150&amp;h=50 150w, https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture2.png?w=300&amp;h=100 300w, https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture2.png 565w" sizes="(max-width: 549px) 100vw, 549px" /></a></p>
<p>In JavaScript terms this would be written as follows:</p>
<pre>var mySingleton = (function(){

                 // Container Object for singleton configuration variables 
                 Config = {},

                 // Container object for private/protect methods
                 Private = {},

                 // Container object for shared methods
                 Shared = {},

                 // Container object for public methods
                 Public = {}, 

                 // Initialization actions
                 initialization = function(){}();

                 return Public;
 }());</pre>
<p>Not the initialization function that auto executes before the outer singleton is itself executed and returns its result, in this case anything defined within the inner Public namespace. The <em>Config</em> namespace (<em>ns</em>) is for internal properties or variables that are consumed internally by the singleton.  In essence they are protected/private and therefore could exist within the <em>Private</em> ns. I simply prefer to have them at the root of the singleton at the very top for ease is access when trolling through the code. Note that each of the root ns’s are capitalized.  This is because public and private are both reserved words for future use in JavaScript. My choices of the root namespaces are purely personal and of course you could use any you choose such as Protected versus Private.  The primary purpose though is to logically break up your code for readability.  So long as you are consistent in your implementation that is all that matters. Note also that I define a singleton global variable called <em>me</em> to refer to the singleton itself.</p>
<p>You may at this point be questioning the use of the <em>Shared</em> ns but there is an important definition within the object.  Shared methods are those methods that are consumed by both <em>Public</em> and <em>Private</em> methods.  I cannot name the number of times where I have code within <em>Private</em> that needs to be replicated by <em>Public.  </em>Any such code with then go into <em>Shared</em>. The importance of this is for legibility and to reduce code errors during future enhancements to the class. When a developer is asked to modify a <em>Public</em> method on the class and they see that the method points to a <em>Shared</em> method they immediately know that they need to look at how it is called from the <em>Private</em> method.  This helps to reduce noodled code as I like to call it because I hate noodles but love spaghetti! Let’s look at some pseudo code as an example:</p>
<pre>var mySingleton = (function(){
                 var Config = {},
                 Private = {
                                 iAmPrivateMethod1 : function(){
                                                 Shared.method1()
                                 }
                 },
                 Shared = {
                                 method1 : function(){…}
                 },
                 Public = {
                                 method1 : function(){
                                                 Shared.method1()
                                 }
                 }, 
                 initialization = function(){}();
                 return Public;
 }());</pre>
<p>Not something important in the above <em>Public</em> ns.The method1 function is not a direct pointer to to Shared.method1 and it NEVER should be. Public methods should always have their own distinct closure, as the British would say ‘<em>It’s just good form</em>’. Notice something else though, the readability of the code becomes very apparent to the developer. This is an incredibly important aspect of good code development, ‘<em>do not write code for just yourself</em>’. To assume that the code you are presently writing will never have to be modified by you later on or by another developer is simply pure ignorance.  I write by the motto of what comes around goes around, well hopefully someday it will, but that’s not the point.</p>
<p>Now that we have the basics of a good Singleton pattern done, let’s look at how we can use basically the exact same pattern for a class.</p>
<pre>var mySingleton = (function(){
                 var Config = {},
                 Private = {
                                 iAmPrivateMethod1 : function(instance){
                                                 Shared.method1(instance)
                                 }
                 },
                 Shared = {
                                 method1 : function(instance){…}
                 },
                 Public = {
                                 method1 : function(){
                                                 Shared.method1(this)
                                 }
                 }, 
                 initialization = function(){}();

                 var Component = function(config){
                                 // initialization code for instance
                                 Private.iAmPrivateMethod1(this);
                                 return this;
                 };
                 component.prototype.method1 = Public.method1;
                 return Component;
 }());</pre>
<p>As you can see from the above code we now return <em>Component</em> which is of course a function that can be called with the new method as in, <em>myinstance = new mySingleton({config})</em>. All that has really changed is what we are returning and the fact that we now pass around <em>this</em> t represent the instance to the Shared and Private methods.  When the Component is instantiated any private methods should be called to define what is required for your component/widget.  The <em>Private</em> methods are only ever called once on instantiation of the instance.  This is where <em>Private</em> becomes much more apparent. <em>Public</em> methods are also <em>prototyped</em> into the component class and point to the subsequent <em>Public</em> methods.</p>
<p>Granted if you had many methods or parameters within the <em>Public </em>ns you would have a lot of prototype lines after your component definition.  In my next post I will demonstrate how to optimize this process with a single call as well as how to create automatic setters and getters for variables you may wish to expose in your class.</p>
<p>Until then, Cheers<br />
Keith</p>
]]></content:encoded>
					
					<wfw:commentRss>https://keithchadwick.wordpress.com/2012/08/18/singleton-to-prototype-design-guidelines/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/9dcf35ae769cdd4c4ba1ee89bc27974a960d5e247b60340c10a2cacb746ccff1?s=96&#38;d=https%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Chady</media:title>
		</media:content>

		<media:content url="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture2.png" medium="image">
			<media:title type="html">Capture</media:title>
		</media:content>
	</item>
		<item>
		<title>Dynamic Drag Alignment Rulers {elegance sometimes happens}</title>
		<link>https://keithchadwick.wordpress.com/2012/08/10/dynamic-drag-alignment-rulers-elegance-sometimes-happens/</link>
					<comments>https://keithchadwick.wordpress.com/2012/08/10/dynamic-drag-alignment-rulers-elegance-sometimes-happens/#respond</comments>
		
		<dc:creator><![CDATA[Keith Chadwick]]></dc:creator>
		<pubDate>Fri, 10 Aug 2012 15:38:25 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Dynamic Guides]]></category>
		<guid isPermaLink="false">http://keithchadwick.wordpress.com/?p=165</guid>

					<description><![CDATA[In most cases when you work on a product, requests from ‘those who shall be obeyed’ and I don’t mean your mother, are fairly simple.  You are given a functional idea or a behavior to be implemented within a product and you say to yourself ‘yep, no problem’. In other words, not often is there [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In most cases when you work on a product, requests from <em>‘those who shall be obeyed’</em> and I don’t mean your mother, are fairly simple.  You are given a functional idea or a behavior to be implemented within a product and you say to yourself ‘<em>yep, no problem</em>’. In other words, not often is there a challenge. Then there are those rare cases where you come across a task where you need to think outside of the box and we all crave those tasks. Such is a task that I recently faced on a product I work on.  In essence think of the product as an online version of Microsoft PowerPoint, it’s not, but it’s the closest I can think of in the context of the post. The request was to display rulers top, bottom, center, middle, left and right on the selected object. As the object was dragged around the screen when any of these rulers came into alignment on the X or Y of any other object they were to be displayed.  A very similar UI behavior that you would see in PhotoShop, for example.  To make it even more difficult the rulers had to gradually get stronger as it got close to any alignment on any other element on the page on its 3 horizontal or 3 vertical axis!</p>
<p>So imagine the below scenario:</p>
<p><a href="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture.png"><img data-attachment-id="169" data-permalink="https://keithchadwick.wordpress.com/2012/08/10/dynamic-drag-alignment-rulers-elegance-sometimes-happens/capture/" data-orig-file="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture.png" data-orig-size="632,304" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;}" data-image-title="Capture" data-image-description="" data-image-caption="" data-medium-file="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture.png?w=300" data-large-file="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture.png?w=549" class="size-full wp-image-169 aligncenter" title="Capture" src="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture.png?w=549" alt=""   srcset="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture.png 632w, https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture.png?w=150&amp;h=72 150w, https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture.png?w=300&amp;h=144 300w" sizes="(max-width: 632px) 100vw, 632px" /></a></p>
<p>So in the above image there are three shapes.  The blue square has been selected and when any of the 3 horizontal rulers comes into contact with the top, middle or bottom of the other shapes they would need to appear.  Same goes for the vertical if the user where to drag the blue square to the right. So this means that for each element/shape on the page there are 3 vertical and 3 horizontal points to compare to the current points on the actively dragged element, in this case the blue box. Now consider you could have any number of shapes you need to align to! This leads one to the conclusion that any sort of heavy on the fly calculation while dragging will simply destroy performance.  So the question then becomes how can we do this with ZERO calculations/conditions while the selected element is being dragged.  The answer is YES we can and here is how. Just a quick note regarding some of the code, in order to preserve the privacy of the application I am not using the general namespace we use for our toolkit that provides DOM manipulation. However you can easily see how to do this in jQuery, ExtJS etc.  The point is the solution not so much the implementation.<span id="more-165"></span></p>
<h2>Creating the Component</h2>
<p>The first step is to create our basic component framework.  Each piece of functionality I call a component and all of its behavior is neatly encapsulated in the file for easy modification.  Since this component is a singleton we will use Crockford’s singleton patter.</p>
<pre>(function(){

      <span style="color:#808080;"><em>// the canvas element we exist in 
 </em></span>     var canvas = me.element.get('canvas');

      <span style="color:#808080;"><em>// set up the necessary static values</em></span>
      var config = {
         width : canvas.width(),
         height : canvas.height(),
         tolerance : Number(8),
         baseTolerance : ‘k’,
         maxToleranceRange = 'kjihgfedcbabcdefghijk',
         activeTolerance= (config.maxToleranceRange.substring(10-tolerance,9+tolerance)).split(''),
      },

      <em><span style="color:#808080;">// object to hold the map cordinates </span>     
</em>      map = {
         x : null,
         y : null
      },

      <span style="color:#999999;">// <em>Small function to help with setting the colorScale object</em></span>
      getIncrementStyle = function(){},

     <span style="color:#808080;"> // <em>Object to hold dynamic ruler styles</em></span>
      colorScale = {},

      <em><span style="color:#808080;">// create our rulers initially</span> 
 </em>     rulers = {
          top : canvas.append(me.create({cls:'ruler horizontal top'})),
          middle : canvas.append(me.create({cls:'ruler horizontal’})),
          bottom : canvas.append(me.create({cls:'ruler horizontal’})),
          left : canvas.append(me.create({cls:'ruler vertical’})),
          center : canvas.append(me.create({cls:'ruler vertical’})),
          right : canvas.append(me.create({cls:'ruler vertical’}))
      },

      createRulerMap = function(){},
      hideRulers = function(){},
      trackRulers = function(){};

<span style="color:#808080;"><em>      // Bind to the necessary system events
      </em></span>me.subscribe(‘me.element.selected’,createRulerMap);
      me.subscribe(‘me.element.deselected’,hideRulers);
      me.subscribe(‘me.canvas.dragMoved’,trackRulers);
      me.subscribe(‘me.canvas.dragEnd’,hideRulers);  
      return {};
}())</pre>
<p>So all we have done at this point is lay out our basic framework which grabs the width and height of our work area and creates the rulers and assigns them to the rulers object for quick reference later one.  I will discuss the tolerance, maxToleranceRange and baseTolerance a little later on. I have also bound to the basic events in the system. The first one is the element selected which gets fired when an element/shape is selected on the canvas.  This is when we will create our map of other elements. The other is the element deselected and canvas drag end which in both cases will hide the rulers.</p>
<p>Note that in the rulers object where I am created the rulers I am assigning several CSS classes to each.  Here is the basic CSS:</p>
<pre><span style="color:#c0c0c0;">.ruler{
   background-color:transparent;
   border-top-width:1px;
   border-left-width:1px;
   position:absolute;
   display:none;
 }
. horizontal{
   height:0px;
   left:0px;
   border-bottom:none !important;
   border-left:none !important;
   border-right:none !important;
 }
. vertical{
   width:0px;
   top:0px;
   border-right:none !important;
   border-top:none !important;
   border-bottom:none !important;
 }</span></pre>
<p>Now some may argue why create the rulers initially rather than on demand to save DOM weight.  My argument against that is speed.  For this specific behavior we have to ensure no lag when the user clicks on an element and begins to drag.  Otherwise I would create on demand then destroy when no longer needed.</p>
<h2>Creating the X and Y Map</h2>
<p>So based on our initial component layout when an element on our canvas is selected we call the createRulerMap function, this is where our config.baseTolerance comes in. First we need to create a string of the baseTolerance keys based on the config.width  and place in map.y and conversely for map.x.</p>
<pre>map.x = (Array(Number(config.width)).join(baseTolerance).split(‘’);
map.y = (Array(Number(config.height)).join(baseTolerance).split(‘’);</pre>
<p>In essence create an empty array for the necessary width or height then join it with the base tolerance value. So if our base tolerance is <em>k</em> and the width is 1200 we end up with a string of 1200 <em>k’s</em> which we then split back into an array each containing a <em>k</em>. In other words we have a shit load of K’s!</p>
<p>Now let’s assume for now that we have one other element on the canvas that is 100 by 100 pixels in size and is at position X 200 and Y 200. So for this element we need to gets its 3 vertical positions and 3 horizontal positions to align the rulers to by placing those coordinates in our map. Let’s assume we have gotten our element in question and assigned it to the variable element.</p>
<pre>var coords = {
   left : Number(element.x()),
   top : Number(element.y()),
   right : Number(element.x()) + Number(element.width()),
   bottom : Number(element.y()) + Number(element.height()),
   center : 0,
   middle : 0
};
coords.center = coords.left + parseInt(cords.right/2,10);
coords.middle = coords.top + parseInt(coords.bottom/2,10);</pre>
<p>So now we have a coords object with left:200, top:200, right:300, bottom:300, center:250 and middle 250.</p>
<p>Now we come back to the config.activeTolerance and config.maxTolerance values along with the config.tolerance level. If we look at our config.activeTolerance we get the following result hgfedcbabcdefgh, this is based on the config.tolerance level which goes either side of the center of the string for the value specific in config.tolerance. If we look at the map.x presently we have a bunch ok baseTolerance <em>k’</em>s and now we need to insert the active tolerance where <em>A</em> sits at the exact coordinate. Therefore assuming our first X coordinate, coords.left, we need to insert it at position 200 in the map.x string.  What we would want to see is in essence:</p>
<pre>…..kkkkkkkkkhgefdcbabcdefghkkkkkkkkkk….</pre>
<p>However we could have more than one element on the page that we have to account for. What happens if there is another element sitting at X205, we need to account for that. So let’s work on doing our enumeration:</p>
<pre>createRulerMap = function(){

   // This grabs all of canvas elements with a class of moveableElement
   var elements = canvas.filter(‘moveableElement’),

   <span style="color:#999999;">// get the Dom ID of the currently selected element</span>
   currentElementId = me.currentElement.id(),

   setTolerance = function(startPoint,mapCoord){                       
       var startPoint -= config.tolerance;
       for(var point=0;point&lt;(config.tolerance*2)-1;point++){
           map[mapCoord][(point+startPoint)]=activeTolerance[point]&lt;map[mapCoord][(point+startPoint)]?activeTolerance[point]:map[mapCoord][(point+startPoint)];
       };
       return null;
    };

    for(var element = 0; element &lt; elements.length; element++){
        if(elements[element].id()!=currentElementId){
            var coords = {
                left : Number(element.x()),
                top : Number(element.y()),
                right : Number(element.x()) + Number(element.width()),
                bottom : Number(element.y()) + Number(element.height()),
                center : 0,
                middle : 0
            };
            coords.center = coords.left + parseInt(cords.right/2,10);
            coords.middle = coords.top + parseInt(coords.bottom/2,10)
            setTolerance(coords.left,’x’);
            setTolerance(coords.right,’x’);
            setTolerance(coords.center,’x’);
            setTolerance(coords.top,’y’);
            setTolerance(coords.bottom,’y’);
            setTolerance(coords.middle,’y’);
        };
     };
     map.x=map.x.join(‘’);
     map.y=map.j.join(‘’);
 }</pre>
<p>So I think I little explanation of the inline setTolerance may be in order at this point so I will lay it out here. Here it is broken down :</p>
<pre><span style="color:#999999;">// @param : startPoint (integer) position of the value we wish to put the string at;
// @param : mapCoord (string) either the string x or y to indicate what map string we are testing against</span>
function(startPoint,mapCoord){
    <span style="color:#999999;"> // The start point in the array that we wish to check against is the passed coordinate minus the actual tolerance, so if x is 200 it would be 200-8</span>
     var startPoint -= config.tolerance;

     <span style="color:#999999;">// now enumerate through the tolerance * 2 but minus 1 because there is only one center value of A</span>
     for(var point=0;point&lt;(config.tolerance*2)-1;point++){

        <span style="color:#999999;">// set map[ x or y](the loop value plus the startPoint     </span> 
        map[mapCoord][(point+startPoint)] =

        <span style="color:#999999;">// test if the present value in the tolerance string is less than the value presently in the array at point+startPoint. This test works because A is less than B and B is less than C etc.</span>
        (activeTolerance[point]&lt;map[mapCoord][(point+startPoint)])?

        <span style="color:#999999;">// if less then put in the tolerance letter otherwise leave what is in there.</span>
        activeTolerance[point]:map[mapCoord][(point+startPoint)];
     };
     return null;
 };</pre>
<p>So in the case of have 2 objects at X 200 and X 205 you would end up with the following snippet in the map.x string:</p>
<pre>…..kkkkkkkkkhgefdcbabccbabcdefghkkkkkkkk….</pre>
<p>At the end of our function we merge the map.x and map.y arrays back into single strings.</p>
<h2>Tracking the Drag and doing the Magic bits</h2>
<p>Now that we have our X and Y map we need to start tracking the drag behavior and decide when it is appropriate to display the necessary ruler. Before we do that however, we need to create our set of style rules that indicate how to display a ruler. If you remember back to when we created the basic framework for the component I declared an empty object variable entitled colorMap in the global scope of the component. To define this object first I first create a simple function that creates a style based on an integer value passed in, this is placed about the colorScale definition.</p>
<pre>getIncrementStyle = function(x){
  var opacity=(((tolerance-x)+1)/10);
  return ';display:block;border-width:'+x+'px;opacity:'+opacity+';filter:alpha(opacity='+(opacity*100)+')'
}</pre>
<p>Now we define our coloScale:</p>
<pre>colorScale = {
  k:'',
  j:'border-color:#f80708;border-style:solid'+getIncrementStyle(10),
  i:'border-color:#f80708;border-style:solid'+getIncrementStyle(9),
  h:'border-color:#f80708;border-style:solid'+getIncrementStyle(8),
  g:'border-color:#f80708;border-style:solid'+getIncrementStyle(7),
  f:'border-color:#f80708;border-style:solid'+getIncrementStyle(6),
  e:'border-color:#f80708;border-style:solid'+getIncrementStyle(5),
  d:'border-color:#f80708;border-style:solid'+getIncrementStyle(4),
  c:'border-color:#f80708;border-style:solid'+getIncrementStyle(3),
  b:'border-color:#f80708;border-style:solid'+getIncrementStyle(2),
  a:'border-color:#00fffc;border-style:solid;display:block'
}</pre>
<p>Now the getIncrementStyle is completely optional but it simply resulted in less coding for me and allowed me to play with the style a little more easily.  Note the value for <em>k</em> does not specify display of block.  This is because it is our config.baseTolerance. Also remember that the default style for the rulers based on its CSS is rules is display of none.  So when the ruler K is assigned to a ruler it is not displayed. In this style implementation the opacity of the ruler and width increases as a user gets closer to <em>A</em> until we hit <em>A</em> then simple make the ruler a solid dark line.</p>
<p>Now the final method of trackRulers, which is called during the drag event on our canvas element. This now becomes very simple.</p>
<pre>trackMove = function(){
   var currentElement = me.currentElement,
   left = currentElement.x(),
   top = currentElement.y(),
   center = left + parseInt(currentElement.width().2,10),
   middle = top + parseInt(currentElement.height()/2,10),
   right = ((center-left)*2)+left,
   bottom = currentElement.height()+top;

<span style="color:#999999;"><em>   // apply the styles based on the letter found in the map which provides us our color via the colorScale object</em></span>
   rulers.top.attribute('style',colorScale[map.y.substr(top,1)]+';top:'+top+'px;width:'+config.width+'px');
   rulers.middle.attribute('style',colorScale[map.y.substr(middle,1)]+';top:'+center+'px;width:'+config.width+'px');
   rulers.bottom.attribute('style',colorScale[map.y.substr(bottom,1)]+';top:'+bottom+'px;width:'+config.width+'px');
   rulers.left.attribute('style',colorScale[map.x.substr(left,1)]+';left:'+left+'px;height:'+config.height+'px');
   rulers.center.attribute('style',colorScale[map.x.substr(center,1)]+';left:'+xCenter+'px;height:'+config.height+'px');
   rulers.right.attribute('style',colorScale[map.x.substr(right,1)]+';left:'+right+'px;height:'+config.height+'px');
   return null;
}</pre>
<p>So as you can see there are NO calculations going on during the applying of the styles to each of the six rulers. In this implementation I set the map.x and map.y to strings and then used the substr method to get the appropriate letter to get the style.  I am not sure why I simply did not leave it as an array in the first place there by negating the need for a substr calculation. But as they say hind sight is 20/20. Note also when setting the style attribute of each ruler I set horizontal rulers width to the config.width and the vertical rulers to config.height.  Each of these config values where defined at component start up time to the height and width of our working canvas area.</p>
<p>I have uploaded a screen cast of the alignment rulers in action at <a href="http://screencast.com/t/MGjZ1mej3be">http://screencast.com/t/MGjZ1mej3be</a>. In my implementation the users have the ability to always have rulers on when they select an element which the video demonstrates.</p>
<h2>{Elegance Sometimes Happens}</h2>
<p>I added this to the title of this post because I consider this an elegant solution to what may first appear as a simple piece of functionality but when you dig a little deeper you realize it is not. It is often the case that elegance is driven by necessity. In this case I had to find a solution that required as small of a footprint as possible while an element was being dragged around the screen.  This was required in order to ensure there was no choppy behavior that would ruin the user experience. This is one of the key factors of elegance, provide an efficient and usable user experience.  Here are some other factors of code elegance:</p>
<ol>
<li>Encapsulated within a closure,</li>
<li>Does not rely on other components and therefore stands alone,</li>
<li>Easy to read,</li>
<li>Small foot print,</li>
<li>Simple and clean,</li>
<li>Easily customizable,</li>
<li>Ratio between size and complexity vs functional behavior and user experience is high</li>
</ol>
]]></content:encoded>
					
					<wfw:commentRss>https://keithchadwick.wordpress.com/2012/08/10/dynamic-drag-alignment-rulers-elegance-sometimes-happens/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/9dcf35ae769cdd4c4ba1ee89bc27974a960d5e247b60340c10a2cacb746ccff1?s=96&#38;d=https%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Chady</media:title>
		</media:content>

		<media:content url="https://keithchadwick.wordpress.com/wp-content/uploads/2012/08/capture.png" medium="image">
			<media:title type="html">Capture</media:title>
		</media:content>
	</item>
		<item>
		<title>Writing Flexible JavaScript Functions</title>
		<link>https://keithchadwick.wordpress.com/2012/07/22/writing-flexible-javascript-functions/</link>
					<comments>https://keithchadwick.wordpress.com/2012/07/22/writing-flexible-javascript-functions/#respond</comments>
		
		<dc:creator><![CDATA[Keith Chadwick]]></dc:creator>
		<pubDate>Sun, 22 Jul 2012 16:26:47 +0000</pubDate>
				<category><![CDATA[Advanced JS AppDev]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Advanced JavaScript Application Development]]></category>
		<category><![CDATA[applyIf]]></category>
		<category><![CDATA[code structures]]></category>
		<category><![CDATA[javascript developers]]></category>
		<category><![CDATA[Singleton]]></category>
		<category><![CDATA[singleton pattern]]></category>
		<guid isPermaLink="false">http://keithchadwick.wordpress.com/?p=156</guid>

					<description><![CDATA[This is a series of posts that explains some of the fundamental rules for developing complex JavaScript applications. How often have we seen function grow over time with just one more parameter added for that supposed last little piece of functionality we have to add. Far too often I would imagine.  Then add in the [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><em>This is a series of posts that explains some of the fundamental rules for developing complex JavaScript applications.</em></p>
<p>How often have we seen function grow over time with just one more parameter added for that supposed last little piece of functionality we have to add. Far too often I would imagine.  Then add in the new requirement that some of the parameters on the function need to be optional and the next thing you know you are in a world of hurt. There is a basic maxim in any software development, <em>the only constant is change</em>. As a result as a software writer I strive to ensure my code recognizes this maxim along with a couple of others.</p>
<p>Alas for JavaScript, the poor Yorick of languages we all know so well, it does not give us a lot of flexibility in the function object. Unlike other languages, even SQL, functions/methods provide much greater flexibility in there definition, including default values, optional parameters, name parameter calling, e.t.c. It would certainly be nice if we could provide a similar model to JS function calls and definitions. Many a moon a go I started developing in ExtJS and was introduced to a very simple method called Ext.apply and Ext.applyIf. In essence these methods take two objects as parameters and merge them into one. So if you call Ext.apply({a:1,b:2},{c:1}) you would get back {a:1,b:2,c:1}.  Sounds simple enough right? The applyIf works in the same fashion but makes a test in the receiving object to see if the property already exists and if so does not over write it. This is a very simple piece of code that we can look at below:</p>
<pre><span style="color:#888888;">function applyIf(objectTo,objectFrom){</span>
<span style="color:#888888;">              if(objectTo){</span>
<span style="color:#888888;">                          for(var property in objectFrom){</span>
<span style="color:#888888;">                                      if(typeof objectTo[property] == 'undefined' ){</span>
<span style="color:#888888;">                                                  objectTo[propety] = objectFrom[property];</span>
<span style="color:#888888;">                                      }</span>
<span style="color:#888888;">                          }</span>
<span style="color:#888888;">              }</span>
<span style="color:#888888;">              return objecTo;</span>
<span style="color:#888888;">  }</span></pre>
<p>So in essence, enumerate through the properties in objectFrom and if the property does not exist in the objectTo then add the property and its value from the objectFrom. So what does this have to do with functions you are probably asking? Let’s have a look at a mythical function as an example</p>
<pre><span style="color:#888888;">function doSomethingCool(</span>
<span style="color:#888888;">              // width of element</span>
<span style="color:#888888;">              width,</span>
<span style="color:#888888;">              // height of element</span>
<span style="color:#888888;">              height,  </span>
<span style="color:#888888;">              // text of element</span>
<span style="color:#888888;">              text,</span>
<span style="color:#888888;">              // optional x and y, element type and style string</span>
<span style="color:#888888;">              ,x,y,elType,style){…do some stuff}</span></pre>
<p>Looks simple enough but what’s with the four of optional parameters at the end of the function.  As you well know from in your function code you end up with a bunch of if statements along the lines of <em>if(x===undefined){x=0}</em>.  This of course gets to be a pain in the code rear. Now let’s change our function to accept to a single parameters as an object.</p>
<pre><span style="color:#888888;">function doSomethingCool(config){</span>
<span style="color:#888888;">            config=applyIf(config,{</span>
<span style="color:#888888;">                          width : null,</span>
<span style="color:#888888;">                          height : null,</span>
<span style="color:#888888;">                          text : ’’,</span>
<span style="color:#888888;">                          x : 0,</span>
<span style="color:#888888;">                          y : 0,</span>
<span style="color:#888888;">                          elType : ‘div’,</span>
<span style="color:#888888;">                          style : ‘position:relative’</span>
<span style="color:#888888;">              })</span>
<span style="color:#888888;">… do some stuff</span>
<span style="color:#888888;">  }</span></pre>
<p>So now in our doSomethingCool function we can easily default each parameter in our function and reduce the amount of <em>if</em> conditions to test for them.  By defaulting each of our values we also reduce the risk of errors being introduced by bad callers.</p>
<p>This may seem like a simple idea but it has a couple of extremely important advantages.  How many times have you had to go and look up a function you wish to call to check the order or the parameters? I would guess far too many times. Using a single parameters object order of the values in the object to not matter. But there is a far more important reason to use this method and that is in regards to the caller.  In the standard function design you would see some code calling the method like thus:</p>
<pre><span style="color:#888888;">doSomethingCool(10,10,’my text to display’,undefined,undefined,’span’)</span></pre>
<p>Really does not really tell you much when you look at it does it. When another developer has to go through your code the above line tells him/her absolutely nothing and forces them to go and look at the doSomethingCool function to determine what 10 and 10 is and why are there two undefined. Now lets make the same call to the function using the config object parameters:</p>
<pre><span style="color:#888888;">doSomethingCool({</span>
<span style="color:#888888;">              width : 10,</span>
<span style="color:#888888;">              elType : ‘span’,</span>
<span style="color:#888888;">              height : 10,</span>
<span style="color:#888888;">              text : ‘my text to desolay’ </span>
<span style="color:#888888;">  })</span></pre>
<p>Looks a lot better doesn’t it! Not only is it very clear on what we are passing, we also did not need to add in a bunch of undefined definitions to get to the elType parameter. Notice also that in the above the order of object properties do not matter either.</p>
<p>A couple of noteworthy things about implementing your functions this way. If you need to add another parameter to your doSomethingCool function you can simply default it the default config object that is applied without any concern of impacting existing callers.  Another great benefit is code readability. How often have you had to take someone else’s code over? Now imagine reading through that code and seeing all these clearly understandable calls.  Not only does it benefit you when you need to revisit something but it will benefits the next developer who has to hit your code to make a modification.</p>
<p>In the next part of the series I will be exploring Crockford’s singleton pattern vs the prototypal pattern and how to merge, extend them and organize code.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://keithchadwick.wordpress.com/2012/07/22/writing-flexible-javascript-functions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/9dcf35ae769cdd4c4ba1ee89bc27974a960d5e247b60340c10a2cacb746ccff1?s=96&#38;d=https%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Chady</media:title>
		</media:content>
	</item>
		<item>
		<title>Hide your JavaScript from Firebug and other Dev Tools</title>
		<link>https://keithchadwick.wordpress.com/2011/09/01/hide-your-javascript-from-firebug-and-other-dev-tools/</link>
					<comments>https://keithchadwick.wordpress.com/2011/09/01/hide-your-javascript-from-firebug-and-other-dev-tools/#comments</comments>
		
		<dc:creator><![CDATA[Keith Chadwick]]></dc:creator>
		<pubDate>Thu, 01 Sep 2011 18:41:47 +0000</pubDate>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Anonymous Function]]></category>
		<category><![CDATA[Module Pattern]]></category>
		<guid isPermaLink="false">http://keithchadwick.wordpress.com/?p=146</guid>

					<description><![CDATA[I write just about everything now a days in Module Pattern, ta Mr. Crockford.  However one of my biggest worries in developing web applications is other people like me.  You know, the geek that hits your web page and immediately hits F12 in Firefox to see what&#8217;s going on, what framework your using and inevitably starts [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I write just about everything now a days in Module Pattern, ta Mr. Crockford.  However one of my biggest worries in developing web applications is other people like me.  You know, the geek that hits your web page and immediately hits F12 in Firefox to see what&#8217;s going on, what framework your using and inevitably starts doing console.log statements just for fun.  For the serious hacker, once they find those exposed AJAX methods and what to push, life can become a real nightmare for you server not to mention the developers as they feebly attempt to explain to management &#8216;that&#8217;s just the way it is&#8217;.</p>
<p>So after several days of adding to a JavaScript Coding Standards document explaining Design Patterns at my most recent job, it got me to thinking <em>&#8216;how can I protect the code yet not loose any flexibility that the Module Pattern provides?</em>&#8216; It&#8217;s one of those problems you think about when you go to sleep and are still going at it when you awake at sunrise and stubbornly refuse to get up despite your brain saying &#8216;get at it lad&#8217; just to add to the encouragement from your bladder. Like many problems you fiddle about with code constantly hitting F5 in your browser as your brain goes into overdrive as it is fully convinced this has to be possible!  Then the solution hits you and you exclaim to yourself &#8216;<em>man that&#8217;s so f&#8217;ing obvious and simple what was I thinking!!</em>&#8216;.  The solution is wrap your singleton in an anonymous function &#8211; duh! So here you go enjoy:</p>
<pre style="color:white;background-color:black;font-family:Courier New;padding:10px 10px 10px 50px;">(function(){

	var myApp =function(){
		//add your application code here as you normally would
	}();

}());</pre>
<p>Yes its that simple!  In essence wrap your application in an anonymous function.  So long as all of your child classes within myApp reference myApp.whatever then no problem.  Give it a try then hit your page with Firebug or any other dev tool and look in vain for myApp, you will not find it.</p>
<p>But this introduces a problem.  Your busy working on your highly complex web app and you <strong>need</strong> to be able to do console.log statements to my app. Well no problem:</p>
<pre style="color:white;background-color:black;font-family:Courier New;padding:10px 10px 10px 50px;">(function(){

	var DEBUG = true,

	var myApp =function(){
		//add your application code here as you normally would
	}();

	if(DEBUG){
		window.MyApp=myApp
	}
}());</pre>
<p>Now you can debug to your hearts content and when ready for the big release set your DEBUG switch to false.  So now the next issue, &#8216;<em>ya that&#8217;s all very nice Keith but I NEED to expose some of my methods for consumption by 3rd parties</em>&#8216;.  Again very simple:</p>
<pre style="color:white;background-color:black;font-family:Courier New;padding:10px 10px 10px 50px;">(function(){

	var DEBUG = true,
	EXPOSED_NS = 'ForTheCosumer';

	var myApp =function(){
		//add your application code here as you normally would
		return {
			DoSomething 	: function(){},
			DoSomethingElse : function(){}
		}
	}();

	// expose my public methods
	window[EXPOSED_NS]={
		doSomething 	: myApp.DoSomething,
		doSomethingElse	: myApp.DoSomethingElse
	};

	if(DEBUG){
		window.MyApp=myApp
	}
}());</pre>
<p>So thats about all there is to it.  In my next post I will deal with another contentious issue with the Module Pattern. Code segmentation into separate files and how to get them into your now hidden application.</p>
<p>Cheers</p>
<p>Keith</p>
]]></content:encoded>
					
					<wfw:commentRss>https://keithchadwick.wordpress.com/2011/09/01/hide-your-javascript-from-firebug-and-other-dev-tools/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/9dcf35ae769cdd4c4ba1ee89bc27974a960d5e247b60340c10a2cacb746ccff1?s=96&#38;d=https%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Chady</media:title>
		</media:content>
	</item>
		<item>
		<title>O Refio, Refio, wherefore art thou Refio (ExtJS Design Patterns)</title>
		<link>https://keithchadwick.wordpress.com/2010/10/03/extjs-design-patterns/</link>
					<comments>https://keithchadwick.wordpress.com/2010/10/03/extjs-design-patterns/#respond</comments>
		
		<dc:creator><![CDATA[Keith Chadwick]]></dc:creator>
		<pubDate>Sun, 03 Oct 2010 18:15:47 +0000</pubDate>
				<category><![CDATA[ExtJS]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<guid isPermaLink="false">http://keithchadwick.wordpress.com/?p=140</guid>

					<description><![CDATA[For longer than I can remember I have been writing complex data centric applications and trying to leverage JavaScript  and DOM to do more and more of the work.  In the early days, yes pre this decade, we had to do a lot of the heavy lifting ourselves.  In today’s world we have a wide [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>For longer than I can remember I have been writing complex data centric applications and trying to leverage JavaScript  and DOM to do more and more of the work.  In the early days, yes pre this decade, we had to do a lot of the heavy lifting ourselves.  In today’s world we have a wide range of frameworks we can choose from.  All of these provide for different object implementations with the same goal in mind.  ExtJS is the most fully fledged out framework to date but there are competitors not far behind, for example Javeline.  Like many implementations it will come down to developer adoption which is often a result of how well that company caters to developers.  But getting into why a framework gets adopted is for a future blog post.  The purpose of this post is to talk about design patterns of an application with a focus on ExtJS.  In many cases I get dropped into the middle of an application development life cycle and in most of these cases I have noted a consistent implementation which in ‘my’ opinion lacks certain elegance. </p>
<p>Since I am very evidently sticking my nose out I had best explain ‘What is Elegence?’ In terms of a JS implementation the object model should provide for an obvious segmentation of functional areas that reflect their purpose and the interface itself.  Having an overly flattened object model simply makes it confusing for developers to inherit the code base and work with it.  I usually layout my base class with the following structure. </p>
<ul>
<li>.ui<br />
Contains all of the components that make up the base interface.  Most often this a direct pointer to the created viewport.</li>
<li>.user<br />
The user class holds the context of the currently logged in user and any methods for login, logout, options etc.  It will contain interface components/methods but most often these are modal dialog in nature so do not impact on UI. The user class should also provide for permission methods.</li>
<li>.remote<br />
The remote class is most often a function and is in charge of ALL remote calls whenever possible.  It is important that an attempt be made to push all of your remote REST calls or any server requests through a single point of entry/exit.  In some cases this is not possible, for example with a tree control or with a panel with autoLoad set, but these are special circumstances.</li>
<li>.component<br />
The component object is a holder for specific component objects that your interface supports. It relies on both ui and user classes.  Often I have a common or core subclass within component that provides for common functionality that is shared amongst components.</li>
<li>.util<br />
A catch all class for methods that support all the other primary classes.</li>
<li>.config<br />
I flip flop on this one frequently.  The config object is used to store configuration objects that are commonly used throughout the application.  For example default panel configs that are applied with Ext.applyIf within functions.  I flip/flop on this one because with it being exposed it opens opportunity for nosey hackers to fiddle with it and introduce behaviors.</li>
</ul>
<p>In many cases I see very large flattened object models and exposed components because for some very bizarre reason people have not picked up on the <strong>ref</strong> property of a container config in ExtJS.  <strong>Ref</strong> is your best friend and simplifies your life.  As you may well know one of the major challenges in ExtJS or any JS application is maintaining a reference to that object you just created.  Sometimes we drop in our on ID so that we can use Ext.getCmp(‘thatDangObject’) or pre-create a id with Ext.id, add it to the config and store the id somewhere for later retrieval.  Well by using the ref function you do not need to.  For example let’s look at a standard 3 panel viewport with a North, South, Center layout. </p>
<p>First off you will note __root.ui, __root is a reference to the base class of the application but I will get to that a little later.  For now you can assume that myapp.ui is now a pointer to the created ExtJS viewport object.  If you were to use FireBug and look at myapp.ui within the DOM explorer you would see under myapp.ui, _panelNorth, _panelWest and _panelCenter.  A quick comment, if you have not heard of Firebug stop reading this article, get it, learn how to use then by all means come back and read the rest. A note about my use of the underscore in the ref property.  I use this for two reasons.  One, I know that the ref name I come up with will NOT conflict with any ExtJS property and more importantly they show at the top of the list in the DOM explorer when expanding the object. </p>
<pre style="border:2px solid silver;color:navy;background-color:#f1f0f0;padding:10px;"><code>__root.ui= new Ext.Viewport({
layout: 'border',
items: [
{region:’north’, ref:’_panelNorth’},
{region:’west:’, ref:’_panelWest’},
{region:’center’,ref:’_panelCenter’}
]});</code></pre>
<p>With ref one of the very spectacular things you can do is move it up the object hierarchy by the use of ‘..\’. So for example if I had a tbar in the _panelNorth and I want to have it exist within the DOM hierarchy directly under myapp.ui I could add in ref:’..\_topTbar’ in the tbar config within the north panel.  There are cases you may want to do this but remember if you do then you loose your logical object flow in your code which means as a result you had better name it something very logical.  For example really which is better of the below two: </p>
<p>                myapp.ui._panelNorth._topToolBar<br />
                myapp.ui._panelNorthTopToolBar </p>
<p>Personally I prefer the first case because that little ol’ dot tells me something directly where as in the later example I am trusting the name to indicate it.  I will defer to dot whenever I can! </p>
<p>‘<strong>Dude it’s an object no need to wrap it more’</strong>, this is one of my favorite issues I see in ExtJS development.  Creating components that wrap ExtJS components because of the need to track some aspect of that component.  It is kind of akin to that annoying Uncle who thought it was cute to wrap a small present inside a big box that was also wrapped.  It’s not funny and it just adds <span style="text-decoration:underline;">waste<strong>!</strong></span><strong> </strong> Waste is the important word here.  Not only are you wasting time but you’re wasting memory and my time while I try to figure out what the hell you are trying to do.  You can add anything to an ExtJS config object and it will show up as part of that object.  Take for example the following panel config: </p>
<pre style="border:2px solid silver;color:navy;background-color:#f1f0f0;padding:10px;"><code>__root.ui._panelCenter.add({
	xtype:’panel’,
	ref:’_panelForSomething’,
	_myProperty1:’abc’,
	_myProperty2:’def’,
	_myMethod:function(){callmyprivateMethod(this)}
})</code></pre>
<p>Now when I want to get to _myProperty in this added panel I can simply say myapp.ui._panelCenter._panelForSomething._myProperty1 and I get <strong>abc</strong>.  What I often see is the reverse where a class has been created that contains the control and a lot of extra code expended to make available certain properties/methods of the container available for consumption.  If you are comfortable with the <span style="text-decoration:underline;">security</span> issues of this then make use of that ExtJS object.  There is a reason they have the functions Ext.apply and Ext.applyIf, read up on them as they are another best friend of ExtJS development.  A small comment on the use of underscore!  I realize and recognize that this is not a recommended implementation according to Mr. Crockford but I would argue this point with him with some zealousness and perhaps a slight grin on my face that I am arguing with Douglas Crockford! </p>
<p>I mentioned the term security and this leads me to my next point. Not everything needs to be a publicly accessible method or property. Object scope is an incredibly important aspect of any complex application design and making EVERYTHING scoped at the object level is just asking for some pimple faced annoying genius kid to go nutty on your application in Firebug and post it up to the world in some sense of accomplishment over your lack of thinking!  This is where ‘design patterns’ come in, there are many, most notably Douglas Crockford’s. It is Crockford’s implementation that is used witin ExtJS for components. I could probably dedicate an entire book or a least a lengthy blog post to JS design patterns for the purposes of this discussion I will outline two that I use primarily.  The first is a basic class that one instance of will be created for the purpose of service the application. </p>
<pre style="border:2px solid silver;color:navy;background-color:#f1f0f0;padding:10px;"><code>
function myClass(scope){

	// private variables
	var _me = this;			// internal reference
	var __root = scope		// constructor reference
	var pTermLength = null		// exposed property

	// private methods
	function doSomething(){};

	// shared methods
	function pIAmASharedMethod(){};

	// shared property setters/getters
	function pSetTermLength(v){pTermLength=v};
	function pSetTermLength(){return pTermLength};

	// public methods/properties
	this.doSomething=pIAmASharedMethod;
	this.getTermLength=pGetTermLength;
	this.setTermLength=pSetTermLength;
	this.letItAllHangOut=new Number(1)
}
</code></pre>
<p>Notice that in this class we only have 3 exposed or public methods and one exposed variable name.  I like to have my public methods point to private functions.  This allows for internal/private functions to call them directly without the use of the <em>this</em> reserved word.  It also means that your exposed methods and properties are simply pointers.  When using this style of implementation it is important that <strong>you</strong> come to a consistent naming convention on the function and variable declarations. With regards to variables the basic rule of thumb is you should <strong>not</strong> let them hang out there publicly but rather create public setter and getter methods.  If the variable has a direct impact on the behavior of the class and typing is important then don’t just let it hang out there for consumption and override. Using a getter/setter implementation allows for you to check type and value scope of the var before fubarring your class.  Now I will fall back to Mr. Crockford and his implementation which is slightly different and serves a different purpose.  Remember the above example is for a class that will behave more like a singleton. ‘Why not a singleton’ you ask, well I will get to that next.  Mr. Cockford would say the above implementation should be done thus: </p>
<pre style="border:2px solid silver;color:navy;background-color:#f1f0f0;padding:10px;"><code>
function myClass(scope){

	// private variables
	var _me = this;			// internal reference
	var __root = scope		// constructor reference
	var pTermLength = null	// exposed property

	// private methods
	function doSomething(){};

	// shared methods
	function pIAmASharedMethod(){};

	// shared property setters/getters
	function pSetTermLength(v){pTermLength=v};
	function pSetTermLength(){return pTermLength};

	// public methods/properties
	return {
		doSomething : pIAmASharedMethod,
		getTermLength : pGetTermLength,
		setTermLength : pSetTermLength,
		letItAllHangOut : new Number(1)
	};
}
</code></pre>
<p>Note that in this case that when creating an instance of the class it returns an object which in essence does the same thing as the earlier class.  The difference is that the return statement returns an object which is in essence a singleton or in this case a singleton expressing the instance of the object.  My problem is that a singleton implementation is extremely limiting in its internal scope referencing.  You must follow the object convention of using commas and can NOT have locally scoped variables within the return object.  The argument would be that you should <span style="text-decoration:underline;">not</span> have locally scoped variables within the returned object but I feel that is limiting.  This leads me to the second style of class implementation and for this let’s try and use a real world example to show why.  Let’s assume we have an application with a standard viewport.  On the left is a tree in which a bunch of users are listed.  In the center panel we have a tabpanel implementation.  When the user selects a user in the tree we have to create a new tab panel for that user.  Obviously then we are going to have a class that manages the interface for the selected user in the tab panel.  In Mr. Crockford’s implementation we would have a class which we would create an instance of and part of its initialization would be to create the interface.  Problem here though is we now have to write a bunch of code to manage the instances of user we have created.  Where should that code go then within are architecture?  Logically it should go in the user class itself but that class is only designed to manage an instance of a user not instances. </p>
<p>Remember way back in this article I had a child class of off base entitled component.  Well this is where out component would go.  Let’s look at the code for our user class that manages multiple instances: </p>
<pre style="border:2px solid silver;color:navy;background-color:#f1f0f0;padding:10px;"><code>
function myClass(scope){

	// private variables
	var _me = this;			// internal reference
	var __root = scope		// constructor reference
	var pTermLength = null	// exposed property
	var instances=[];

	// private methods
	function doSomething(){};
	function createInterface(instance){
		// create the interface for the instance and store
		instances.push(__root.ui.center.add(instance.config))
	}

	// shared methods
	function pIAmASharedMethod(instance){};
	function pcloseAllUsers(){
		Ext.each(instances,function(o){
			__root.ui.center.hideTabPanel(o.id)
		})
	}

	// shared property setters/getters
	function pSetTermLength(v){pTermLength=v};
	function pSetTermLength(){return pTermLength};

	// public methods
	this.closeAllUsers=

	// start component
	this.component=function(config){
		var _me=this;				// pointer to this instance
		var myTermLength=1			// local instance variable

		function initialize(){
			createInterface(_me)
		};
		this.config=config
		this.doSomething = function(){pIAmASharedMethod(_me)},
		this.getGlobalTermLength = function(){return pGetTermLength()},
		this.setGlobalTermLength = function(v){pSetTermLength(v)},
		this.getTermLength=function(){return myTermLength},
		this.setTermLength=function(v){myTermLength=v}
		this.letItAllHangOut = new Number(1)		

		// init instance
		initialize();

		return _me;
	}; //-&gt; end component
}
</code></pre>
<p>Notice a couple of things: </p>
<ol>
<li>Initially we created a single instance of this class with myapp.component.user=new myClass(this) where this is a pointer to the root of our application myapp.  This means that the class can now get to any of our child classes, such as ui via the locally scoped variable __root.</li>
<li>When we want to create a new user interface we call new myapp.component.user.component({some config})</li>
<li>The component creates a locally scoped variable entitled _me that points to its self. On creation the internal initialize function is called which in turn calls the base class createInterface function and passes an instance of its self.</li>
<li>Since createInterface is passed a pointer to the instance and instance has a public property that points to the passed config our createInterface method in the base class can now say create the tab panel using the passed instance.config.  The createInterface stores a pointer to it in a LOCALLY scoped array.</li>
<li>When creating the component it returns a reference to itself for further manipulation.</li>
</ol>
<p>Now a couple of other things.  Let’s assume that the config we pass to the component creation contains a ref value, for example it is set to ‘userABC’. Now if we want to get to it publicly through our object hierarchy it would be myapp.ui._panelCenter.userABC.  This of course would only get us to the ExtJS component.  Now is where things can get a bit confusing and there are several approaches you can use depending on your requirement. </p>
<p>For arguments sake let’s assume you <strong>want</strong> to be able to get to that control directly then you could do this.  Remember you can add anything to that config! </p>
<pre style="border:2px solid silver;color:navy;background-color:#f1f0f0;padding:10px;"><code>
// start component
	this.component=function(config){
		var _me=this;				// pointer to this instance
		var myTermLength=1			// local instance variable

		function initialize(){
			createInterface(_me)
		};
		this.config=config
		config._doSomething = function(){pIAmASharedMethod(_me)},
		config._getGlobalTermLength = function(){return pGetTermLength()},
		config._setGlobalTermLength = function(v){pSetTermLength(v)},
		config._getTermLength=function(){return myTermLength},
		config._setTermLength=function(v){myTermLength=v}
		config._letItAllHangOut = new Number(1)		

		// init instance
		initialize(config)
	}; //-&gt; end component
</code></pre>
<p>Now we have added our public component methods as part of the config of the ExtJS object.  So now I can say myapp.ui._panelCenter.userABC._doSomething() </p>
<p>The advantage of doing this is of course the base user class when enumerating through its array of component instances can access each of the public methods of each since they are part of the ExtJS component. </p>
<p>How you decide to implement these types of components comes down to what your needs are.  Questions such as does this need to be accessible from other classes, what are the security risks of being public exposed, do I need a component or will a singleton do?  Should my controller base class provide all the functionality needed? </p>
<p>In my next post I will discuss the overuse of Ext.extend and Observable. When to use it and when to not use it. </p>
<p>One last thing to think on… config.instance=_me!!  Now you’re going down the rabbit hole and saying to yourself ‘I should have taken the blue pill’  Try it and see what you see in Firebug DOM J </p>
<p>Until then….cheers </p>
<p>Keith Chadwick</p>
]]></content:encoded>
					
					<wfw:commentRss>https://keithchadwick.wordpress.com/2010/10/03/extjs-design-patterns/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		
		<media:content url="https://0.gravatar.com/avatar/9dcf35ae769cdd4c4ba1ee89bc27974a960d5e247b60340c10a2cacb746ccff1?s=96&#38;d=https%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96" medium="image">
			<media:title type="html">Chady</media:title>
		</media:content>
	</item>
	</channel>
</rss>
