doT.js Tutorial part 1


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94

doT.js Tutorial: Part 1 of 2

What’s dot.js?

It’s one of the fastest and concise javascript template engine for nodejs and web browsers, created by Laura Doktorova, the President & Co-Founder of Bebedo Inc.
Check out dot.js on Github.com.
dot.js works on both the client and server side. But for this tutorial, we’re only going to be focusing on the client-side.

Why use a template engine?

There are many reasons to use a template engine rather than printing your code in a given language. I think overall, the main reasons for this are code consistency and organization. If you have a good separation of your markup from your logic it becomes easier to debug your code, to share your code with collaborators, and allows for more rapid development by streamlining common methods for outputting your markup.

By: Bryce Hamrick

How to import doT.js

Just include “doT.js” using the script tag. Once included, “doT” will be added to the global namespace.

<script src="https://raw.github.com/olado/doT/master/doT.js"></script>

Steps for using doT.js

  1. Create an object literal to store your data. A JSON format is preferred.

    var data = { name: "David" };

  2. Create a template that creates the overall structure and tells where your data will be placed.

    var template = "Hey <b>{{=it.name}}</b>, you own me money.";

  3. Generate a template function from the template using doT.template().

    var templateFunction = doT.template( template );

  4. Generate HTML by providing data to the template function.

    var html = templateFunction( data );

Full source:

var data = { name: "David" };                                 // step 1
var template = "Hey <b>{{=it.name}}</b>, you own me money.";  // step 2
var templateFunction = doT.template( template );              // step 3
var html = templateFunction( data );                          // step 4
 
// result
html == "Hey &lt;b>David&lt;/b>, you own me money.";

Let’s now examine the function doT.template().

doT.template(template, settings, userDefinedDef);

Forming a template

The content of a template will remain the same, except for the sections that contain javascript encapulated sections (JES). JES look like this. "{{ }}".
Note that the data passed to the template function can be reference by the template using the namespace ‘it’.

Example:

// input
var data = { thatThingOverThere: "Bartman" };
var template = "Hey, look over there! It's {{=it.thatThingOverThere}}!";
var tempFunc = doT.template(template);
var html = tempFunc(data);
 
// output
html == "Hey, look over there! It's Bartman!";

To better understand what’s going on, let’s look at the generated source for the tempFunc.

// source for tempFunc
function anonymous(it) {
	var out = 'Hey, look over there! It\'s '+(it.thatThingOverThere)+'!';
	return out;
}

Type of JES

There two basic type of JES.
Type 1 requires a returned value.

var template = "{{=it.value}}";

Type 2 allows for javascript statements to be executed.

var template = "{{ var global = {}; }}";


Example:

var data = { team: "POWER RANGERS!"}
var template = '{{ var chant = "Go go"; }}{{= chant + " " + it.team}}';
var tempFunc = doT.template( template );
var html = tempFunc( data );
 
// result
html == "Go go POWER RANGERS!";
 
// source for tempFunc
function anonymous(it) {
	var out=''; 
	var chant = "Go go"; 
	out+=( chant + " " + it.team);
	return out;
}

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Code of the day: jQuery, Get comments from HTML elements.


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94

Code of the day: Get comments from HTML elements.
Here’s a simple jquery plugin to get the comments from a HTML elements.

// source code for $.fn.getComments()
$(function () {
/**
* $.fn.getComments() is used to extract the html comments from a HTML elements.
* 
* @author Larry Battle <http://bateru.com/news/contact-me>
* @license MIT
* @date June 11, 2012
* @version 0.1
* @args {boolean} asArray - If true, returns an array of the comments values. 
		Otherwise returns jquery objects of the node comments.
* @example 
	HTML:
	<div id="example">I am a div. <!--Duh!--></div>
 
	Javascript: 
	$("#example").getComments(true) // returns [ "Duh!" ]
*/
	var getCommentsFromEl = function (el, asArray) {
		var result,
		$el = $(el).contents();
		result = $el.filter(function () {
				return this.nodeType == 8;
			});
		if (asArray) {
			result = $.makeArray(result.map(function () {
						return this.nodeValue;
					}));
		}
		return result;
	};
	$.fn.getComments = function (asArray) {
		return getCommentsFromEl(this, asArray);
	};
});

Demo and testcases here: http://jsfiddle.net/96rux/

Fork this on Github.com
https://github.com/LarryBattle/jQuery.getComments

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Code of the Day: Javascript, create object without calling new on the Constructor


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94

Here’s a simple trick to avoid having to call new on a constructor. All you have to do is have the constructor do it for you. Here’s how.

Check if the `this` variable is an instanceof of the Constructor. If not, then return a new instance of the constructor whiling passing the same arguments. `new ConstructorName(arg1, arg2, … argN)`.

If you call a constructor without using this trick, `this` will be referenced to the scope to which the constructor is contained within. Which in most cases is `window`.

Example:

var Person = function( name ){
    if(!(this instanceof Person)){
        return new Person(name);
    }
    this.name = name || "NA" ;
    return this;
};

Live Demo:*click the results tab*

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Code of the Day: Javascript Decimal Expansion a.k.a Division


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94


Today’s Code of the Day is about decimal expansion, which is just division.

So you might be asking yourself, “if decimal expansion is divsion. Then why not use a/b?”.
Well the problem is that Javascript has a ton of problems when dealing with floating point operations because of the way they are stored.

Examples:

var a = 1/3;
a.toString()     // returns  "0.3333333333333333"
a.toFixed(25);   // returns "0.3333333333333333148296163"
0.1 + 0.2;       // returns 0.30000000000000004

Source for decimalExpansion()

// borrowed from jQuery 1.7.2
var isNumeric = function(val){
	return !isNaN(parseFloat(val)) && isFinite(val);
};
/**
* @author Larry Battle <http://bateru.com/news/contact-me>
* @date May 16, 2012
* @license MIT and GPLv3
*/
//decimalExpansion returns a string representation of a divided by b to a fixed length.
// All the paramaters must be whole numbers.
// Example: decimalExpansion( 1, 3, 3 ) === "0.333"
var decimalExpansion = function (top, bottom, decLength) {
	if (!isNumeric(top) || !isNumeric(bottom) || !isNumeric(decLength) || !bottom) {
		return null;
	}
	var sign = ((top * bottom) != Math.abs(top * bottom)) ? "-" : "";
	top = Math.abs(top);
	bottom = Math.abs(bottom);
	decLength = Math.abs(decLength);
 
	var result = Math.floor(top / bottom),
	remainder = top % bottom,
	maxDecimal = 100,
	i = Math.min(Math.max(0, decLength), maxDecimal) + 1;
 
	if (1 < i) {
		result += ".";
		while (i--) {
			top = remainder * 10;
			remainder = top % bottom;
			result += "" + Math.floor(top / bottom);
		}
		result = result.replace(/(\d)(\d)$/, function (match, a, b) {
				return +b > 4 ? +a + 1 : a;
			});
	}
	return sign + result;
};

Test cases:

Demo:

Here are excellent links over the topic.
Wolfram MathWorld: Decimal Expansion
Wikipedia.org: Fraction (mathematics)
Oracle: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube