<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
  <channel>
    <title>lostsyntax.net posts</title>
    <link>http://lostsyntax.net/posts</link>
    <description>lostsyntax general news</description>
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/LostSyntax" /><feedburner:info uri="lostsyntax" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
      <title>Publishing Events In YUI3</title>
      <link>http://feedproxy.google.com/~r/LostSyntax/~3/kByiX0JybGU/3</link>
      <description>&lt;p&gt;
One of the things I love most about YUI3 is the event utility. Firing and listening for custom events makes solving typically tedious problems easy, allows for true extensibility in the application and compartmentalizes functionality into logical buckets. Let’s examine the following issue and how we might use YUI3’s event structure to help solve it.
&lt;/p&gt;
&lt;p&gt;
The sign in and sign out events are two of the most interesting events that could impact a web application on multiple levels. For the purpose of this example we will use the sign out event and follow how that might effect a web application with several widgets residing in it.
&lt;/p&gt;
&lt;p&gt;
We’ll start off with a simple page that contains a cart widget that holds a number of items we have in our cart. When the user signs out we will want to empty the cart without refreshing the page, as the user may be in the middle of a search or some other important action that we don’t want to interrupt if possible. Since we use authentication and carts on many sites it makes sense to turn these two items into YUI3 widgets that will handle our events. YUI3 widgets are designed to handle common user interface patterns in applications. Here’s what a simple cart widget may look like:
&lt;/p&gt;
&lt;pre&gt;
&lt;code&gt;
YUI.add('cart', function(Y) {		
	function Cart( config ) {
		Cart.superclass.constructor.apply( this, arguments );
	}

	Cart.NAME = "cart";
	
	Y.extend( Cart, Widget, {
		initializer : function() {
		},
		destructor : function() {
		},
		renderUI : function() {
			this.countNode = this.get('srcNode').one('.cartCount');
		},
		bindUI : function() {
			Y.on('auth:signOut', this._emptyCart, this);
		},
		syncUI : function() {
		},
		_emptyCart : function(e){
			this.countNode.set('innerHTML', '0');
		}
	});
		
	Y.Cart = Cart;
			
}, '1.0.0' ,{requires:[ 'widget' ], skinnable:false});
&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;
If you aren’t familar with YUI3 widgets let me briefly run down what’s happening here. The first line of this code registers our widget to the YUI instance in which it’s being used. A little further down we are extending the Widget class which provides us with some basic functionality. When the new method is called on our widget the initilazer function is immediately called. Likewise, destructor on destroy. When we call render on our widget three functions are called: renderUI, bindUI and syncUI. In our example renderUI sets this.countNode to the carts count span so that we may manipulate those contents later. 
&lt;/p&gt;
&lt;p&gt;
After renderUI sets the countNode we are now ready to bind our listener: Y.on('auth:signOut', this._emptyCart, this). This simple line tells our widget to listen for the signOut event and perform an action when it happens. In this case it calls the _emptyCart function which simply sets the innerHTML of our count span to 0.
&lt;/p&gt;
&lt;p&gt;
Next we will create an authentication widget that would likely contain functions to handle signing in and out. For our example we’ll create a simple handler for when the sign out button is clicked.
&lt;/p&gt;
&lt;pre&gt;
&lt;code&gt;
YUI.add('auth', function(Y) {
	function Auth( config ) {
 		Auth.superclass.constructor.apply( this, arguments );
	}

	Auth.NAME = "auth";
	
	Y.extend( Auth, Y.Widget, {
		initializer : function() {
			////////////////////////////////////////////////////////
			// Create custom events
			////////////////////////////////////////////////////////
			this.publish("signOut", {
                                broadcast: 1
			});
			
		},
		destructor : function() {
		},
		renderUI : function() {
			this.signOutNode = this.get('srcNode').one('#signOut');
		},
		bindUI : function() {
			this.signOutNode.on('click', this._signOut, this);
		},
		syncUI : function() {
		},
		_signOut : function(e){
			e.preventDefault();
			this.signOutNode.set('innerHTML', 'sign in');

			this.fire('signOut');
		}
	});
	
	Y.Auth = Auth;
			
}, '1.0.0' ,{requires:[ 'widget', 'event-custom' ], skinnable:false});
&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;
The structure of this widget is similar to the cart widget.  We are setting this.signOutNode to the sign out button and attaching a click event. The click event fires a custom event called signOut. Our initializer function is what I want to spend a little more time on.
&lt;/p&gt;
&lt;pre&gt;
&lt;code&gt;
this.publish("signOut", {
        broadcast: 1
});
				
&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;
The first line of code creates a custom event called signOut passing in a paramater of broadcast:1. Broadcast will notify the YUI instance every time this event is fired. This allows us to use the line Y.on(‘auth:signOut’) in our cart widget.
&lt;/p&gt;
&lt;p&gt;
Putting it all together our HTML document looks something like this:
&lt;/p&gt;
&lt;pre&gt;
&lt;code&gt;
&amp;lt;head&amp;gt;
	&amp;lt;script src="http://yui.yahooapis.com/3.3.0/build/yui/yui-min.js"&amp;gt;&amp;lt;/script&amp;gt;
	
	&amp;lt;script&amp;gt;
		        
		YUI({
			modules:  {
				cart: {
		        	fullpath: 'cart.js',
					requires: ['widget', 'event-custom',]
				},
				auth: {
				fullpath: 'auth.js',
					requires: ['widget', 'event-custom']
				}
			}
		}).use('node', 'cart', 'auth', function(Y) {
			var myCart = new Y.Cart({
				srcNode : Y.one('#cart')
			});
			
			myCart.render();
			
			var myAuth = new Y.Auth({
				srcNode : Y.one('#auth')
			})
			
			myAuth.render();
		});
			
	&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
&amp;lt;div id="auth"&amp;gt;
	&amp;lt;button id="signOut"&amp;gt;Sign Out&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;div id="cart"&amp;gt;
	&amp;lt;span class="cartCount"&amp;gt;5&amp;lt;/span&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;
&lt;/pre&gt;
&lt;h3&gt;In Conlusion&lt;/h3&gt;
&lt;p&gt;
Could we have handled this more procedurally? Sure. This is a simple example that could have been handled many different ways. As you begin adding complexity in the form of additional widgets or porting of these widgets into other applications the power and grace of the custom events become apparent.
&lt;/p&gt;
&lt;p&gt;&lt;a href='http://www.davidmart.in/play/events/'&gt;View a working sample here&lt;/a&gt;&lt;/p&gt;</description>
      <guid isPermaLink="false">http://lostsyntax.net/posts/3</guid>
    <feedburner:origLink>http://lostsyntax.net/posts/3</feedburner:origLink></item>
    <item>
      <title>Redux</title>
      <link>http://feedproxy.google.com/~r/LostSyntax/~3/snXLe6mX8eA/4</link>
      <description>&lt;p&gt;It has been some time since I have generated content of any sort outside of work. As time went on I found myself slipping into a very comfortable place in my life. Typically one might think comfort to be a positive thing, not for anyone who is accustomed to pushing their limits.&lt;/p&gt;
&lt;p&gt;This is where Lost Syntax comes into play. While I still enjoy those things which made my life so comfortable to begin with, it's time I start contributing to the greater community I have taken so much from. My writing is very likely stale and out practice. This is something I promise to work on.&lt;/p&gt;
&lt;p&gt;As I begin publishing content to the site there are several things I would like you, the reader, to keep in mind. Please, I cannot stress this enough, let me know when I have mis-spoken. I will be relaying my experiences on specific topics for two primary reasons. First, I would like to offer my solution to anyone who may be in a similar situation. Second, a very selfish reason, I would like to learn from you. So with that, let's begin this journey.&lt;/p&gt;</description>
      <guid isPermaLink="false">http://lostsyntax.net/posts/4</guid>
    <feedburner:origLink>http://lostsyntax.net/posts/4</feedburner:origLink></item>
    <item>
      <title>My Solution For HTML Templating</title>
      <link>http://feedproxy.google.com/~r/LostSyntax/~3/qjwSyDLztUE/5</link>
      <description>&lt;p&gt;
I am a big fan of separating application logic from presentation as much as possible. JavaScript naturally tends to blur the lines between these two areas which makes it extremely easy to just throw them both into a giant interface mixing pot. This method proves to be extremely inefficient when you are building applications that require maintenance by individuals who are not expected to know a bit of JavaScript. I have landed on a happy medium for several of my recent projects. I would like to share that process and inquire as to how you may handle this.
&lt;/p&gt;
&lt;h3&gt;The Problem&lt;/h3&gt;
&lt;p&gt;
We will start with a page that has sent an XHR request to the server, a search perhaps. This search may return ten to several hundred results. You could simply have the server return a giant chunk of HTML containing your full search results. The JavaScript then needs to only append the results to the appropriate place on the document. That would be the easy way out. HTML adds a bunch of unimportant pieces of data to the stream that our browser is handling.
&lt;/p&gt;

&lt;h3&gt;Simple Solution&lt;/h3&gt;
&lt;p&gt;
To help our browser while it chokes down the data we can instead request a JSON object from our server. Several hundred results may still be large, but we’ve likely cut our total size down by a significant value. This leaves us with the problem of displaying this information. Each record has the same display properties, just different values. We could just loop over each object in our code and use a replace command on a pre-determined string to populate our data correctly. This is how it might look in vanilla JavaScript:
&lt;/p&gt;
&lt;pre&gt;
&lt;code&gt;
var htmlSnip = "&amp;lt;p&amp;gt;Your name is: {name}, Your Position is: {title}&amp;lt;/p&amp;gt";
	var content = '';
	for (var x=0; x&amp;lt;mydata.length; x++){
		tmp = htmlSnip.replace('{name}', mydata[x].firstName);
		tmp = tmp.replace('{title}', mydata[x].title);
		content += tmp;
	}
	document.getElementById('wrapper').innerHTML = content;
&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;
Loop over each record in our data set and replace our predetermined variables with information from the data. In this example I have used {name} and {title} to create a variables for replacing later.
&lt;/p&gt;
&lt;p&gt;
This scenario however is less than ideal if we are working with a team that may have minimal or no JavaScript knowledge. The site may have rolled to production months ago and is now handled by a new HTML developer. It would be ideal if we can move our HTML out of the JavaScript entirely. If we move it to the body of the HTML document it will reside in the same place as the rest of the presentation. Here is a sample:
&lt;/p&gt;
&lt;pre&gt;
&lt;code&gt;
&lt;!-- Edit content inside of the div with an ID of template. Do not modify the div. --&gt;
	&amp;lt;div id="template" style="display: none;"&amp;gt;
		&amp;lt;p&amp;gt;Your name is: {name}, Your Position is: {title}&amp;lt;/p&amp;gt;
	&amp;lt;/div&amp;gt;
&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;
The template now sits in the HTML document, removed completely from our JavaScript logic.
&lt;/p&gt;
&lt;pre&gt;
&lt;code&gt;
var htmlSnip = "&amp;lt;p&amp;gt;Your name is: {name}, Your Position is: {title}&amp;lt;/p&amp;gt;";
&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;
becomes:
&lt;/p&gt;
&lt;pre&gt;
&lt;code&gt;
	var htmlSnip = document.getElementById(‘template’).innerHTML;
&lt;/code&gt;
&lt;/pre&gt;

&lt;h3&gt;A YUI3 Version Using Substitute&lt;/h3&gt;
&lt;p&gt;
It’s possible that we will need to re-use this code. For that, I have called in the help of YUI3. Converting the JavaScript above to YUI3 yields the following:
&lt;/p&gt;
&lt;pre&gt;
&lt;code&gt;
var content = '';
	var htmlSnip = Y.one('#template').get('innerHTML');
	Y.each(mydata, function(person){
		content += 	Y.substitute( htmlSnip, {
			name: person.firstName,
			title: person.title
		});
	});
	Y.one('#wrapper').set('innerHTML', content);
&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;
If you are processing a lot of templates you could turn this into an object and simply call:
&lt;/p&gt;
&lt;pre&gt;
&lt;code&gt;			
var myTemplate = new Y.fastTemplate({
data: mydata,
		templateNode: Y.one('#template'),
		wrapperNode: Y.one('#wrapper')
	});

myTemplate.process();
&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt;
The base object for that looks like this:
&lt;/p&gt;
&lt;pre&gt;
&lt;code&gt;
YUI.add('fastTemplate', function(Y) {
		function fastTemplate( config) 
		{
	 		fastTemplate.superclass.constructor.apply( this, arguments );
		}
		
		fastTemplate.NAME = "fastTemplate";
		
		fastTemplate.ATTRS = {
			data : {},
			variables: {},
			templateNode: {},
			wrapperNode: {}
		};
		
		Y.extend( fastTemplate, Y.Base, {
			process : function() {
				var content = '';
				var myData = this.get('data');
				var htmlSnip = this.get('templateNode').get('innerHTML');
				Y.each(myData, function(i){
					content += Y.substitute( htmlSnip, i);
				}, this);
				this.get('wrapperNode').set('innerHTML', content);
			}
		});
		
		Y.fastTemplate = fastTemplate;
}, '0.0.1' ,{requires:[ 'node', 'base', 'substitute']});
&lt;/code&gt;
&lt;/pre&gt;

&lt;a href=http://www.davidmart.in/play/fast_template&gt;View a sample of the base object in action.&lt;/a&gt;
&lt;p&gt;&lt;a href=https://github.com/drmartin1998/FastTemplate&gt;On GitHub&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;In Closing&lt;/h3&gt;
&lt;p&gt;
I’m curious what other people are using out there. I’d like to know if you have any suggestions or updates to what I have here.
&lt;/p&gt;
</description>
      <guid isPermaLink="false">http://lostsyntax.net/posts/5</guid>
    <feedburner:origLink>http://lostsyntax.net/posts/5</feedburner:origLink></item>
    <item>
      <title>Add/Remove YUI3 Module</title>
      <link>http://feedproxy.google.com/~r/LostSyntax/~3/PuLIHMBqNkk/7</link>
      <description>&lt;p&gt;
I often work on interfaces where a user is adding to a list of information. Typically it’s a list of locations or addresses that we are storing to the users account. I wrote a small module sometime ago that handled this and recently submitted it to the YUI3 Gallery. Here’s a quick sample of how you might implement this:
&lt;/p&gt;
&lt;h3&gt;Sample Use&lt;/h3&gt;
&lt;pre&gt;
&lt;code&gt;		
YUI({
modules:  {
		           ‘gallery-add-remove': {
		            		fullpath: '/play/addRemove/gallery-add-remove.js'
		           	}
		}
	}).use('base', 'anim', 'widget', 'json', 'node', 'substitute', 'gallery-add-remove', function(Y) {
		Y.on("domready", function(){
			var addRemove = new Y.addRemove({
				addNode: Y.one('#locationAddButton'),
				removeNode: Y.one('#locationRemoveButton'),
				originalNode: Y.one('.locationWrapper'),
				animate: true
			});
			
			addRemove.init();
            		});
});
&lt;/code&gt;
&lt;/pre&gt;
&lt;p&gt; The module accepts 4 attributes: addNode, removeNode, originalNode, animate.&lt;/p&gt;
&lt;pre&gt;
&lt;code&gt;
&amp;lt;div class="locationWrapper" style="border: 1x solid #ccc; margin: 20px;"&amp;gt;
	&amp;lt;div&amp;gt;Location Address: &amp;lt;input type="text"&amp;gt;&amp;lt;/div&amp;gt;
	&amp;lt;div&amp;gt;Location Phone: &amp;lt;input type="text"&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;button type="button" id="locationAddButton"&amp;gt;Add&amp;lt;/button&amp;gt;
&amp;lt;button type="button" id="locationRemoveButton"&amp;gt;Remove&amp;lt;/button&amp;gt;

&lt;/code&gt;
&lt;/pre&gt;
&lt;h3&gt;Try It Out&lt;/h3&gt;
&lt;p&gt;
		&lt;script&gt;


YUI({
	modules:  {
		'gallery-add-remove': {
			fullpath: '/play/addRemove/gallery-add-remove.js'
		 }
	}
	}).use('base', 'anim', 'widget', 'json', 'node', 'substitute', 'gallery-add-remove', function(Y) {
		Y.on("domready", function(){
			var addRemove = new Y.addRemove({
				addNode: Y.one('#locationAddButton'),
				removeNode: Y.one('#locationRemoveButton'),
				originalNode: Y.one('.locationWrapper'),
				animate: true
		});
			
	addRemove.init();

 	});
});

		&lt;/script&gt;
	&lt;/head&gt;
	
&lt;div class="sample"&gt;
&lt;div class="locationWrapper" style="border: 1x solid #ccc; margin: 20px;"&gt;
	&lt;div&gt;Location Address: &lt;input type="text"&gt;&lt;/div&gt;
	&lt;div&gt;Location Phone: &lt;input type="text"&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;button type="button" id="locationAddButton" class="sampleButton"&gt;Add&lt;/button&gt;
&lt;button type="button" id="locationRemoveButton" class="sampleButton"&gt;Remove&lt;/button&gt;
&lt;/div&gt;
&lt;/p&gt;
&lt;p&gt;
It’s not a complicated procedure, but it helps save some time. You can download/view the module from the &lt;a href=http://yuilibrary.com/gallery/show/add-remove&gt;YUI Gallery&lt;/a&gt;
&lt;/p&gt;</description>
      <guid isPermaLink="false">http://lostsyntax.net/posts/7</guid>
    <feedburner:origLink>http://lostsyntax.net/posts/7</feedburner:origLink></item>
  </channel>
</rss>

