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

<channel>
	<title>Alchemy</title>
	<atom:link href="http://tech.diaslopes.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://tech.diaslopes.com</link>
	<description>Notes from a front-end code addict</description>
	<lastBuildDate>Fri, 30 Mar 2012 09:31:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>LESS CSS in Sublime Text 2</title>
		<link>http://tech.diaslopes.com/?p=112</link>
		<comments>http://tech.diaslopes.com/?p=112#comments</comments>
		<pubDate>Thu, 29 Mar 2012 21:11:22 +0000</pubDate>
		<dc:creator>Marco Dias Lopes</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[less]]></category>
		<category><![CDATA[sublime text]]></category>

		<guid isPermaLink="false">http://tech.diaslopes.com/?p=112</guid>
		<description><![CDATA[If you haven&#8217;t tested LESS you should. LESS is not a new language or a technical replacement for CSS, it&#8217;s a way of implementing CSS as it was a more structured language. The development process is fairly simple, you write &#8230; <a href="http://tech.diaslopes.com/?p=112">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you haven&#8217;t tested <a href="http://lesscss.org/" target="_blank">LESS</a> you should. LESS is not a new language or a technical replacement for CSS, it&#8217;s a way of implementing CSS as it was a more structured language. The development process is fairly simple, you write your LESS code in a LESS file that will be compiled into a CSS file that your browser can read. Before starting you&#8217;ll need two things: a syntax highlighter and a compiler.</p>
<p><span id="more-112"></span></p>
<h2>Syntax highlighting</h2>
<p>First you should install the <a href="https://github.com/danro/LESS-sublime" target="_blank">LESS-sublime package</a> from <a href="http://wbond.net/sublime_packages/package_control/installation" target="_blank">Sublime Package Control</a>. To the check if it is working properly, just create a new file with the less extension. And add some code like this:</p>
<pre class="prettyprint">
.rounded-corners (@radius: 5px) {
  border-radius: @radius;
  -webkit-border-radius: @radius;
  -moz-border-radius: @radius;
}</p>
<p>#header {
  .rounded-corners;
}
#footer {
  .rounded-corners(10px);
}
</pre>
<p>The code should be correctly highlighted.</p>
<h2>Compiling</h2>
<p>Now you need something to compile the LESS file into a CSS file. There are two ways of compiling LESS: the client side and the server side.</p>
<h3>Client side</h3>
<p>The client side is pretty straight forward:</p>
<ol>
<li>Place a link to the LESS in the HTML: <pre class="prettyprint">&lt;link rel="stylesheet/less" type="text/css" href="styles.less"&gt;</pre></li>
<li>Add the script to the HTML file: <pre class="prettyprint">&lt;script src="http://lesscss.googlecode.com/files/less-1.3.0.min.js" type="text/javascript"&gt;&lt;/script&gt;</pre></li>
</ol>
<p>I&#8217;m not very fond of the client side compiling. It puts unnecessary load on the browser, leaving the page blank while the JavaScript processes the LESS file. And it&#8217;s a clear violation of the Progressive Enhancement rules, where the presentation (CSS) an behavior (JavaScript) layers should be separate.</p>
<h3>Server side</h3>
<p>For the server side compilation, there are two different approaches: using the Sublime Text&#8217;s <a href="https://github.com/berfarah/LESS-build-sublime">LESS-build package</a> on build or using a simple app like <a href="http://incident57.com/less/" target="blank">LESS.app</a>.
<p>The Less-build package is very simple for Windows users, just install it from the Package control in Sublime Text. This package, in Windows, uses <a href="https://github.com/dotless/dotless" target="_blank">dotless</a> to compile the LESS files into CSS files and there are no changes required. You can skip to the <a href="#bkm_1">&#8220;Build&#8221;</a> part.</p>
<p>For Mac it&#8217;s not that simple, you&#8217;ll need the <span class="mono">lessc</span> package, that requires <span class="mono">nodejs</span> and <span class="mono">npm</span>.</p>
<p>If you have mac ports, install <span class="mono">nodes</span> and <span class="mono">npm</span>:</p>
<pre class="prettyprint">sudo port install nodes npm</pre>
<p>If you don&#8217;t have mac ports installed please check this <a href="http://shapeshed.com/setting-up-nodejs-and-npm-on-mac-osx/" target="blank">tutorial</a> to install <span class="mono">nodejs</span> and <span class="mono">npm</span>.</p>
<p>Now you need to install <span class="mono">lessc</span>:</p>
<pre class="prettyprint">sudo npm install --global less</pre>
<p>You need to check if the <span class="mono">lessc</span> file is where the LESS-build package wants it to be:</p>
<pre class="prettyprint">ls /usr/local/bin/lessc</pre>
<p>If the file does not exist you need to find it&#8217;s path. Unfortunately the LESS-build package doesn&#8217;t have a reliable way of configuring the path to the <span class="mono">lessc</span> file, you can place it inside the package config files, but it will be removed when you update the package. To solve this you can create a symlink to the lessc file, that should be located in the <span class="mono">/opt/local/bin folder</span>, like this:</p>
<pre class="prettyprint">ln -s /opt/local/bin/lessc /usr/local/bin/lessc</pre>
<p id="bkm_1">You&#8217;ll need to set the build system in Sublime Text&#8217;s Tools menu, to LESS or LESS-min (minified compiled file). And now you will be able to compile the LESS file on &#8220;Build&#8221;.</p>
<p>If you are a Mac user and want a simpler way, you can download <a href="http://incident57.com/less/files/Less.zip" target="blank">LESS.app</a>. Then add the folder that holds the less files and every time you save the file a compiled CSS file will be generated or updated.</p>
<p>Place the compiled CSS file in the HTML as an usual CSS. And you&#8217;re done!</p>
<p>If you want to give LESS a try check this article: <a href="http://www.sitepoint.com/a-comprehensive-introduction-to-less/" target="_blank">A Comprehensive Introduction to LESS</a> from Sitepoint.</p>
<p>There are many advantages to use LESS such as variables, mixins, function and operations. The resultant code is cleaner, stricter, structured, minimizes the vendor prefixes nightmare and therefore more maintainable. However there are some drawbacks and one of them is huge, the existing debug tools are almost useless. When debugging with tools like Firebug, the lines refer to the compiled css file.</p>
]]></content:encoded>
			<wfw:commentRss>http://tech.diaslopes.com/?feed=rss2&#038;p=112</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Observer or Pub/Sub pattern</title>
		<link>http://tech.diaslopes.com/?p=89</link>
		<comments>http://tech.diaslopes.com/?p=89#comments</comments>
		<pubDate>Tue, 31 Jan 2012 23:23:24 +0000</pubDate>
		<dc:creator>Marco Dias Lopes</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[pattern]]></category>

		<guid isPermaLink="false">http://tech.diaslopes.com/?p=89</guid>
		<description><![CDATA[If you ever worked with YUI or Dojo frameworks, you must be familiar with this pattern, it consists on subscribing a widget&#8217;s event by supplying a method to run when the event occurs. The Observer or Pub/Sub (publish/subscribe) pattern is &#8230; <a href="http://tech.diaslopes.com/?p=89">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class='compat'><dl><dt>Compatibility:</dt><dd class='ff'><a title='compatible' class=''></a></dd><dd class='ie'><a title='compatible' class=''></a></dd><dd class='chrome'><a title='compatible' class=''></a></dd><dd class='safari'><a title='compatible' class=''></a></dd><dd class='opera'><a title='compatible' class=''></a></dd></dl></div>
<p>If you ever worked with YUI or Dojo frameworks, you must be familiar with this pattern, it consists on subscribing a widget&#8217;s event by supplying a method to run when the event occurs. The Observer or Pub/Sub (publish/subscribe) pattern is not <a href="http://en.wikipedia.org/wiki/Observer_pattern">new</a> but has great effect in a language like JavaScript which is event driven.</p>
<p><span id="more-89"></span><br />
<h2>How does it work</h2>
<p>Imagine that we have a widget that loads on a page, and there are a set of procedures that we want to run when that widget fully loads. A conventional way to achieve this is by calling the methods from the widget, however this doesn&#8217;t seem right, since you may be using the widget in other pages. The proper way is to implement a mechanism that informs when the widget has loaded, and then run the procedures. We can easily implement this with the observer pattern.</p>
<h2>Advantages</h2>
<p>There are two main advantages using this method: independence and manageability. The object, widget or module that fires the event doesn&#8217;t care about their subscribers structure and if they still exist or not. We can also subscribe or stop subscribing without interacting directly with the publisher owner. So the code can be isolated which facilitates its management.</p>
<h2>Disadvantages</h2>
<p>The main disadvantage is that we need to know exactly how the environment should work. When we have multiple subscribers and publishers it&#8217;s easy to inadvertently create an endless loop.</p>
<h2>Implementation</h2>
<p>First we need the <span class="mono">Observer</span> constructor, it should create a stack that stores all the necessary information to run the handlers when the event fire and set the name of the topic. The name of the topic is used when the event is fired to inform the handler of the occurred event&#8217;s name.</p>
<pre class="prettyprint">
var Observer = function (topic) {
	this._topic = topic || "";
	this._stack = [];
};
</pre>
<p>Next we need the subscribe method. This method should store the subscription information: the handler function, an arguments object and a flag that defines if the arguments object should be used as scope or not.</p>
<pre class="prettyprint">
Observer.prototype = {</p>
<p>	subscribe: function (fHandler, oScope, bOverride) {
		this._stack.push({
			handler: fHandler,
			scope: (bOverride &#038;&#038; typeof oScope === "object") ? oScope : window,
			args: oScope || {},
			override: bOverride
		});
	}
};
</pre>
<p>Now we should create the method to fire (publish) the event. This method may receive some arguments if needed and run the subscribers, stored in the stack, according to their settings. The subscription handler will receive as parameters the Observer&#8217;s topic, the subscription arguments and the publish arguments:</p>
<pre class="prettyprint">
Observer.prototype = {
	...
	publish: function (args) {
		var i, li, cur;
		args = args || [];
		for (i = 0, li = this._stack.length; i < li; ++i) {
			cur = this._stack[i];
			cur.handler.call(cur.scope, this._topic, cur.args, args);
		}
	}
};
</pre>
<p>The publish method could be improved by using the <span class="mono">Array.forEach</span> if available, instead of the conventional for loop.</p>
<p>The last required method is the <span class="mono">unsubscribe</span>, that removes a subscription from the stack by the defined handler.</p>
<pre class="prettyprint">
Observer.prototype = {
	...
	unsubscribe: function (fHandler) {
		var cur, res = [];
		while (this._stack.length) {
			cur = this._stack.shift();
			if (cur.handler !== fHandler) {
				res.push(cur);
			}
		}
		this._stack = res;
	}
};
</pre>
<p>In more advanced browsers you can use the <span class="mono">Array.filter</span> instead of the while statement.</p>
<p>There other useful methods to have in the Observer method, but not mandatory. The <span class="mono">unsubscribeAll</span>, unsubscribes all methods and is very useful when destroying a widget. The <span class="mono">getSubscribers</span> gets all the subscribers and enables to debug or filter the handlers.</p>
<pre class="prettyprint">
Observer.prototype = {
	...
	getSubscribers: function () {
		return this._stack;
	},
	unsubscribeAll: function () {
		this._stack = [];
	}
};
</pre>
<p>Putting all together:</p>
<pre class="prettyprint">
var Observer = function (topic) {
	this._topic = topic || "";
	this._stack = [];
};</p>
<p>Observer.prototype = {</p>
<p>	subscribe: function (fHandler, oScope, bOverride) {
		this._stack.push({
			handler: fHandler,
			scope: (bOverride &#038;&#038; typeof oScope === "object") ? oScope : window,
			args: oScope || {},
			override: bOverride
		});
	},</p>
<p>	publish: function (args) {
		var i, li, cur;
		args = args || [];
		for (i = 0, li = this._stack.length; i < li; ++i) {
			cur = this._stack[i];
			cur.handler.call(cur.scope, this._topic, cur.args, args);
		}
	},</p>
<p>	unsubscribe: function (fHandler) {
		var cur, res = [];
		while (this._stack.length) {
			cur = this._stack.shift();
			if (cur.handler !== fHandler) {
				res.push(cur);
			}
		}
		this._stack = res;
	},</p>
<p>	getSubscribers: function () {
		return this._stack;
	},</p>
<p>	unsubscribeAll: function () {
		this._stack = [];
	}
};
</pre>
<h2>How to use it</h2>
<p>The usage is fairly simple:.</p>
<pre class="prettyprint">
var event,
    obj1 = { a: "A", b: "B" },
    obj2 = { c: "C", d: "D" };</p>
<p>// create a new Observer instance setting the topic (testing)
event = new Observer("testing");</p>
<p>// create handler for the subscription
// the received arguments are the topic, the subscription arguments
// and the published arguments
function fn(sTopic, oSubArgs, oPubArgs) {
	console.log("inside the handler", sTopic, oSubArgs, oPubArgs);
}</p>
<p>// subscribe the event
event.subscribe(fn, obj1, false);</p>
<p>// publish the event
event.publish(obj2); // logs the information from the handler</p>
<p>// remove the subscription
event.unsubscribe(fn);</p>
<p>// publish the event
event.publish(); // shouldn't log anything
</pre>
<h2>Conclusion</h2>
<p>This a very simple pattern that should be used to keep the modularity of the scripts, leading to clean and reliable code. You may optimize the widget or add more events in an independent way without worrying about side effects.</p>
]]></content:encoded>
			<wfw:commentRss>http://tech.diaslopes.com/?feed=rss2&#038;p=89</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing a versatile iterator &#8211; The each method</title>
		<link>http://tech.diaslopes.com/?p=81</link>
		<comments>http://tech.diaslopes.com/?p=81#comments</comments>
		<pubDate>Thu, 19 Jan 2012 15:09:04 +0000</pubDate>
		<dc:creator>Marco Dias Lopes</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[each]]></category>
		<category><![CDATA[foreach]]></category>
		<category><![CDATA[iteration]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[loop]]></category>

		<guid isPermaLink="false">http://tech.diaslopes.com/?p=81</guid>
		<description><![CDATA[A versatile iterator, like the foreach, is a method that allows the iteration of Array, Objects or HTML elements (nodes) collections. Similar method exist in other languages, and can be very useful by using less code, optimized loops and profiting &#8230; <a href="http://tech.diaslopes.com/?p=81">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class='compat'><dl><dt>Compatibility:</dt><dd class='ff'><a title='Compatible' class=''></a></dd><dd class='ie'><a title='Compatible' class=''></a></dd><dd class='chrome'><a title='Compatible' class=''></a></dd><dd class='safari'><a title='Compatible' class=''></a></dd><dd class='opera'><a title='Compatible' class=''></a></dd></dl></div>
<p>A versatile iterator, like the <span class="mono">foreach</span>, is a method that allows the iteration of Array, Objects or HTML elements (nodes) collections. Similar method exist in other languages, and can be very useful by using less code, optimized loops and profiting directly from the language enhancements.</p>
<p><span id="more-81"></span></p>
<h2>Implementation</h2>
<h3>Handling arrays</h3>
<p>Let&#8217;s start our <span class="mono">each</span> method by enabling its use for arrays. The method will expect an array (<span class="mono">source</span>), a function (<span class="mono">fHandler</span>) to be applied when iterating and the scope (<span class="mono">oScope</span>) where the function will run, this last one will be optional.</p>
<pre class="prettyprint">
function each(source, fHandler, oScope)
{
    var i, li,
        scope = oScope || this;</p>
<p>    if(source instanceof Array)
    {
        for(i = 0, li = source.length; i < li; ++i)
        {
            fHandler.call(scope, source[i], i, source);
        }
    }
}
</pre>
<p>The <span class="mono">for</span> loop is improved by caching the array length, you can see some performance statistics <a href="http://jsperf.com/array-iteration-compare" target="_blank">here</a>.</p>
<p>You may be wondering why the iteration handler (<span class="mono">fHandler</span>) receives those 3 arguments, I'll explain it without delay. Some modern browsers already implemented a native iteration method for Arrays:</p>
<pre class="prettyprint">
var a = [1,2,3],
    f = function(value, index, structure){};</p>
<p>a.forEach(a, f, this);
</pre>
<p>The <span class="mono">f</span> function receives 3 arguments: the current iteration value, the index and the array that's being iterated. We can profit by using this native method. If we want to use this native method we need to ensure that its usage is compatible with our <span class="mono">each</span>. So the 3 arguments used by function <span class="mono">f</span> must match the arguments used by the <span class="mono">each</span> handler</p>
<p>However this functionality is not available on all major browsers, which makes it unreliable to use it without testing its existence. But we can integrate this to improve our each method:</p>
<pre class="prettyprint">
function each(source, fHandler, oScope)
{
    var i, li,
        A = Array.prototype,
        scope = oScope || this;</p>
<p>    if(source instanceof Array)
    {
        if(typeof A.forEach === "function")
        {
            A.forEach.call(source, fHandler, scope);
        }
        else
        {
            for(i = 0, li = source.length; i < li; ++i)
            {
                fHandler.call(scope, source[i], i, source);
            }
        }
    }
}
</pre>
<h3>Handling objects</h3>
<p>Now that we have covered the Arrays, it's time to direct our attention to object iteration. Conventionally an object is iterated by using the <span class="mono">for in</span> statement. Before iterate we need to make sure we are handling a standard object, not a function, which is also an instance of object. We should also include a validation for the object member in order to avoid iterating through unwanted properties, that's  why we add the hasOwnProperty verification, this is a JSLint recommendation.</p>
<pre class="prettyprint">
function each(source, fHandler, oScope)
{
    var i, li,
        A = Array.prototype,
        scope = oScope || this;</p>
<p>    if(source instanceof Array)
    {
        if(typeof A.forEach === "function")
        {
            A.forEach.call(source, fHandler, scope);
        }
        else
        {
            for(i = 0, li = source.length; i < li; ++i)
            {
                fHandler.call(scope, source[i], i, source);
            }
        }
    }
    else if(source instanceof Object &#038;&#038; typeof source !== "function")
    {
        for(i in source)
        {
            if(source.hasOwnProperty(i))
            {
                fHandler.call(scope, source[i], i, source);
            }
        }
    }
}
</pre>
<p>Some may ask why we shouldn't use the for in statement to also iterate Arrays, there are two main reasons: the for in statement is much slower that the conventional for loop and when looping through an array we will be accessing some unwanted properties, like the length.</p>
<h3>Handling collections</h3>
<p>JavaScript collections are structures that hold nodes, like those that we get from the <span class="mono">getElementsByTagName</span> or using the <span class="mono">document.forms[0].elements</span>. They are not arrays, they are objects with the length property. However we can handle them as arrays.</p>
<pre class="prettyprint">
function each(source, fHandler, oScope)
{
    var i, li,
        A = Array.prototype,
        scope = oScope || this;</p>
<p>    if(source instanceof Array || ((typeof source === "object" || source instanceof Object) &#038;&#038; typeof source.length === "number"))
    {
        if(typeof A.forEach === "function")
        {
            A.forEach.call(source, fHandler, scope);
        }
        else
        {
            for(i = 0, li = source.length; i < li; ++i)
            {
                fHandler.call(scope, source[i], i, source);
            }
        }
    }
    else if(source instanceof Object &#038;&#038; typeof source !== "function")
    {
        for(i in source)
        {
            if(source.hasOwnProperty(i))
            {
                fHandler.call(scope, source[i], i, source);
            }
        }
    }
}
</pre>
<h2>How to use it</h2>
<p>The usage is simple, the first parameter can be an Array, Object or Collection, the second is a function that serves as iteration handler, which means the action you want to apply in each iteration and the third is the scope where the handler will run. The scope is optional but it can be very useful.</p>
<pre class="prettyprint">
each(Array/Object/Collection, Function, Object);
</pre>
<p>The only thing to keep in mind is the arguments that the handler receives: the value of the current iteration position, the index (current iteration position) and the structure being iterated. If you want to access the scope just use the <span class="mono">this</span> statement.</p>
<pre class="prettyprint">
function handler(value, index, coll)
{
    //code to execute in each iteration
};
</pre>
<h2>Performance</h2>
<p>So what about performance? I wrote some <a href="http://jsperf.com/versatile-iterator" target="_blank">tests</a> with this <span class="mono">each</span> implementation, against conventional implementation and the jQuery <span class="mono">each</span> method.</p>
<div class="center"><img alt="Each method performance" title="Each method performance" src="http://tech.diaslopes.com/wp-content/uploads/2012/02/versatileIterator.jpg" /></div>
<p>The most obvious conclusion is that the jQuery method is the slowest. Although the performance of the conventional implementation is faster than the each method in most of the browsers, the each method requires less code and less weight over the wire. But in my opinion, the most important thing is profiting from the Array.forEach implementation and its future optimization. One day we won't need this <span class="mono">each</span> implementation but until then I'll be using it.</p>
]]></content:encoded>
			<wfw:commentRss>http://tech.diaslopes.com/?feed=rss2&#038;p=81</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mac Ports: Downgrade subversion</title>
		<link>http://tech.diaslopes.com/?p=73</link>
		<comments>http://tech.diaslopes.com/?p=73#comments</comments>
		<pubDate>Tue, 15 Nov 2011 12:51:59 +0000</pubDate>
		<dc:creator>Marco Dias Lopes</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[mac ports]]></category>
		<category><![CDATA[subversion]]></category>

		<guid isPermaLink="false">http://tech.diaslopes.com/?p=73</guid>
		<description><![CDATA[A few days ago, I&#8217;ve upgrade the mac ports that included an upgrade for subversion to version 1.7. The problem is that apps like Cornerstone or Netbeans that depend on version 1.6 stopped working Here&#8217;s a quick a simple way &#8230; <a href="http://tech.diaslopes.com/?p=73">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A few days ago, I&#8217;ve upgrade the mac ports that included an upgrade for subversion to version 1.7. The problem is that apps like <a href="http://www.zennaware.com/cornerstone/index.php">Cornerstone</a> or <a href="http://netbeans.org/">Netbeans</a> that depend on version 1.6 stopped working</p>
<p>Here&#8217;s a quick a simple way to fix it: <a href="https://trac.macports.org/wiki/howto/InstallingOlderPort">https://trac.macports.org/wiki/howto/InstallingOlderPort</a></p>
]]></content:encoded>
			<wfw:commentRss>http://tech.diaslopes.com/?feed=rss2&#038;p=73</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>YUI Compressor for Sublime Text 2</title>
		<link>http://tech.diaslopes.com/?p=61</link>
		<comments>http://tech.diaslopes.com/?p=61#comments</comments>
		<pubDate>Wed, 09 Nov 2011 10:08:16 +0000</pubDate>
		<dc:creator>Marco Dias Lopes</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Sublime Text 2]]></category>
		<category><![CDATA[YUI Compressor]]></category>

		<guid isPermaLink="false">http://tech.diaslopes.com/?p=61</guid>
		<description><![CDATA[A few months ago I&#8217;ve discovered Sublime Text 2, it looked nice, but I didn&#8217;t manage to have the time to look into it in more thoroughly, until now. Sublime Text 2 is awesome. YUI Compressor is a very useful &#8230; <a href="http://tech.diaslopes.com/?p=61">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>A few months ago I&#8217;ve discovered <a href="http://www.sublimetext.com/2">Sublime Text 2</a>, it looked nice, but I didn&#8217;t manage to have the time to look into it in more thoroughly, until now. Sublime Text 2 is awesome.</p>
<p><a href="http://developer.yahoo.com/yui/compressor/">YUI Compressor</a> is a very useful tool to compress code, JavaScript or CSS. Integrating java based tools in Sublime Text is pretty simple. Here&#8217;s how to integrate YUI Compressor.</p>
<p><span id="more-61"></span></p>
<ul class="ordered">
<li>Download YUI compressor from <a href="http://yui.zenfs.com/releases/yuicompressor/yuicompressor-2.4.6.zip">here</a>.</li>
<li>Unpack it in the Sublime Text <span class="mono">Users</span> folder located in the <span class="mono">Packages</span> folder. In my case is something like this: <span class="mono">~/Library/Application Support/Sublime Text 2/Packages/User</span></li>
<li>I&#8217;ve named the extracted folder <span class="mono">YUI Compressor</span></li>
<li>Open Sublime Text 2, and go to Tools > Build System > New build System</li>
<li>Add the following code:<br />
<pre class="prettyprint">{
    "cmd": ["java", "-jar",  "${packages}/User/YUI Compressor/build/yuicompressor-2.4.6.jar", "$file", "-o", "${file_base_name}-min.${file_extension}", "--charset", "utf-8"],
    "selector": "source.js"
}</pre></li>
<li>Save the file as &#8220;YUI Compressor&#8221;</li>
<li>Restart the editor</li>
<li>Open a CSS or JavaScript file, and select the YUI Compressor build system from Tools > Build System</li>
<li>And you can run the build from Tools > Build, or using the shortcut <span class="mono">super + b</span></li>
</ul>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://tech.diaslopes.com/?feed=rss2&#038;p=61</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Pattern: The single var</title>
		<link>http://tech.diaslopes.com/?p=51</link>
		<comments>http://tech.diaslopes.com/?p=51#comments</comments>
		<pubDate>Tue, 18 Oct 2011 07:46:11 +0000</pubDate>
		<dc:creator>Marco Dias Lopes</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[good practices]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[pattern]]></category>

		<guid isPermaLink="false">http://tech.diaslopes.com/?p=51</guid>
		<description><![CDATA[The single var pattern is a very simple and straight forward implementation, as opposite of the side effects of not using it. It consists in declaring all the vars in the top of a scope with a single statement and &#8230; <a href="http://tech.diaslopes.com/?p=51">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class='compat'><dl><dt>Compatibility:</dt><dd class='ff'><a title='compatible' class=''></a></dd><dd class='ie'><a title='compatible' class=''></a></dd><dd class='chrome'><a title='compatible' class=''></a></dd><dd class='safari'><a title='compatible' class=''></a></dd><dd class='opera'><a title='compatible' class=''></a></dd></dl></div>
<p>The single var pattern is a very simple and straight forward implementation, as opposite of the side effects of not using it. It consists in declaring all the vars in the top of a scope with a single <code class="prettyprint">var</code> statement and the variables separated by commas.</p>
<p><span id="more-51"></span></p>
<pre class="prettyprint js">
var i = 0,
    a = 3,
    b = 5,
    c = a + b,
    oObject = {},
    el = document.getElementById("trigger");
</pre>
<p>There is more to it than looking pretty. This pattern is very useful, by creating a place to declare and control all the scope variables and avoiding collisions, unused variables or preventing logical issues due to uninitialized items (hoisting).</p>
<p>This pattern also good because is less code, even after using minifying tools, and maintains the readability. If the variables are initialized it will provide valuable information about scope environment when you return to fix or improve something.</p>
]]></content:encoded>
			<wfw:commentRss>http://tech.diaslopes.com/?feed=rss2&#038;p=51</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implied global var</title>
		<link>http://tech.diaslopes.com/?p=40</link>
		<comments>http://tech.diaslopes.com/?p=40#comments</comments>
		<pubDate>Thu, 13 Oct 2011 08:51:29 +0000</pubDate>
		<dc:creator>Marco Dias Lopes</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[antipattern]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://tech.diaslopes.com/?p=40</guid>
		<description><![CDATA[If you use &#8220;Chain assignment&#8221; or are considering using it, beware of implied globals. Take this example:]]></description>
			<content:encoded><![CDATA[<div class='compat'><dl><dt>Compatibility:</dt><dd class='ff'><a title='compatible' class=''></a></dd><dd class='ie'><a title='compatible' class=''></a></dd><dd class='chrome'><a title='compatible' class=''></a></dd><dd class='safari'><a title='compatible' class=''></a></dd><dd class='opera'><a title='compatible' class=''></a></dd></dl></div>
<p>If you use &#8220;Chain assignment&#8221; or are considering using it, beware of implied globals. Take this example:</p>
<pre class="prettyprint js">
function vars()
{
	var a = b = "hello";
	console.log("a: " + a); // outputs: a: hello
}
vars();
console.log("b: " +  b); // outputs: b: hello
console.log("a: " +  a); // error not defined
</pre>
]]></content:encoded>
			<wfw:commentRss>http://tech.diaslopes.com/?feed=rss2&#038;p=40</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Defer script attribute</title>
		<link>http://tech.diaslopes.com/?p=28</link>
		<comments>http://tech.diaslopes.com/?p=28#comments</comments>
		<pubDate>Sun, 09 Oct 2011 22:16:33 +0000</pubDate>
		<dc:creator>Marco Dias Lopes</dc:creator>
				<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://tech.diaslopes.com/?p=28</guid>
		<description><![CDATA[Using the attribute in a html tag is commonly advised as a good practice, however it&#8217;s rare to see it in action. I think its lack of usage is related with browser compatibility and the developer&#8217;s skepticism to implement it. &#8230; <a href="http://tech.diaslopes.com/?p=28">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class='compat'><dl><dt>Compatibility:</dt><dd class='ff'><a title='Partial' class=''></a></dd><dd class='ie'><a title='Compatible' class=''></a></dd><dd class='chrome'><a title='Partial' class=''></a></dd><dd class='safari'><a title='Partial' class=''></a></dd><dd class='opera'><a title='Not compatible' class='disabled'></a></dd></dl></div>
<p>Using the <code class="prettyprint">defer</code> attribute in a html <code class="prettyprint">&lt;script&gt;</code> tag is commonly advised as a good practice, however it&#8217;s rare to see it in action. I think its lack of usage is related with browser compatibility and the developer&#8217;s skepticism to implement it.</p>
<p>Setting this attribute means that the script execution will be delayed and it will run after all the contents are loaded, parsed and executed, just before the onload event. The deferred files will start downloading when the <code class="prettyprint">&lt;script&gt;</code> tag is parsed, however it won&#8217;t block the other process and it will allow parallel downloads of other resources of the page. This can be very useful to avoid heavy JavaScript execution at start that blocks the browser UI rendering leading to blank screens and unresponsive applications.</p>
<p><span id="more-28"></span></p>
<h2>The experiment</h2>
<p>In order to better understand how this attribute works, I have written the following code:</p>
<pre class="prettyprint">
&lt;!-- inline scripts --&gt;
&lt;script&gt;
	var test1 = "fail";
&lt;/script&gt;
&lt;script defer&gt;
	console.log(test1);
&lt;/script&gt;
&lt;script&gt;
	test1 = "success";
&lt;/script&gt;</p>
<p>&lt;!-- external scripts --&gt;
&lt;script src="script1.js"&gt;&lt;/script&gt;
&lt;script src="script2.js" defer&gt;&lt;/script&gt;
&lt;script src="script3.js"&gt;&lt;/script&gt;</p>
<p>&lt;!-- document events --&gt;
&lt;script&gt;
	window.onload = function()
	{
		alert("onload");
	};
&lt;/script&gt;
</pre>
<p>The external scripts have almost the same code as the code in the inline <code class="prettyprint">&lt;script&gt;</code> tags, the only difference is that instead of the variable test1, I use test2.</p>
<p>For a full <code class="prettyprint">defer</code> implementation we expect the &#8220;success&#8221; string to be outputted in the console twice and finally the onload message.</p>
<table class="results">
<thead>
<tr>
<td></td>
<th>Firefox 7</th>
<th>Chrome 15</th>
<th>Safari 5.1</th>
<th>Internet Explorer 9</th>
<th>Opera 11.5</th>
</tr>
</thead>
<tbody>
<tr>
<th>Inline script</th>
<td><span class="check false"></span></td>
<td><span class="check false"></span></td>
<td><span class="check false"></span></td>
<td><span class="check true"></span></td>
<td><span class="check false"></span></td>
</tr>
<tr>
<th>External script</th>
<td><span class="check true"></span></td>
<td><span class="check true"></span></td>
<td><span class="check true"></span></td>
<td><span class="check true"></span></td>
<td><span class="check false"></span></td>
</tr>
</tbody>
</table>
<p>The <code class="prettyprint">defer</code> in Firefox 7, Chrome 15 and Safari 5.1 only works for external scripts. Internet Explorer implements it correctly. Opera does not work at all. Even if there isn&#8217;t a full support for deffered scripts you can profit from its performance capabilties in the compatible browsers.</p>
]]></content:encoded>
			<wfw:commentRss>http://tech.diaslopes.com/?feed=rss2&#038;p=28</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DOM insertAdjacentHTML</title>
		<link>http://tech.diaslopes.com/?p=21</link>
		<comments>http://tech.diaslopes.com/?p=21#comments</comments>
		<pubDate>Fri, 07 Oct 2011 23:19:47 +0000</pubDate>
		<dc:creator>Marco Dias Lopes</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[dom]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://tech.diaslopes.com/?p=21</guid>
		<description><![CDATA[Inserting an HMTL string inside or as a sibling of a DOM node should be simple, even when the DOM node has already some content. Usually to insert a string inside an element, without replacing all of its content you &#8230; <a href="http://tech.diaslopes.com/?p=21">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class='compat'><dl><dt>Compatibility:</dt><dd class='ff'><a title='Not compatible' class='disabled'></a></dd><dd class='ie'><a title='4.0+' class=''></a></dd><dd class='chrome'><a title='1.0+' class=''></a></dd><dd class='safari'><a title='4.0+' class=''></a></dd><dd class='opera'><a title='Compatible' class=''></a></dd></dl></div>
<p>Inserting an HMTL string inside or as a sibling of a DOM node should be simple, even when the DOM node has already some content. Usually to insert a string inside an element, without replacing all of its content you need to concatenate strings or create and append nodes to accurately inserted it.</p>
<p>The DOM node <code class="prettyprint js">insertAdjacentHTML</code> method does that for you, believe it or not, this method exist in Microsoft Internet Explorer since version 4, but it is not currently supported by Firefox, it will when <a href="https://developer.mozilla.org/en/DOM/Element.insertAdjacentHTML">version 8</a> comes out.<br />
<span id="more-21"></span></p>
<h2>See it in action</h2>
<p>Imagine you have the following HTML content:</p>
<pre class="prettyprint html">
&lt;ul&gt;
&lt;li&gt;1st line here!&lt;/li&gt;
&lt;li&gt;2nd line here!&lt;/li&gt;
&lt;li&gt;3rd line here!&lt;/li&gt;
&lt;/ul&gt;
</pre>
<p>And you want to append some more content to the target element as the first line. Using the <code class="prettyprint js">insertAdjacentHTML</code> method should be something like this:</p>
<pre class="prettyprint js">
var t = document.getElementById("target");
t.insertAdjacentHTML("afterbegin", "&lt;strong&gt;Inserted content&lt;/strong&gt;");
</pre>
<p>There are 4 ways you can use the insertAdjacentHTML:</p>
<ul>
<li><em>beforebegin</em> &#8211; places the HTML before the element</li>
<li><em>afterbegin</em> &#8211; places the HTML inside the element as its first child</li>
<li><em>beforeend</em> &#8211; places the HTML inside the element as its last child</li>
<li><em>afterend</em> &#8211; places the HTML after the element</li>
</ul>
<p>You can find more info about this matter at <a href="http://html5.org/specs/dom-parsing.html#insertadjacenthtml%28%29">HTML5.org specs</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://tech.diaslopes.com/?feed=rss2&#038;p=21</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

