<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">

    <title type="text">Studio Koi Blog</title>
    <subtitle type="text">Studio Koi Blog:</subtitle>
    <link rel="alternate" type="text/html" href="http://studiokoi.com/blog/index/" />
    <link rel="self" type="application/atom+xml" href="http://studiokoi.com/code/atom" />
    <updated>2010-08-18T12:49:11Z</updated>
    <rights>Copyright (c) 2010, Greg Ferrell</rights>
    <generator uri="http://www.expressionengine.com/" version="2.1.0">ExpressionEngine</generator>
    <id>tag:studiokoi.com,2010:08:17</id>


    <entry>
      <title>The Cobbler&#8217;s assistant&#8217;s children have no shoes, either</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/the_cobblers_assistants_children_have_no_shoes_either" />
      <id>tag:studiokoi.com,2010:blog/index/1.56</id>
      <published>2010-08-17T22:48:10Z</published>
      <updated>2010-08-18T12:49:11Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="News"
        scheme="http://studiokoi.com/code/category/News"
        label="News" />
      <content type="html"><![CDATA[
        <p>Last week we released a new design for <a href="http://solspace.com">Solspace</a>. Everything went over pretty well, aside from some small hiccups. Not bad for a new site design launch. I am quite proud that we have a new face as we are very dedicated to our work and our old website just didn&#8217;t reflect that. Good change.</p>

<p>Like the <a href="http://www.solspace.com/blog/entry/cobblers_children_have_no_shoes/" title="Solspace - Cobblers’ Children Have No Shoes"> blog post about the redesign</a> suggests, it is hard to work on your on self image when you are spending all of your time trying to make sure everything else is taken care of. Customer service, bug fixes, and fresh products are first and foremost, because that&#8217;s what&#8217;s most useful to customers. However, a good face is very important.</p>

<p>This sort of brings me to this website. I added a new design recently, but didn&#8217;t spend much time on it, as i don&#8217;t usually have much to give because I am trying to make my work at Solspace the best it can be. It really needed the update, though because it was just slow and hard to read. However, it&#8217;s still not to my liking and will probably redesign again in the coming months and start to chronicle a bit more of what i am working on now.</p>

<p>I still want to share knowledge and pay forward the help so many others have given me over time.&nbsp; <img src="http://codeblog.studiokoi.com/images/smileys/wink.gif" width="19" height="19" alt="wink" style="border:0;" />
</p> {extended}
      ]]></content>
    </entry>

    <entry>
      <title>Ghetto tag limiting in EE 2</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/ghetto_tag_limiting_in_ee_2" />
      <id>tag:studiokoi.com,2010:blog/index/1.54</id>
      <published>2010-05-16T00:33:39Z</published>
      <updated>2010-05-21T20:07:41Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="ExpressionEngine"
        scheme="http://studiokoi.com/code/category/ExpressionEngine"
        label="ExpressionEngine" />
      <content type="html"><![CDATA[
        <p>So, I finally decided to take the time to update my website to the ExpressionEngine 2.0 Beta.</p>

<p>This means that some of my stuff is going to be broken, but I can live with that. Going to improve how things are done and use better components this way. But the transition had a couple of small hiccups&#8230;</p>

<p>Step one, however, is that I use a tag limiter on the front page because I am too lazy to copy paste paragraphs into the summary field. Besides, i shouldn&#8217;t have to. This is a CMS right? I should only have to work once. Well, the tag limiter i was using was broken, so instead of working too hard, I made this ghetto tag limiter with in template php.</p>

<pre class="brush: php">
&#36;content = &lt;&lt;&lt; END_OF_CONTENT
{body}

END_OF_CONTENT;
	
&#36;content_array = explode('&lt;/p&gt;', &#36;content);

echo &#36;content_array[0] . '&lt;/p&gt;' . &#36;content_array[1] . '&lt;/p&gt;';
</pre>

<p>Pretty simple, and as you can see, quite effective. Though, I will have to make this into an addon for later. That is my job now <img src="http://codeblog.studiokoi.com/images/smileys/smile.gif" width="19" height="19" alt="smile" style="border:0;" />.</p> {extended}
      ]]></content>
    </entry>

    <entry>
      <title>Simple argument defaults in JavaScript</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/simple_argument_defaults_in_javascript" />
      <id>tag:studiokoi.com,2009:blog/index/1.52</id>
      <published>2009-09-27T03:51:50Z</published>
      <updated>2010-05-21T20:37:51Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="JavaScript"
        scheme="http://studiokoi.com/code/category/JavaScript"
        label="JavaScript" />
      <content type="html"><![CDATA[
        <p>In many other interpreted programming languages like: Python, PHP, ActionScript 3.0, etc., you can have defaults to arguments that do not get passed to functions. In the three a fore mentioned languages, it's as easy as saying arg = 'default' inline in the function definition. This however is not available in the JavaScript interpreter. (It might be in ECMAScript 5, though.) But that can easily be remedied with a simple helper function.</p>

<p>I have met other programmers that find it ridiculous that you have to create features in JavaScript that are built into other languages. They use that to put down JavaScript and call it a terrible language. However, I think that's part of what makes JavaScript so great. JavaScript, though not as powerful in features as some other languages, offers enough flexibility and expressiveness that you can create what you feel that you are missing. Lets take a look at the problem and see how easy we can remedy it.</p>

<p>First, look at a basic function that is about the same in most C based languages:</p>

<pre class="brush: js">
function foo(arg1, arg2)
{
	return arg2;
}
foo('one', 'two'); 	// returns 'two'
foo('one'); 		// undefined
</pre>

<p>In the above example, you MUST have a second argument passed to the function, or you get an error. Some people remedy that like so:</p>

<pre class="brush: js">
function foo(arg1, arg2)
{
	//check for defaults
	var arg1 = arg1 || "one";
	var arg2 = arg2 || "two";
	
	return arg2;
}
foo('one', 'also two');	// returns 'also two'
foo('one'); 		// returns 'two'
</pre>

<p>The above works OK, but is a little cumbersome. The logical or operator or '||' (double pipe) in JavaScript returns the first item if it is truthy, or the second item no matter what. Usually, you'll only see that in if statement blocks, but this idiom works well as an either or return value and is used such. <strong>NOTE: This idiom would not work well with any value passed that is falsey: A blank string, an integer 0, boolean false, etc., because it returns the second item when the first argument is a falsey value and not just undefined or null.</strong></p>

<p>The above fix is lousy, though, because it becomes a mess when you have more than one optional argument. Take the following example that uses an object literal as the only argument and allows for passing only the arguments you want to send:</p>

<pre class="brush: js">
function foo(args)
{
	//check for defaults
	args.arg1 = args.arg1 || "one";
	args.arg2 = args.arg2 || "two";
	args.arg3 = args.arg3 || "three";
	
	return args.arg2;
}
foo({"arg2":"also two"});	// returns 'also two'
foo({"arg1":"also one"});	// returns 'two'
</pre>

<p>The above works a little better because it allows you to pass only the arguments you want without having to null out others. It still presents ugly default checking and the same issues with falsey statements. We can use the same idea, but implement it far better with a simple function that will take a set of defaults and replace passed items over it and return the a useable object with all defaults and arguments in one.</p>

<pre class="brush: js">
function defaults(def, arg)
{
	for(var i in arg)
	{
		def<i> = arg<i>;
	}
	return def;
}
</pre>

<p>The above code takes exactly two arguments, the first being an object with the default 'name:value' pairs for your arguments. The second one is the argument object actually passed to the defaults function. The second object is iterated over and all of its values are placed over the default ones and the default object is returned. This will give a usable object with defaults in place and actual passed arguments where presented.</p>

<p>How it actually works can be displayed as such:</p>

<table class="inline-table">
	<thead>
		<tr>
			<th>Defaults Object</th>
			<th>Arguments Object</th>
			<th>Resulting Object</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>"one"</td>
			<td>(nothing passed)</td>
			<td>"one"</td>
		</tr>
		<tr>
			<td>"two"</td>
			<td>"also two"</td>
			<td>"also two"</td>
		</tr>	
		<tr>
			<td>"three"</td>
			<td>(nothing passed)</td>
			<td>"three"</td>
		</tr>
	</tbody>
</table>

<p>Lets see it in action:</p>

<pre class="brush: js">
function foo(args)
{
	args = defaults({
		arg1 :"one",
		arg2 :"two",
		arg3 :"three"
	}, args);
	
	return args.arg2;
}
foo({"arg2":"also two"});	// returns 'also two'
foo({"arg1":"also one"});	// returns 'two'
</pre>

<p>The default arguments are much less cluttered and were properly applied to items missing from the passed args object. Armed with our new defaults function and knowledge of how to use a single object to send all arguments, we can now safely send only select arguments, falsey or not, and have default arguments take care of the rest.</p>

<p>Enjoy!</p> {extended}
      ]]></content>
    </entry>

    <entry>
      <title>I Won Frank Peak&#8217;s Twitter Contest!</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/i_won_frank_peaks_twitter_contest" />
      <id>tag:studiokoi.com,2009:blog/index/1.51</id>
      <published>2009-09-09T06:18:00Z</published>
      <updated>2009-09-09T10:17:13Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="News"
        scheme="http://studiokoi.com/code/category/News"
        label="News" />
      <content type="html"><![CDATA[
        <p>If you like art at all and you don't already follow <a href="http://twitter.com/frankpeak" title="Frank Peak on Twitter">Frank Peak</a> on twitter, or visit <a href="http://frankpeak.com" title="Frank Peak's Online Portfolio">his website</a>, I would highly recommend it. He periodically has "Almost Daily Drawings" that are his random doodles and concept drawings. His <a href="http://frankpeak.com/portfolio.html" title="Portfolio - Frank Peak">portfolio</a> is also very, VERY good.</p>

<p>Frank is a very skilled illustrator and 3D artist who recently held a <a href="http://www.frankpeak.com/blog/?p=154" title="BUTTON PACK GIVE AWAY! - Frank Peak">contest</a> on Twitter for people who would retweet him. I was one of the fortunate winners of the contest.</p>

<p>Included in the package was a SWEET envelope that Frank personalized for each winner with random (and rather cute) artwork. Inside the package was a button pack with buttons by <a href="http://royalbuttons.com" title="Royal Buttons -  Custom Buttons Made to Order">Royal Buttons Custom Buttons</a>. There was also an unbent copy of the package art, and a sweet random drawing on nice card stock with a personal note from Frank, thanking the winner for participation.</p>

<p>Frank said he would also have some future contests, so even though this one is over, there could be some stuff up for grabs later.</p>

<div class="thumb-box">
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_1.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_1_t.jpg" /></a>
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_2.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_2_t.jpg" /></a>
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_3.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_3_t.jpg" /></a>
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_4.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_4_t.jpg" /></a>
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_5.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_5_t.jpg" /></a>
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_6.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_6_t.jpg" /></a>
<a href="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_7.jpg" title="Frank Peak Contest" class="thickbox thumb-left"><img src="http://codeblog.studiokoi.com/images/frankpeak/frank_peak_contest_7_t.jpg" /></a>
<div class="clear-left"></div>
</div>
 {extended}
      ]]></content>
    </entry>

    <entry>
      <title>Execution order of functions and variables in JavaScript and ActionScript.</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/execution_order_of_functions_and_variables_in_javascript_and_actionscript" />
      <id>tag:studiokoi.com,2009:blog/index/1.45</id>
      <published>2009-04-13T07:17:37Z</published>
      <updated>2010-05-19T15:24:39Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="JavaScript"
        scheme="http://studiokoi.com/code/category/JavaScript"
        label="JavaScript" />
      <content type="html"><![CDATA[
        <p>Many newcomers to web development may not be used to how web implementations of JavaScript execute. Namely, in what <em>order</em> it executes. This can be the source of many errors that are difficult to pinpoint if you aren't experienced with it. I think this also affects people who are very experienced with other programming languages and fosters a lot of undeserved hate towards ActionScript and JavaScript. (It's important to note that not all implementations of JavaScript are the same, and that some may in fact defer from what is said below. This article concerns browser and Flash based ECMAScript.)</p>

<p>The thing to understand about JavaScript is that it isn't compiled for the most part. (This is not <em>exactly</em> true for ActionScript because of the introduction of classes in ActionScript 2.0, however, the runtime script remains the same. You might argue that it compiles into a *.swf file, but in reality, that is the combination of everything that has to do with the Flash file. The ActionScript still remains live.) It's good that it isn't compiled though, because this allows for much more dynamic, expressive coding.</p>

<p>So, if it isn't compiled, how does it work? Browser-based JavaScript code is all executed at first calling, nothing is compiled or cached in a scope until it is called (except AS2 &amp; AS3 classes). It works this way because, with the exception of basic, immutable variable types: strings, booleans, numbers, and 'undefined', every variable in JavaScript is an object. This includes 'null' and functions ('null' is technically a basic variable, but is reported as an object in JavaScript). Since functions are objects, this means their value in memory is also like an object and names are only assigned by reference. Lets see how this works:</p>

<pre class="brush: js">
//bob first initialization
function bob()
{
	alert('bob');
}

//set jan to bob via reference
var jan = bob;

//set bob to another function
function bob()
{
	alert('newbob');
}

jan(); //alerts 'bob'
bob(); //alerts 'newbob'
</pre>

<p>This where things can be very confusing to people who are used to other languages where functions are <em>just</em> functions and can only be written once to a variable name at compile time. In order to understand better, let's write the same code again with anonymous functions:</p>

<pre class="brush: js">
//bob first initialization
var bob = function()
{
	alert('bob');
};

//set jan to bob via reference
var jan = bob;

//set bob to another function
bob = function()
{
	alert('newbob');
};

jan(); //alerts 'bob'
bob(); //alerts 'newbob'
</pre>

<p>This is how functions are actually assigned in JavaScript. The traditional C style that was seen in the previous example is translated at runtime into something like the above. So, when you code JavaScript, imagine instead that all functions are really variable pointers to anonymous functions in memory. (ActionScript 3.0 in strict mode attempts to stop this sort of behavior by warning you when your code tries to overwrite variables that have already been set. While this is good for heavier languages, I think it is moving away from what makes ECMAScript really dynamic in the first place.)</p>

<p>At this point, you might be asking: "Why is all this important to the execution order of JavaScript?". This gives you background as to why JavaScript doesn't execute anything until runtime. In light of this, there is one thing JavaScript does to speed things up that is VERY important to understanding its execution order: JavaScript caches declared functions <em>before</em> any other variables, after this, it goes back to the top of the scope and runs variable definitions and functions calls in the order that they appear. This is where the confusion begins for the uninitiated.</p>

<p>Let's say for example that you have a function that returns a value from a passed variable. You might want to assign a variable to the result of that function like so:</p>

<pre class="brush: js">
var newNumber = secondPower(5); //25

//first definition of function
function secondPower(n)
{
	return n * n;
}
</pre>

<p>This works because the function was cached before the variable was assigned. However, doing things this way in your own code is a <strong>TERRIBLE</strong> idea because it can cause more problems than it solves. Lets look at an example of where this might fail. Remember our previous example where we assigned the anonymous function to a variable name? While in that example, it worked perfectly, it actually causes a strange thing to happen to execution order:</p>

<pre class="brush: js">
var newNumber = secondPower(5); //error, secondPower is not defined yet

//some parsers would not even get this far due to the above error
//thrown errors in ECMAScript halt the execution scope they are in
var secondPower = function(n)
{
	return n * n;
};

var newNumber2 = secondPower(5); //25
</pre>

<p>This error happens because when the parser came through, it cached the anonymous function before anything else, but <em>not</em> the variable name assignment to the anonymous function. Therefore, when we called 'secondPower', it had not been assigned yet and the first calling was undefined and possibly threw an error. It is important to remember that the bad thing that happened here was not the fact that we assigned a variable name to an anonymous function in place of the classic C way to declare a function, but rather the bad idiom of calling a function before it is assigned. Anonymous functions offer huge benefits to ECMAScript and are not inherently bad.</p>

<p>Other problems can arise from calling functions before they are declared even if the function is written in the classic style. Perhaps the function we use for variable assignment requires an outside variable to function properly. This would cause an error if the function was called before the assignment of the dependent variable took place:</p>

<pre class="brush: js">
var newNumber = multiplyNumber(5);
//multiple is not defined yet, incorrect result with possible error 

var multiple = 2;

//this is cached and available before all other variables
function multiplyNumber(n)
{
	return n * multiple;
}
</pre>

<p>As we can see here, an error would occur in our variable assignment because even though the function was properly cached, its dependent was not assigned yet and the function could not execute properly.</p>

<p>So, knowing this, what should you do to avoid these errors? Here is a quick list to help you when writing your code:
	<ul>
		<li>Never call a function before it is declared</li>
		<li>Declare all variables in a execution scope as soon as possible</li>
		<li>Only assign variables to a function result after all functions and other variables have been declared</li>
	</ul>
</p>

<p>Just to reiterate, let's look at how a good code setup should be writen:</p>

<pre class="brush: js">
//declare all variables as soon as possible
var newNumber, multiple = 2;

//declare all functions before calling them
function multiplyNumber(n)
{
	return n * multiple;
}

//finally, set variable values that require function results
newNumber = multiplyNumber(5); //10
</pre>

<p>Declaring your variables and functions in this way will allow you to use more expressive methods to set functions and will most importantly avoid errors. For some further reading, check out <a href="http://javascript.crockford.com/code.html" title="Code Conventions for the JavaScript Programming Language">Douglas Crockford's recommendations on JavaScript coding conventions</a>.</p>

<p>While I mostly mentioned JavaScript in this Article, the majority of these principles and Douglas Crockford's suggestions apply to ActionScript as well.</p> {extended}
      ]]></content>
    </entry>

    <entry>
      <title>Type&#45;checking arrays in JavaScript</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/typechecking_arrays_in_javascript" />
      <id>tag:studiokoi.com,2009:blog/index/1.44</id>
      <published>2009-01-10T08:06:00Z</published>
      <updated>2009-01-26T15:43:54Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="JavaScript"
        scheme="http://studiokoi.com/code/category/JavaScript"
        label="JavaScript" />
      <content type="html"><![CDATA[
        <p>In JavaScript the typeof operator reports an array as 'object'. While this is technically correct (an array in JavaScript is really just a specialized object), it's a pain in the neck when you are type checking a variable.</p>

<p>There are a number of ways to identify an array in JavaScript. Checking for properties of an array isn't totally accurate because you can add any named member to an object to imitate an array. Checking for 'instanceof Array' works most of the time but could be tricky in some implementations of JavaScript.</p>

<p>Mark Miller of Google gives us a solution that is standard to the ECMAScript documentation:</p>

<pre class="brush: javascript">Object.prototype.toString.apply(value) === '[object Array]';</pre>

<p>What this essentially does is take the standard Object method "toString" and applies it to the passed argument (which is your array you are checking). This makes sure that it reports itself according to standard, which all real arrays should. We can implement it in an easy checking function that returns a boolean:</p>

<pre class="brush: javascript">function isArray(a)
&#123;
	return Object.prototype.toString.apply(a) === '[object Array]';
&#125;</pre>

<p>Props to Douglas Crockford because I read about this on his blog. There is also some <a href="http://blog.360.yahoo.com/blog-TBPekxc1dLNy5DOloPfzVvFIVOWMB0li?p=916#comments" title="Douglas Crockford | Yahoo 360">further discussion</a> there on using this method and i recommend reading it.</p>

<p>As a bonus of sorts, this also works in ActionScript 2.0 and ActionScript 3.0.</p> {extended}
      ]]></content>
    </entry>

    <entry>
      <title>JavaScript Errors: Testing for the existence of functions in JavaScript</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/javascript_errors_testing_for_the_existence_of_functions_in_javascript" />
      <id>tag:studiokoi.com,2008:blog/index/1.43</id>
      <published>2008-12-29T22:38:21Z</published>
      <updated>2010-05-20T14:57:22Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="JavaScript"
        scheme="http://studiokoi.com/code/category/JavaScript"
        label="JavaScript" />
      <content type="html"><![CDATA[
        <p>When using multiple JavaScript libraries, it is inevitable that one JavaScript file will need to call functions named in other libraries. This is necessary but can cause issues if all of the libraries aren't present.</p>

<p>Error handling with JavaScript is somewhat lackluster. With this in mind, you should do your best to catch and handle errors and avoid sending them to the end-user. In order to prevent errors and allow for scalability, you should test for functions that aren't present in the script where you are calling them.</p>

<p>Lets say for example that you have downloaded a JavaScript library named "bob.js" and it contains just a main function named "bob". To keep things clean, you might load this file separately. (Of course this is a bit unrealistic, no one would make a separate file for one function, but for the sake of example, bear with me.) Your loading code might look like this:</p>


<pre class="brush: xml">&lt;script type="text/javascript" src="bob.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="mycode.js"&gt;&lt;/script&gt;</pre>

<p>So, correctly, we have loaded the "bob" library first and our code second.</p>

<p>For the sake of example and understanding, lets suppose that the "bob" function just returns a simple math result. It isn't important what the bob function does, but it might be easier for some to understand if we had a real example:</p>

<pre class="brush: javascript">//bob.js
function bob(n)
&#123;
	return n * n;
&#125;</pre>

<p>Now this takes us to our real example. Given that we have the function "bob" in another file, we want to use it in our own code, "mycode.js". When the page loads, we want to add a div tag with some text that has a number in it. We are going to use the "bob" function to return the number to the power of 2 and write it:</p>

<pre class="brush: javascript">//mycode.js
window.onload = function()
&#123;
	//the starting number
	var oldNum = 43;
	
	//make the number we are going to write
	var newNum = bob(oldNum);

	//set the body tag to a variable
	var body = document.getElementsByTagName('body')[0];
	
	//make the div container
	var myDiv = document.createElement('div');
	
	//create the text container
	var myText = document.createTextNode(newNum);
	
	//add the text to the div
	myDiv.appendChild(myText);
	
	//add the div to the body
	body.appendChild(myDiv);
&#125;</pre>

<p>While the above code could be written quite a bit smaller, it works well and it is plain what is happening. You run into an issue however when the "bob.js" file isnt present. When you run into an error in JavaScript, it usually kills the chain the function or event is called in. So in the above instance, as soon as it hit the second variable, and the bob code wasn't present, the code would simply halt on error and nothing would display on screen, potentially breaking many other things in the process.</p>

<p>This brings the issue of error handling and function testing. One of the tools that we do have in JavaScript is the try/catch(/finally) statement. It is very handy for areas of code that can be error prone or have outside influence on the application. We could fix our example by adding a try/catch statement that would have a backup variable in case the "bob.js" isn't present:</p>

<pre class="brush: javascript">//mycode.js
window.onload = function()
&#123;
	//the starting number
	var oldNum = 43;
	
	//make the number we are going to write
	try &#123;	
		//works if bob is present
		var newNum = bob(oldNum);
	&#125; catch(e) &#123;
		//catches the error if bob is missing and provides an alternative
		var newNum = oldNum;
	&#125;

	//..etc
&#125;</pre>

<p>This will effectively remove the chance for error if "bob.js" isn't present. However, the try/catch statement takes a bit of a performance hit due to all it is designed to do. When simply testing for functions, I feel it is a bit verbose.</p>

<p>My personal preference is just to test for the existence of the function before I attempt to call it. This way you don't spend the CPU time calling the function, getting the failure, sending the error, catching the error, then running the error block. When testing for a function, it's usually best to make sure it is actually a function rather than simply checking for it to be not undefined. This is doubly important in situations where you are using multiple libraries or working with a lot of people on the same file. Your code and their code could have the same name for two different types of objects. JavaScript has no overwrite protection even on its own built in functions unless specific platforms add it in, therefor you must take it upon yourself to check.</p>

<p>Checking for the existence of functions can be done easily using the typeof operator in JavaScript. Many times, I code that simply checks for "undefined" or not, then lets the code run. As mentioned above, this still leaves some potential for errors in your code. Granted, there will always be margin for error, but the goal is to make habits that minimize it and help you the real issues. Therefore I think it is better to make sure your function is actually a function. The same code we used with the try/catch statement can be written similarly with the typeof checking:</p>

<pre class="brush: javascript">//mycode.js
window.onload = function()
&#123;
	//the starting number
	var oldNum = 43;
	
	//make the number we are going to write
	if(typeof bob === "function") &#123;	
		//works if bob is present and is a function
		var newNum = bob(oldNum);
	&#125; else &#123;
		//if bob is not present, provides an alternative
		var newNum = oldNum;
	&#125;

	//..etc
&#125;</pre>

<p>This has better performance than the try/catch statement and gives you a better idea where an error could be if it occurs. However, we could write this even shorter to make the code a little cleaner using a ternary operator:</p>

<pre class="brush: javascript">//mycode.js
window.onload = function()
&#123;
	//the starting number
	var oldNum = 43;
	
	//make the number we are going to write
	//if bob is present and is a function, make number
	//if bob is not present, provides an alternative
	var newNum = (typeof bob === "function")? bob(oldNum) : oldNum;

	//..etc
&#125;</pre>

<p>One last thing to mention when using typeof. It will throw an error if you are testing for a function inside of a nonexistent parent. So, say "bob" is an object, with a subobject "math", with a method called "double". If we test for "bob.math.double" and "bob" doesn't exist, JavaScript will throw an error with the typeof operator. To avoid such errors you could test for each segment of the method's parent chain before testing for the method itself:</p>
<pre class="brush: javascript">//mycode.js
window.onload = function()
&#123;
	//the starting number
	var oldNum = 43;
	
	//make the number we are going to write
	if(typeof bob === "object" && 
	   typeof bob.math === "object" &&
	   typeof bob.math.double === "function") &#123;	
		//works if bob is present and is a function
		var newNum = bob.math.double(oldNum);
	&#125; else &#123;
		//if bob is not present, provides an alternative
		var newNum = oldNum;
	&#125;

	//..etc
&#125;</pre>

<p>This seems a lot longer given the possibilities of nested objects, but doing it this way also prevents the issue of same-named objects clobbering each other and sneaking in to create errors. If you are really confident with your code and have no outside workers/code coming in, you could skip the middle statements and just test for the parent object.</p>

<p>There we have it. This method of function existence checking has saved me lots of time and has created some interesting idioms for projects where external code may or may not be present. Enjoy!</p> {extended}
      ]]></content>
    </entry>

    <entry>
      <title>Making Anonymous Functions and Closures Work in ActionScript 2.0</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/making_anonymous_functions_and_closures_work_in_actionscript_20" />
      <id>tag:studiokoi.com,2008:blog/index/1.39</id>
      <published>2008-08-26T05:35:01Z</published>
      <updated>2008-08-25T22:12:23Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="Flash&#45;ActionScript"
        scheme="http://studiokoi.com/code/category/Flash-ActionScript"
        label="Flash&#45;ActionScript" />
      <content type="html"><![CDATA[
        <p>One of the most powerful idioms available in JavaScript is the anonymous function closure: e.g. (function(){})();. If you are unfamiliar with this, it simply creates an anonymous scope bubble that can be used to prevent automatic global variables, or trick JavaScript into allowing private variables. Unfortunately, this idiom isnt available in ActionScript 2.0. It simply doesnt work. (As of ActionScript 3.0, it works perfectly.)</p>
 
<p>This means that, on the surface, the only way to prevent time line variables from being constantly created is an init function of sorts. (ActionScript 2.0 has a pseudo global object which is the main time line of a movie level, and a totally global object named _global.) This also means that private variables are restricted to the creation of object classes. I personally get annoyed at times with classes in ActionScript. One of the things that has always bugged me with ActionScript 2.0 and the introduction of classes is that they are hard to make portable. (I work on no less than 3 computers in a single week, and 4-5 when on business trips, so portability is paramount to my work.) Rather than being able to simply include the classes in the same folder as the flash working file (*.fla), you must specify where on the computer the includes are. This is just annoying if you work on the file on several different computers. There are a couple of ways to avoid naming the class include folder on each computer, but they are as much of a pain as the default method. Fortunately, there is a solution.</p>

<p>To reiterate, while this works in JavaScript and ActionScript 3.0, it will not in ActionScript 2.0:
</p>
<pre class="brush: actionscript">(function()&#123;
	//statements
&#125;)();

var myFunc = (function()&#123;
	var hiddenVar = "hidden";
	return function()
	&#123;
		return hiddenVar;
	&#125;
&#125;)();
hiddenVar		//undefined
myFunc.hiddenVar; 	//undefined
myFunc(); 		//returns "hidden"</pre>

<p>The good news about ActionScript 2.0 is that it retains the ability to pass anonymous functions as variables to another function. Like so:
</p>
<pre class="brush: actionscript">var myArray = [5,1,6,23,15];
var sortedArray = myArray.sort(function(a, b)&#123;
	return a - b;
&#125;);
trace(sortedArray); //returns [1, 5, 6, 15, 23]</pre>

<p>Knowing this, we can emulate anonymous function closures in ActionScipt 2.0. First we will create a global function that returns the function passed to it.</p>
<pre class="brush: actionscript">_global.closure = function(f)
&#123;
	return f;
&#125;</pre>

<p>To use it, you treat it the same as you would the parenteses in the javascript idiom:
</p>

<pre class="brush: actionscript">closure(function()&#123;
	//statements
&#125;)();</pre>

<p>Changing the name to something shorter will make this more practical and the code a little cleaner.</p>

<pre class="brush: actionscript">_global.&#36; = function(f)
&#123;
	return f;
&#125;

&#36;(function()&#123;
	//statements
&#125;)();</pre>

<p>Given this new ability, we can now apply anonymous closures to our script without littering the time line object with useless variables.</p> 

<p>Lets use a hypothetical situation to illustrate how we might use the anonymous closure. In this script, we want to make 5 buttons that each need to trace their respective number when you click them. We could code each button individually, but that is messy and doesn't promote good code reuse. Instead, lets make a loop that makes all the buttons work, in addition to making it easier to add more buttons.</p>

<pre class="brush: actionscript">for (var i = 1; i &lt;= 5; i++)
&#123;
	//for each button
	this["click" + i + "_btn"].onPress = &#36;(function(n)&#123;
		//return a function that has access to n via
		// a closure
		return function()
		&#123;
			//trace the number passed to the parent closure
			trace(n);
		&#125;
	&#125;)(i); //pass in current loop iteration for caching
&#125;</pre>

<p>Now when you press click3_btn, it will trace '3' and click5_btn, '5'. In this way, we avoid creating useless variables inside each button, and we didn't have to create a singular use function.</p>

<p>Earlier I mentioned my slight distaste for how classes were implemented in ActionScript 2.0. Let me first caveat this statement by saying they are extremely useful and are wonderful for individuals or teams that have good version networks and servers. Just for myself and the smaller applications I write, I prefer portable objects. Lets see how we would write a singleton object with private variables and functions:</p>

<pre class="brush: actionscript">var bob = &#36;(function ()
&#123;
	//---------------------------
	//private variables
	var secret = "you found me";
	//---------------------------
	//private functions
	function compare(a, b)
	&#123;
		return a &gt; b;
	&#125;
	//---------------------------
	//constructor
	var Bob = &#123;
		//---------------------------
		//public members/variables
		works		:true,
		getSecret	:function()
		&#123;
			return secret;
		&#125;,
		getCompare	:function(a, b)
		&#123;
			return compare(a, b);
		&#125;
	&#125;;
	//---------------------------
	//return object
	return Bob;
&#125;)();
//test
trace(typeof bob) 		//returns object
trace(bob.works);		//returns true
trace(bob.getSecret());		//returns the string: you found me
trace(bob.secret);		//returns undefined
trace(bob.getCompare(1, 2));	//returns false
trace(bob.compare(1, 2));	//returns undefined function</pre>

<p>As you can see with the tests, we have a singleton object with private functions and variables as well as public methods and members. With a little work, using the prototypal inheritance method, we can make this a reusable pseudo class:</p>

<pre class="brush: actionscript">var Bob = &#36;(function ()
&#123;
	//---------------------------
	//private variables
	var secret = "you found me";
	//---------------------------
	//private functions
	function compare(a, b)
	&#123;
		return a &gt; b;
	&#125;
	//---------------------------
	//constructor
	var Bob = function ()
	&#123;
		//---------------------------
		//public members/variables
		this.works = true;
	&#125;;
	//---------------------------
	//public methods
	Bob.prototype.getSecret = function()
	&#123;
		return secret;
	&#125;;
	Bob.prototype.getCompare = function(a, b)
	&#123;
		return compare(a, b);
	&#125;;
	//---------------------------
	//return constructor
	return Bob;
&#125;)();
//invoke
var mybob = new Bob();
//test
trace(typeof Bob);		//returns function
trace(typeof mybob);		//returns object	
trace(mybob.works);		//returns true
trace(mybob.getSecret());	//returns the string: you found me
trace(mybob.secret);		//returns undefined
trace(mybob.getCompare(1, 2));	//returns false
trace(mybob.compare(1, 2));	//returns undefined</pre>

<p>So, with a single global function, we can bring the magic of anonymous function closures to ActionScript 2.0. Enjoy!</p> {extended}
      ]]></content>
    </entry>

    <entry>
      <title>Parsing a nested or name spaced object from a string in ECMAScript</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/parsing_a_nested_or_name_spaced_object_from_a_string_in_ecmascript" />
      <id>tag:studiokoi.com,2008:blog/index/1.23</id>
      <published>2008-01-10T06:37:00Z</published>
      <updated>2008-01-09T20:39:03Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="JavaScript"
        scheme="http://studiokoi.com/code/category/JavaScript"
        label="JavaScript" />
      <content type="html"><![CDATA[
        <p>Often times when I am making dynamic scripts in Flash or JavaScript, I want to call an object method using a string. It may be a situation where I am stuck using <a href="http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary372.html" title="ActionScript Dictionary: fscommand">fscommand</a> (due to a customer request of a Flash version &lt;8) or just writing script with script.</p>

<p>The problem that comes with this method is the advent of ActionScript 3 with Flash CS3/Flex 2 and the rising use in namespaces by JavaScript developers (myself included). Both encour a heavy usage of object methods instead of one-off functions. Dynamically calling singleton functions is easy, you can just use subscript notation, e.g. object[&#8216;member/method&#8217;]. What you can&#8217;t do with this method is pass it any dot syntax and expect it to work e.g. object[&#8216;subobject.method&#8217;]. The subscript notation is only meant to work one level. So the previous example won&#8217;t work. In order to fix this issue and to make sending object methods/members in a single string a little easier, I wrote a function that takes a string and a base object (the default is the window object if no object reference is passed) and returns the method/member. (I know at this point that some will simply direct me to ECMAScript&#8217;s built in eval() function, but I personally avoid using it at all costs as it can have unintended, and unsecure results. I&#8217;ll let <a href="http://javascript.about.com/library/bleval.htm" title="About.com: Alternatives to eval">Stephen Chapmen tell you</a> because this article is about something else.)
</p>

<p>The function is executed somewhat simply by splitting the string at the dots and adding them as subscripts to one another in order. However, there are some other pieces to it that make it a little more friendly to mistakes and general usage.</p>

<p><pre class="brush: javascript">function parseNameSpace(s , o)
&#123;
	//default to window if no object sent
	var w = o || window, a;
	
	//reutrn if parsing not necessary or not a method
	if ( s.indexOf('.') == -1 )
	&#123;
		return (typeof w[s] === "undefined") ? false : w[s] ;
	&#125;
	
	//make array for looping through
	a = s.split('.');
	
	//run though members / methods
	for (var i = 0,l = a.length; i &lt; l; i++)
	&#123;
		w = w[a[i]];
	&#125;
	
	//return object if it is valid, or return false
	return (typeof w === "undefined") ? false : w ;
&#125;</pre></p>

<p>The function takes two variables, first the string that you want to parse to an object member, and the second optional base object. The first variable w looks for the object &#8220;o&#8221; and if not found, defaults to &#8220;window&#8221; which is the default parent object of browser based JavaScript. (You could change it to &#8220;this&#8221; and it would work in ActionScript as well). Second, we check to see if the passed string has any dots in it. If not, we check to see if it is a regular function. This way you could use this function as a catch all even if you aren&#8217;t always passing nested functions. If it isnt a member of the window object, false is returned. If it does have dots, we split them into an array, and loop through it, making each a member of the previous using the subscript notation. Finally we check to see if the result is valid, and we return false if it isn&#8217;t, or a reference to the object itself.</p>

<p>Let&#8217;s take a look at a simple way to use it. Lets say we have an object literal with a subobject, and a method inside that.</p>

<p><pre class="brush: javascript">var obj = &#123;
	innerObj: &#123;
		func: function()&#123;
			return "worked";
		&#125;
	&#125;
&#125;</pre></p>

<p>Then we retrieve it via string with the function.</p>

<p><pre class="brush: javascript">var objFunc = parseNameSpace("obj.innerObj.func");
alert(objFunc()); //shows "worked"</pre></p>

<p>This should work most places as long as you are mindful of function scope. Enjoy!</p> {extended}
      ]]></content>
    </entry>

    <entry>
      <title>Create Right Click Menus to Test AIR Files (Win/Mac)</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/create_right_click_menus_to_test_air_files_win_mac" />
      <id>tag:studiokoi.com,2007:blog/index/1.21</id>
      <published>2007-08-22T09:18:02Z</published>
      <updated>2007-08-22T07:24:04Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="AIR"
        scheme="http://studiokoi.com/code/category/air"
        label="AIR" />
      <content type="html"><![CDATA[
        <p>At the beginning of this year, when I first heard about <a href="http://labs.adobe.com/technologies/air/" title="Adobe Integrated Runtime">A.I.R.</a> I was excited to learn more about it and see what I could do with it. What really jumpstarted my interest was a trip to Cincinnati, OH to the <a href="http://onair.adobe.com/" title="Adobe onAIR Bus Tour">Adobe onAIR Bus Tour</a>. At this point I am full steam excited about working with AIR.</p>

<p>I work on a Windows machine at work and Mac at home, so I am also excited to see cross platform development. One thing that is a little wonky about AIR is the way that you test your applications. Since AIR is built with an SDK instead of a builder application, such as Flash, you have you use the terminal to launch the SDK. So I came up with methods for OS X and Windows XP to use right-click contextual menus to test AIR applications. I will first note that you can use <a href="http://aptana.com" title="Aptana">Aptana</a>, <a href="http://labs.adobe.com/technologies/flex/" title="Flex 3 Beta &quot;Moxie&quot;">Flex 3</a>, <a href="http://labs.adobe.com/wiki/index.php/AIR:Flash_CS3_Professional_Update#Download_and_Install" title="Flash CS3 AIR Plug-in">Flash CS3</a>, and <a href="http://labs.adobe.com/wiki/index.php/AIR:Dreamweaver_CS3_Extension" title="Dreamweaver CS3 AIR Plug-in">Dreamweaver CS3</a> to test your AIR apps, but i thought i would make something for the hardcore coders. Though, I personally use all the aforementioned for AIR.</p>

<p>I will assume you have already installed the <a href="http://labs.adobe.com/downloads/airsdk.html" title="Adobe AIR SDK">SDK</a> on either system.</p>

<p>Windows XP: <a href="#mac">[skip to mac version]</a><hr /></p>

<p>In Windows XP, you can customize your right-click menus for any filetype with the 'folder options' panel. First, navigate to control panel, then folder options. Navigate to XML (It will be close to the bottom.).</p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/xp_func_slct_avd.gif" alt="image" width="386" height="475" /></p>

<p>If the button says 'Restore' where you expect it to say 'Advanced', it is because you have changed the Windows default opening program for the xml file type. Click 'Restore' first then you can click 'Advanced'. (When you are finished, you can change the opening program back when you are finished, the menu will still stick.)</p>

<p>Next, click the 'edit' button and we will create a new contextual command. You will need the full path of the location of your AIR SDK. For this example, I will use mine:</p>

<code>C:\Program Files\Adobe\AIR SDK\bin\adl.exe</code>

<p>This will application field in quotes, followed by "%1". This will notate that you are opening the file right-clicked with this program. (This works on most other windows programs as well.) Then give it a name you can remember. This is how it will show up in the contextual menu. Just replace my AIR bin location with yours.</p>

<code>"C:\Program Files\Adobe\AIR SDK\bin\adl.exe" "%1"</code>

<p><img src="http://codeblog.studiokoi.com/images/uploads/xp_func_code.gif" alt="image" width="347" height="361" /></p>

<p>Now click OK and you should see your command in the window:</p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/xp_func_fin.gif" alt="image" width="347" height="318" /></p>

<p>Now you can right-click your AIR application.xml and test them right from the Windows file explorer:</p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/xp_func_rtclk.gif" alt="image" width="374" height="328" /></p>

<p>The CMD prompt will open, then your air file should open. The CMD prompt will be your error output window.</p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/xp_func_adl_run.gif" alt="image" width="550" height="394" /></p>

<p>&nbsp;</p>
<p><a name="mac">OS X:</a><hr /></p>

<p>The Mac version will be somewhat similar, but we will use Automator to do the function. This means you will need at least OS X 10.4 for this tutorial.</p>

<p>Open Automator, and go to 'Finder' in the Library menu, under Applications. Drag 'Get Selected Finder Items' to the work space.</p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/mac_adl_get.gif" alt="image" width="540" height="104" /></p>

<p>Next, go to 'Automator' in the Library menu, and drag 'Run AppleScript' to the work space under 'Get Selected Finder Items'.</p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/mac_adl_aplscr.gif" alt="image" width="540" height="377" /></p>

<p>For the Applescript, I had a little help from <a href="http://www.macosxhints.com/article.php?story=20050827164648766" title="MacOSXHints.com | Use Automator to open chosen folder in Terminal">Mac OS X Hints</a>. You will need the directory for your Adobe AIR SDK. Mine is:</p>

<code>/Applications/Adobe AIR SDK/bin/adl</code>

<p>For this one, I will give the code to you. Paste this into the Applescript window and replace my AIR Adl location with yours:</p>

<pre class="brush: applescript">
on run &#123;input, parameters&#125;
	tell application "Terminal"
		activate
		if (the (count of the window) = 0) or ¬
			(the busy of window 1 = true) then
			tell application "System Events"
				keystroke "n" using command down
			end tell
		end if
		do script "'/Applications/Adobe AIR SDK/bin/adl' \"" & (POSIX path of ¬
			(input as string)) & "\"" in window 1
	end tell
	return input
end run
</pre>

<p>Next, we will save this as a Plug-in. Under the File menu, select 'Save As Plug-in..'. Then select finder as the application and give it a name you can remember:</p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/mac_adl_plug.gif" alt="image" width="351" height="296" /></p>
<p><img src="http://codeblog.studiokoi.com/images/uploads/mac_adl_save.gif" alt="image" width="406" height="143" /></p>

<p>Now you can just right-click your AIR application.xml, hover over Automater, and choose your new workflow to preview AIR projects!</p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/mac_adl_rgtclk.gif" alt="image" width="558" height="500" /></p>

<p>Enjoy!</p>

 {extended}
      ]]></content>
    </entry>

    <entry>
      <title>Expression engine 1.6 Preview and Rick Ellis Birthday Contest</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/expression_engine_16_preview_and_rick_ellis_birthday_contest" />
      <id>tag:studiokoi.com,2007:blog/index/1.20</id>
      <published>2007-06-19T08:14:00Z</published>
      <updated>2008-07-01T10:05:17Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="ExpressionEngine"
        scheme="http://studiokoi.com/code/category/ExpressionEngine"
        label="ExpressionEngine" />
      <content type="html"><![CDATA[
        <p>So Expression Engine is previewing version 1.6 (filled with LOADS of new features) and it is also EE CEO Rick Ellis' Birthday. To celebrate this and some new software, they are having a photoshop contest that ends noon Tuesday June 19th, 2007. Check out the <a href="http://expressionengine.com/forums/viewthread/54250/" title="Expression Engine Forums">forums here</a> for the other submissions. Here is the <a href="http://expressionengine.com/blog/entry/160_preview_and_multiple_rick_manager_birthday_contest/" title="Expression Engine Blog">original blog post</a>.</p>

<p>Without further adieu here are my entries.</p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/ricky_mouse_m.jpg" style="border: 0;" alt="image" width="450" height="299" />
<br/><a href="http://codeblog.studiokoi.com/images/uploads/ricky_mouse.jpg" title="View Larger" class="thickbox">View Larger</a></p>

 <p><img src="http://codeblog.studiokoi.com/images/uploads/rick_oboe_m.jpg" style="border: 0;" alt="image" width="450" height="299" />
<br/><a href="http://codeblog.studiokoi.com/images/uploads/rick_oboe.jpg" title="View Larger" class="thickbox">View Larger</a></p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/rick_tricycle_m.jpg" style="border: 0;" alt="image" width="450" height="299" />
<br/><a href="http://codeblog.studiokoi.com/images/uploads/rick_tricycle.jpg" title="View Larger" class="thickbox">View Larger</a></p>


<p><img src="http://codeblog.studiokoi.com/images/uploads/rick_tiger_m.jpg" style="border: 0;" alt="image" width="450" height="299" />
<br/><a href="http://codeblog.studiokoi.com/images/uploads/rick_tiger.jpg" title="View Larger" class="thickbox">View Larger</a></p> {extended}
      ]]></content>
    </entry>

    <entry>
      <title>Import classes and Multiple ActionScript layers in Flash</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/import_classes_and_multiple_actionscript_layers_in_flash" />
      <id>tag:studiokoi.com,2007:blog/index/1.19</id>
      <published>2007-05-24T06:11:00Z</published>
      <updated>2007-05-23T21:15:03Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="Flash&#45;ActionScript"
        scheme="http://studiokoi.com/code/category/Flash-ActionScript"
        label="Flash&#45;ActionScript" />
      <content type="html"><![CDATA[
        <p>At work I am making a new Flash interface for a project, and my goal this time around was to make as many global functions out of repetitive ones as possible so we could save development time.</p>

<p>As I began writing and testing Prototype class extensions and global functions, I noticed something I had not run into before with flash. If Import classes on one ActionScript layer, and call it on another Actions layer, or even the next frame, it produces an ActionScript error.</p>

<p>Normally, I put all actions and functions on one layer and have no keyframes unless they are inside other MovieClips, or I need to animate something to audio cues. With this current project, there was going to be so much ActionScript, I decided to do more than one Actions layer so I could keep everything straight. Never having a reason to do this until now, I was not prepared for some of the problems I ran into. First and foremost being that: If import a class on one Actions layer, and I create a new class object from that group on another layer, I get a syntax error.</p>

<p>Here is a quick example. I have a MovieClip named &#8220;box1&#8221; and I am going to tween it with the Tween class. normally I would just put it all on the same layer like this:</p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/imprtClsMltLyrs1.gif"  alt="script" width="342" height="212" /></p>

<p><pre class="brush: actionscript">import mx.transitions.Tween;
import mx.transitions.easing.*;
var boxTween:Tween = new Tween(box1, "_x", Regular.easeOut, box1._x, box1._x+300, 1, true);</pre></p>

<p>This works perfectly and makes the box move across the screen on load. When I ran into the error was when I decided that I wanted all imports on one actions layer and the object on another. Like so:</p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/imprtClsMltLyrs2.gif"  alt="moved script" width="329" height="211" /></p>

<p>I expected it to work just the same, as I have My publish settings set to ActionScript 2.0, top down, and Flash 8. Instead, I was presented with a nice error.</p>

<p><img src="http://codeblog.studiokoi.com/images/uploads/imprtClsMltLyrs3.gif"  alt="flash error" width="425" height="209" /></p>

<p>The problem is replicated also by putting the new Tween object in the following frame. Effectively, any frame that ISN&#8217;T the one I imported the class into. This strikes me as totally odd, as functions endure over frames and from layer to layer. I also tested this with other import classes besides the Tween class. I had the same issues with the Alert class and BitmapData class.</p>

<p>For now, the simple solution I came up with was making a function in the same frame/layer as the import classes that I would simply call elsewhere when I needed the tween to happen. This of course makes no sense to me at all, but it works perfectly.</p>

<p><pre class="brush: actionscript">import mx.transitions.Tween;
import mx.transitions.easing.*;
function tweenIt() &#123;
	var boxTween:Tween = new Tween(box1, "_x", Regular.easeOut, box1._x, box1._x+300, 1, true);
&#125;</pre></p>

<p>Calling this function in other frames and layers has worked so far, and has more than solved my problem. If you are using multiple tweens, or classes, you could use passthrough variables to be able to make the function usable in other situations.</p>

<p><pre class="brush: actionscript">import mx.transitions.Tween;
import mx.transitions.easing.*;
function tweenIt(mc:MovieClip):Void &#123;
	mc.boxTween = new Tween(mc, "_x", Regular.easeOut, mc._x, mc._x+300, 1, true);
&#125;
tweenIt(box1)</pre></p>

<p>If I found out any more info as to why this is a problem, I will post it here. If anyone else has some insight, please leave me a comment.</p> {extended}
      ]]></content>
    </entry>

    <entry>
      <title>Using The Tag Limit Plug&#45;in with ExpressionEngine</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/using_the_tag_limit_plugin_with_expressionengine" />
      <id>tag:studiokoi.com,2007:blog/index/1.11</id>
      <published>2007-04-22T09:33:01Z</published>
      <updated>2007-04-22T01:11:56Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="ExpressionEngine"
        scheme="http://studiokoi.com/code/category/ExpressionEngine"
        label="ExpressionEngine" />
      <content type="html"><![CDATA[
        <p>Upon redesigning this website, I decided I wanted to do a little more with the front page. The first thing that I wanted to accomplish besides a new look was removing entire posts from the front page and just having short snippets of each post so that there would be less scrolling and a reason to view the entry/comments page.</p>

<p><a href="http://expressionengine.com" title="Ellis Lab's ExpressionEngine Content Management System">ExpressionEngine</a> has a built in word limiter function that can be used on template tags that produce words. My immediate problem with using the word limiter is that it would cut off paragraphs without closing the paragraph tag. I also show a lot of code within pre tags and those not being closed screwed up the entire page layout.</p>

<p>In my search for a solution that would always work, I came across <a href="http://expressionengine.com/forums/member/31739/" title="the_butcher">the_butcher</a>'s <a href="http://expressionengine.com/forums/viewthread/34079/" title="Tag Limit Plug-in for ExpressionEngine">Tag Limit Plug-in for ExpressionEngine</a>. It is a rather brilliant plug-in that lets you wrap a content output with tags that will limit the amount of a certain tag that will be renderd. Like so:</p>

<pre class="brush: php">&#123;exp:tag_limit tag="p" class="foo" num="2" offset="2"&#125;</pre>

<p>This instance will only show 2 tags with the class "foo" and will start with the third one as the offset is set to two. My only grip so far is that you cannot use autoformatting in your post menu when you make posts. You have to enter all html tags yourself, otherwise the extention renders nothing. My guess is that the extention is run before the tags are automatically placed, but I don't know for sure. The simple solution was for me to just enter the paragraph and break tags myself when posting, which isn't a big deal, just a pain in the butt.</p>

<p>All in all, I love the plug-in, and what I was able to accomplish with it on the site. I could have used the summary tag to do what this does, and only showed summaries on the front page and full articles at the link, but I like this idea better. It lets me post a little faster not having to come up with a summary as well as the content</p> {extended}
      ]]></content>
    </entry>

    <entry>
      <title>CSS Backgrounds on the body and html tags</title>
      <link rel="alternate" type="text/html" href="http://studiokoi.com/code/comments/css_backgrounds_on_the_body_and_html_tags" />
      <id>tag:studiokoi.com,2006:blog/index/1.4</id>
      <published>2006-12-22T03:28:15Z</published>
      <updated>2010-07-13T19:54:16Z</updated>
      <author>
            <name>Greg Ferrell</name>
            <email>nospam@example.com</email>
            <uri>http://codeblog.studiokoi.com</uri>      </author>

      <category term="CSS"
        scheme="http://studiokoi.com/code/category/CSS"
        label="CSS" />
      <content type="html"><![CDATA[
        <p>Today I decided to update the html of <a href="http://studiokoi.com" title="Studio Koi Web Design">my main page</a> to appear more like the code blog.</p>
<p>Mainly it was adding the background gradient to the top and some new JavaScript. The background CSS was a very simple effect using the html tag AND the body tag for displaying background images.</p>

<pre class="brush: css">html &#123;
	background-image: url("images/back.gif");
	background-repeat: repeat;
	background-color: #666;
&#125;
body &#123;
	margin:0;
	padding:0;
	background-image: url("images/back_gradient.png");
	background-repeat:repeat-x;
	text-align:center;
&#125;</pre>

<p>I of course assumed it would go very quickly and I just change, upload, and go. I should have known better.</p>

<p>When I was editing the html page, I noticed that I didn't have a <a href="http://www.w3.org/QA/Tips/Doctype" title="w3.org Doctypes">doctype</a>. Being forced to use IE6 all day by the army, I had forgotten what <a href="http://getfirefox.com" title="Get the Firefox Web Browser!">good browsers</a> do when a proper doctype is added. It broke my always-in-the-middle table hack.</p>

<p>There was a simple JavaScript fix I had planed on using anyway, so I decided to implement it. In order for it to work correctly I had to make the div container for the content absolutely positioned. When I did so, the top gradient for the body disappeared. I thought at first that it was a server side issue until I tried it locally with the same results.</p>

<p>I spent more than two hours looking with <a href="http://ee.koruproductions.com" title="Koru Productions' Expression Engine Blog">a friend</a> for the problem. It didn't come to me until after I implemented his suggestion of running a vanilla page with just the CSS.</p>

<p>When an object is absolutely positioned, it doesn't push is parent container. As it was the only thing on the page, and the body counts as a container, there was nothing pushing the body open so that the background could be seen.</p>

<p>The simple solution is adding a height value to the body tag that is as high or higher than the background image.</p>

<pre class="brush: css">body &#123;
	height:400px;
	margin:0;
	padding:0;
	background-image: url("images/back_gradient.png");
	background-repeat:repeat-x;
	text-align:center;
&#125;</pre>

<p>The good thing is that it also <a href="http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Fstudiokoi.com%2Fmain.css&warning=1&profile=css21&usermedium=all" title="W3C CSS Validator">validates!</a> Enjoy.</p> {extended}
      ]]></content>
    </entry>


</feed>