<?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>frag   (frăg)</title>
	<atom:link href="http://fragged.org/feed" rel="self" type="application/rss+xml" />
	<link>http://fragged.org</link>
	<description>frag   (frăg) [..] 2. To completely ruin something.</description>
	<lastBuildDate>Mon, 14 Aug 2017 20:58:18 +0000</lastBuildDate>
	<language>en-GB</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.8.15</generator>
	<item>
		<title>The bane of all reactjs newbies: binding event handlers</title>
		<link>http://fragged.org/solving-the-bane-of-all-reactjs-newbies-binding_1690.html</link>
		<comments>http://fragged.org/solving-the-bane-of-all-reactjs-newbies-binding_1690.html#respond</comments>
		<pubDate>Mon, 14 Aug 2017 15:59:03 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[react]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1690</guid>
		<description><![CDATA[It is fair to say at least 1/3 of all reactjs questions posted on StackOverflow can be solved by understanding simple DOM event handler binding. Typically, they look like this: class EmailSignup extends React.Component { state = { email: '' } handleChange({target}) { this.setState({email: target.value}) } render(){ return &#60;input onChange={this.handleChange} value={this.state.email} /&#62; } } And then comes the dreaded error...<span class="path-read-more"><a class="more-link" href="http://fragged.org/solving-the-bane-of-all-reactjs-newbies-binding_1690.html" title="The bane of all reactjs newbies: binding event handlers">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>It is fair to say at least 1/3 of all <a href="https://stackoverflow.com/questions/tagged/reactjs">reactjs questions</a> posted on StackOverflow can be solved by understanding simple DOM event handler binding.</p>
<p>Typically, they look like this:</p>
<pre><code>class EmailSignup extends React.Component {
  state = {
    email: ''
  }

  handleChange({target}) {
    this.setState({email: target.value})
  }

  render(){
    return &lt;input onChange={this.handleChange} value={this.state.email} /&gt;
  }
}</code></pre>
<p>And then comes the dreaded error and a new forum post:</p>
<blockquote><p>TypeError: Cannot read property &#8216;setState&#8217; of undefined on line 8.</p></blockquote>
<p>This is an event handler, contextually <code>this</code> will be the <code>event.target</code> by default. Patterns to solve it are so many&#8230;</p>
<p>1. Preferred way is to bind the method to your instance in your constructor.</p>
<pre>constructor(props){
  super(props)
  this.state = { email: props.email }
  this.handleChange = this.handleChange.bind(this)
}
</pre>
<p>It is preferred as it happens once only at instantiation of the component, so it&#8217;s cheap.</p>
<p>2. Use an arrow function to keep contextual <code>this</code>. This works but makes a new function on every render of your component (tree)</p>
<pre>render(){
  return &lt;input onChange={event => this.handleChange(event)} value={this.state.email} /&gt;
}
</pre>
<p>3. Use local binding. It works but also makes a new function on every render of your component (tree)</p>
<pre>render(){
  return &lt;input onChange={this.handleChange.bind(this)} value={this.state.email} /&gt;
}
</pre>
<p>4. Use the new experimental (not in ECMAScript yet[tm]) bind syntax <code>::</code>. Essentially, sugar for #3</p>
<pre>render(){
  return &lt;input onChange={::this.handleChange} value={this.state.email} /&gt;
}
</pre>
<p>5. Use the new <a href="https://babeljs.io/docs/plugins/transform-class-properties/">Class property transforms</a></p>
<pre>
// just inside your class definition - just like the state = 
handleChange = ({target}) => {
  this.setState({email: target.value})
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/solving-the-bane-of-all-reactjs-newbies-binding_1690.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CSS fun: labels that change colour when their input is focused</title>
		<link>http://fragged.org/css-fun-labels-that-change-colour-when-their-input-is-focused_1682.html</link>
		<comments>http://fragged.org/css-fun-labels-that-change-colour-when-their-input-is-focused_1682.html#respond</comments>
		<pubDate>Mon, 01 Jun 2015 15:20:26 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[css]]></category>
		<category><![CDATA[fragged]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1682</guid>
		<description><![CDATA[This is the sort of UX that should be easy to do, but is not. CSS pseudos allow us to style different form input states, like input:focus. This is fine but ever wanted to also highlight the label element for that input? You just can&#8217;t do it. Typical markup is: &#60;label for="email">LOGIN&#60;/label> &#60;input required type="email" name="email" id="email" class="dark-input" /> CSS3...<span class="path-read-more"><a class="more-link" href="http://fragged.org/css-fun-labels-that-change-colour-when-their-input-is-focused_1682.html" title="CSS fun: labels that change colour when their input is focused">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>This is the sort of UX that should be easy to do, but is not.</p>
<p>CSS pseudos allow us to style different form input states, like <code>input:focus</code>. This is fine but ever wanted to also highlight the <code>label</code> element for that input? You just can&#8217;t do it.</p>
<p>Typical markup is:</p>
<pre>
&lt;label for="email">LOGIN&lt;/label>
&lt;input required type="email" name="email" id="email" class="dark-input" />
</pre>
<p>CSS3 has no backreference (reverse combinator) selector so we can&#8217;t go <code>input:focus < label</code> or whatever syntax (eg. <code>!</code> in MooTools Slick). 

What you can do is apply a sibling style instead by re-arranging your DOM



<pre>
&lt;input required type=&#8221;email&#8221; name=&#8221;email&#8221; id=&#8221;email&#8221; class=&#8221;dark-input&#8221; />
&lt;label for=&#8221;email&#8221;>LOGIN&lt;/label>
</pre>
<p>The above HTML now allows for the natural CSS selector of:</p>
<pre>
input:focus + label {
    color: white;
}
</pre>
<p>But now the label looks like it&#8217;s underneath the control. You can move it back up by using some <code>translate()</code> to offset the order:</p>
<pre>
label {
    transform: translate(0, -30px);
    color: #ccc;
}
</pre>
<p>Want to see it in all in action? Here comes batman&#8230; </p>
<p><iframe height='350' scrolling='no' src='//codepen.io/DimitarChristoff/embed/BNKpRY/?height=350&#038;theme-id=0&#038;default-tab=result' frameborder='no' allowtransparency='true' allowfullscreen='true' style='width: 100%;'>See the Pen <a href='http://codepen.io/DimitarChristoff/pen/BNKpRY/'>Bank of Gotham Login</a> by Dimitar Christoff (<a href='http://codepen.io/DimitarChristoff'>@DimitarChristoff</a>) on <a href='http://codepen.io'>CodePen</a>.<br />
</iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/css-fun-labels-that-change-colour-when-their-input-is-focused_1682.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using RequireJS sugar syntax in main.js files</title>
		<link>http://fragged.org/using-requirejs-sugar-syntax-in-main-js-files_1679.html</link>
		<comments>http://fragged.org/using-requirejs-sugar-syntax-in-main-js-files_1679.html#respond</comments>
		<pubDate>Sun, 06 Apr 2014 11:16:12 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[amd]]></category>
		<category><![CDATA[requirejs]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1679</guid>
		<description><![CDATA[I love the sugar API of RequireJS. It&#8217;s elegant, clean and nearly identical to CommonJS. However, the examples often fail to demonstrate how to use it from a main.js file which does a require call, rather than a define. Doing something like this is quite useful, particularly when your config object is not a require call in itself: (function(config, require,...<span class="path-read-more"><a class="more-link" href="http://fragged.org/using-requirejs-sugar-syntax-in-main-js-files_1679.html" title="Using RequireJS sugar syntax in main.js files">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>I love the <a href="http://requirejs.org/docs/whyamd.html#sugar" target="_blank">sugar API</a> of RequireJS. It&#8217;s elegant, clean and nearly identical to CommonJS.</p>
<p>However, the examples often fail to demonstrate how to use it from a <code>main.js</code> file which does a <code>require</code> call, rather than a <code>define</code>. Doing something like this is quite useful, particularly when your config object is not a require call in itself:</p>
<pre>
(function(config, require, define){
    'use strict';

    // config in
    require.config(config);

    // main logic, wrapped in a define but working as a require
    define(function(require){
        var App = require('apps/foo/controllers/main'),
            instance = new App();
    });
}.call(this, {
    baseUrl: 'js',

    paths: {
        apps: '../bower_components/',
        react: '../bower_components/react/react'
    }
}, require, define); 
// passes local refs to closure, sets scope to global object with strict mode on.
</pre>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/using-requirejs-sugar-syntax-in-main-js-files_1679.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing Epik: micro MVC on top of primish and lodash</title>
		<link>http://fragged.org/introducing-epik-micro-mvc-on-top-of-primish-and-lodash_1665.html</link>
		<comments>http://fragged.org/introducing-epik-micro-mvc-on-top-of-primish-and-lodash_1665.html#respond</comments>
		<pubDate>Wed, 19 Mar 2014 13:28:07 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[epik]]></category>
		<category><![CDATA[Epitome]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1665</guid>
		<description><![CDATA[Nearly two years ago, I started work on Epitome, an MVC framework for MooTools. And today, it&#8217;s pretty stable and a viable project to use, if you have MooTools in your stack, rather than jQuery. Unfortunately, less and less people use MooTools these days, myself included. This made Epitome redundant &#8211; and yet I wanted to continue using the API....<span class="path-read-more"><a class="more-link" href="http://fragged.org/introducing-epik-micro-mvc-on-top-of-primish-and-lodash_1665.html" title="Introducing Epik: micro MVC on top of primish and lodash">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>Nearly two years ago, I started work on <a href="http://epitome-mvc.github.io/Epitome/">Epitome</a>, an MVC framework for MooTools. And today, it&#8217;s pretty stable and a viable project to use, if you have MooTools in your stack, rather than jQuery.</p>
<p>Unfortunately, less and less people use MooTools these days, myself included. This made Epitome redundant &#8211; and yet I wanted to continue using the API.</p>
<p>So, without further delays, I present <a href="http://dimitarchristoff.github.io/epik/" title="http://dimitarchristoff.github.io/epik/">Epik</a>.  </p>
<p>API is nearly identical with Epitome, with some slight changes and fixes. If anything, Epik is more powerful and more resilient. Built on top of the tiny class library <a href="http://dimitarchristoff.github.io/primish/" title="http://dimitarchristoff.github.io/primish/">Primish</a>, it even offers a syntax that is similar to that of MooTools. </p>
<p>Architecture wise, it is built on top of <code>lodash</code> with <code>jQuery</code> or <code>zepto</code> for the views and a RivetsJS adapter for bi-directional model binding. </p>
<p>What does the code look like?</p>
<pre>
;(function(factory){
        // works under nodejs (CJS) and requirejs (AMD)
	if (typeof define == 'function' && define.amd){
		define([
			'epik/index',
			'epik/model'
		], factory);
	} else if (typeof module != 'undefined' && module.exports){
		module.exports = factory(
			require('epik'),
			require('epik/lib/model')
		);
	}
}).call(this, function(epik, model, big){
        // currency pair model
	var cp = epik.primish({

		extend: model,

		options: {
			refreshMin: 100,
			refreshMax: 2000
		},

		validators: {
			size: function(value){
				return Number(value) == value || 'size needs to be a number';
			}
		},

		defaults: {
			title: '',
			formatter: '0.0000',
			bid: 0,
			ask: 0,
			oldBid: 0,
			oldAsk: 0,
			changeBid: '',
			changeAsk: ''
		},
                
                constructor: function(data){
			this.parent('constructor', data);
			this.set('spread', spreads[this.get('title')] || 1);

			this.formatter = this.get('formatter').replace(/[1-9]/g, '0');
			this.set('formatter', null, true);
			this.maxPips = Number(this.formatter.substring(0, this.formatter.length - 2) + _.random(50,70));
		}
	});


	return cp;
});
</pre>
<p>Available via web, Bower and npm (node), written with UMD wraps throughout. </p>
<p>For more complete examples, look at the following:</p>
<ul>
<li><a href="http://fragged.org:8000/">Currency Pairs</a> demo, repo here: <a href="https://github.com/dimitarchristoff/cp">https://github.com/dimitarchristoff/cp</a>, via RivetsJS bindings</li>
<li>The classic <a href="https://github.com/epitome-mvc/todomvc/tree/epik/labs/dependency-examples/epik" title="epik todomvc">TodoMVC implementation</a></li>
<li><a href="https://github.com/DimitarChristoff/epik/tree/master/dist/example">Examples in epik repo</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/introducing-epik-micro-mvc-on-top-of-primish-and-lodash_1665.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CSS-only Modal Window dialogue</title>
		<link>http://fragged.org/css-only-modal-window-dialogue_1657.html</link>
		<comments>http://fragged.org/css-only-modal-window-dialogue_1657.html#respond</comments>
		<pubDate>Thu, 28 Nov 2013 11:28:57 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[css]]></category>
		<category><![CDATA[modal]]></category>
		<category><![CDATA[vertical-centering]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1657</guid>
		<description><![CDATA[There was a time when we used to spend ages writing various Modal Window plugins in JavaScript. But with browser support for IE6-7 now pretty much dead and IE8 on its knees, it is time to explore different routes. So I give you the demo first: http://jsfiddle.net/dimitar/fFzKg/ Several things that are special in this implementation that has no JavaScript whatsoever....<span class="path-read-more"><a class="more-link" href="http://fragged.org/css-only-modal-window-dialogue_1657.html" title="CSS-only Modal Window dialogue">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>There was a time when we used to spend ages writing various Modal Window plugins in JavaScript. But with browser support for IE6-7 now pretty much dead and IE8 on its knees, it is time to explore different routes.</p>
<p>So I give you the demo first: <a href="http://jsfiddle.net/dimitar/fFzKg/" target="_blank">http://jsfiddle.net/dimitar/fFzKg/</a></p>
<p>Several things that are special in this implementation that has no JavaScript whatsoever.</p>
<blockquote><p>Disclaimer: broken on IE6-8, also broken on windows phone. Who cares, though&#8230;</p></blockquote>
<p>Centering &#8211; using the <code>absolute-center</code> technique first &#8216;discovered&#8217; by <a href="http://designshack.net/articles/css/how-to-center-anything-with-css/#comment-684580538" target="_blank">Simon</a>.</p>
<pre>
.absolute-center {
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}
</pre>
<p>This won&#8217;t work in IE older than IE9, BTW. Caveats include: the element that gets this className needs to have a known width AND height so dynamic height changes are not going to work &#8211; you need to use <code>overflow</code> hacks within the modal body to keep it from breaking.</p>
<p>To do the toggle, a small adjacent selector hack that is reliant on the order of elements and the <code>:checked</code> pseudo selector.</p>
<pre>
&lt;style>
.modal {
    display: none;
}
input:checked + .modal {
    display: block;
}
&lt;/style>
...
&lt;input type="checkbox" id="modal1" class="hide" autocomplete="off" />
&lt;div class="absolute-center modal text-center">
    content here.
&lt;/div>

...
Press here to &lt;label for="modal1">toggle modal&lt;/label>
</pre>
<p>That&#8217;s about it &#8211; the rest are simply sugary effects. There is also a blocker div that uses the same technique. Have fun and don&#8217;t use in production &#8211; unless you only care about modern browsers anyway. </p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/css-only-modal-window-dialogue_1657.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spy on any method on an object and profile number of times called</title>
		<link>http://fragged.org/spy-on-any-method-on-an-object-and-profile-number-of-times-called_1661.html</link>
		<comments>http://fragged.org/spy-on-any-method-on-an-object-and-profile-number-of-times-called_1661.html#respond</comments>
		<pubDate>Mon, 28 Oct 2013 20:00:04 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1661</guid>
		<description><![CDATA[So, Object.observe will become a standard at some point. In the meanwhile, you may want to unobtrusively log any methods called on an object from the outside. So I wrote this little snippet that helps me do just that. Object.monitor = function(obj, quiet){ var keys = (function(obj){ // include from prototype also, any function. var keys = [], key; for...<span class="path-read-more"><a class="more-link" href="http://fragged.org/spy-on-any-method-on-an-object-and-profile-number-of-times-called_1661.html" title="Spy on any method on an object and profile number of times called">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>So, <code>Object.observe</code> will become a standard at some point. In the meanwhile, you may want to unobtrusively log any methods called on an object from the outside. So I wrote this little snippet that helps me do just that.</p>
<pre>
Object.monitor = function(obj, quiet){
	var keys = (function(obj){
			// include from prototype also, any function.
			var keys = [], key;
			for (key in obj) typeof obj[key] === 'function' && keys.push(key);
			return keys;
		}(obj)),
		// alternating foreground colours for odd/even calls.
		colours = [
			'#FFFFFF',
			'#CCCCCC'
		],
		token = '%c',
		monitor = ' monitor:',
		log = function(what, method){
			// more use goes red in console.
			console.log(token + '%d' + token + monitor + '%s',
				'font-family:courier;background-color:rgb(' + Math.min(255, what) + ',0,0);color:' + colours[+(what %2 == 0)],
				what,
				'font-family:courier',
				method
			);
		},
		counters = {};

	keys.forEach(function(key){
		var orig = obj[key];
		Object.defineProperty(obj, key, {
			get: function(){
				key in counters || (counters[key] = 0);
				counters[key]++;
				quiet || log(counters[key], key);
				return orig;
			}
		});
	});

	return function(){
		// serialize the calls and order by counts
		return {
			raw: counters,
			sorted: keys.map(function(key){
				return {
					key: key,
					value: counters[key]
				};
			}).filter(function(obj){
					return !!obj.value;
				}).sort(function(a, b){
					return a.value <= b.value;
				}).map(function(obj){
					var o = {};
					return o[obj.value] = obj.key, o;
				})
		}
	}
};
</pre>
<p>Basically, saving a reference of the original method, logging and returning the method. Downside: just asking for a reference or toSource does not guarantee the method is being called. If you need to take that into account, simply wrap the method into a function instead.</p>
<p><code>Object.monitor</code> will return a reference to a function that you can call at any time to inspect the current results.</p>
<p>To use it, simply go:</p>
<pre>
var foo = {
    count: 0,
    one: function(){
        this.count++;
    },
    two: function(){
        this.count += 2;
    }
};

var fooStats = Object.monitor(foo);
foo.one();
foo.two();
var c = 150;
while(c--) foo.one();

console.log(fooStats()); // returns an object with sorted and raw counters. 
</pre>
<p>See it in action: <a href="http://jsfiddle.net/dimitar/aCcVX/">http://jsfiddle.net/dimitar/aCcVX/</a></p>
<p>Tweaks you can do to get different methods:</p>
<pre>
// only local keys not proto
keys = Object.keys(obj).filter(... fn only ...);
// local and prototype keys on a class
keys = Object.keys(obj).concat(Object.keys(obj.constructor.prototype)).filter(... fn only ...);
</pre>
<p>The <code>quiet</code> argument will prevent it from spamming your console. You can tweak to use console.count as well if you prefer.</p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/spy-on-any-method-on-an-object-and-profile-number-of-times-called_1661.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hacking MooTools Elements and Storage / UIDs</title>
		<link>http://fragged.org/hacking-mootools-elements-and-storage-uids_1649.html</link>
		<comments>http://fragged.org/hacking-mootools-elements-and-storage-uids_1649.html#respond</comments>
		<pubDate>Mon, 23 Sep 2013 19:07:53 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[mootools]]></category>
		<category><![CDATA[mootoos]]></category>
		<category><![CDATA[slick]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1649</guid>
		<description><![CDATA[Any element that has either being created or is passed on through a selector, gets assigned a property uid, which is incremental and unique. Since MooTools 1.4.2, this is only readable via Slick.uidOf(node) and not via the old element attr .uid. You can now use the new uniqueNumber property of any MooTools Element object. How is that being used? For...<span class="path-read-more"><a class="more-link" href="http://fragged.org/hacking-mootools-elements-and-storage-uids_1649.html" title="Hacking MooTools Elements and Storage / UIDs">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>Any element that has either being created or is passed on through a selector, gets assigned a property <code>uid</code>, which is incremental and unique. Since MooTools 1.4.2, this is only readable via <code>Slick.uidOf(node)</code> and not via the old element attr <code>.uid</code>. You can now use the new <code>uniqueNumber</code> property of any MooTools Element object.</p>
<p>How is that being used? For starters, Element Storage. It relies on the uid as the key in the <code>Storage</code> object inside a closure, which will have anything you have <code>.store</code>&#8217;d for that element. </p>
<pre>
element.store('foo', 'bar');
</pre>
<p>translates to:</p>
<pre>
Storage[Slick.uidOf(element)].foo = 'bar';
</pre>
<p>and </p>
<pre>
element.retrieve('foo'); // getter of the storage key
element.eliminate('foo'); // delete Storage[Slick.uidOf(element)].foo
</pre>
<p>Initializing storage for an element you have created externally, eg, via <code>var foo = document.createElement(&#8216;div&#8217;)</code> and not Element constructor</p>
<pre>
Slick.uidOf(foo); // makes it compatible with Storage
// same as:
document.id(foo);
</pre>
<p>Things that are stored by the framework into Storage also include all <code>events</code> callbacks, <code>validators</code> instances, <code>Fx</code> instances (tween, morph etc) and so forth.</p>
<p>What can you do knowing the UIDs of elements? Well, cloning an element does NOT get the element&#8217;s storage or events. You can actually write a new <code>Element.cloneWithStorage</code> prototype that will also copy all of the stored values you may have, which is useful upto a point &#8211; instances that reference a particular element (such as, <code>Fx.Tween</code>) will continue referencing the old element, so it may have unexpected results. This can be useful in moving your own storage, though, all you need is a similar method that will record what you have stored and allow you to clone it. </p>
<p>Example Storage puncture of another Element&#8217;s data:</p>
<pre>
var foo = new Element('div'),
    uid = foo.uniqueNumber;
    
foo.store('foo', 'foo only');
    
var bar = new Element('div');

console.log(bar.retrieve('foo')); // null

bar.uniqueNumber = uid; // force overwrite of uid to the other el

console.log(bar.retrieve('foo')); // foo only - OH NOES

console.log(Object.keys(foo)); // ["uniqueNumber"] - oh dear. enumerable!
</pre>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/hacking-mootools-elements-and-storage-uids_1649.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tooling for the node.js generation, part II</title>
		<link>http://fragged.org/tooling-for-the-node-js-generation-part-ii_1625.html</link>
		<comments>http://fragged.org/tooling-for-the-node-js-generation-part-ii_1625.html#respond</comments>
		<pubDate>Tue, 23 Jul 2013 10:16:37 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[nodejs]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1625</guid>
		<description><![CDATA[In the previous article, a number of things got covered that help with npm modules you&#8217;d want to use in your node.js projects. This is a continuation. anything in a require() is an npm module, installable via npm install name Interaction with the OS require(&#8216;node-growl&#8217;) &#8211; Growl is a OSX style notification system, also available for windows or linux. node-growl...<span class="path-read-more"><a class="more-link" href="http://fragged.org/tooling-for-the-node-js-generation-part-ii_1625.html" title="Tooling for the node.js generation, part II">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>In the <a href="http://fragged.org/tooling-for-the-node-js-generation-part-i_1607.html">previous article</a>, a number of things got covered that help with npm modules you&#8217;d want to use in your <code>node.js</code> projects. This is a continuation.</p>
<blockquote><p>anything in a <strong>require()</strong> is an <strong>npm</strong> module, installable via <strong>npm install name</strong></p></blockquote>
<h3>Interaction with the OS</h3>
<ul>
<li><strong>require(&#8216;node-growl&#8217;)</strong></li>
<p> &#8211; Growl is a OSX style notification system, also available for windows or linux. <a href="https://github.com/visionmedia/node-growl">node-growl</a> abstracts having to deal with the different implementations of growl / messaging notifications between different operating systems and gives you a unified API. </p>
<pre>var growl = require('growl');
growl('5 new emails', { title: 'Email Client', image: 'Safari', sticky: true });</pre>
</li>
</ul>
<h3>Serving HTTP and sockets</h3>
<p>Often, you need to do quick prototypes, test APIs or work with a node.js backend altogether. This is a standard stack of tools that will cater for most of your needs</p>
<ul>
<li><strong>require(&#8216;express&#8217;);</strong> &#8211; <a href="http://expressjs.com/" target="_blank">Express.js</a> is great tool that allows you to set a node.js HTTP server in no time. Works with the <code>http</code> stock npm as well as support for things like <code>socket.io</code> for streaming. Here&#8217;s an <a href="http://fragged.org/epitome-now-available-as-npm-and-under-commonjs_1567.html">example express app</a> for <a href="http://epitome-mvc.github.io/Epitome/">Epitome</a></li>
<li><strong>require(&#8216;socket.io&#8217;);</strong> &#8211; a <a href="http://socket.io/" target="_blank">sockets implementation</a> available for the server and client with a wide browser support and graceful degradation by Guillermo Rauch. A viable alternative to <a href="http://kaazing.com/products/html5-edition">Kaazing</a>, no support for Binary Data Types yet</li>
<li><strong>require(&#8216;ws&#8217;);</strong> &#8211; <o>one of</o> the fastest websockets implementations available, <a href="https://npmjs.org/package/ws">ws</a> that also supports Binary Data. </li>
</ul>
<h3>Building / Generators</h3>
<p>A lot of the time, you want to automate builds and processes. </p>
<ul>
<li><strong>require(&#8216;requirejs&#8217;);</strong> &#8211; the npm version for the excellent AMD library is super cool, allowing you to use <code>r.js</code> functionality within your script and package/minify your scripts for production in a bespoke way with great control. It also allows you to use AMD modules instead of CJS, but that&#8217;s just silly, unless you want isomorphic code&#8230; How-to&#8217;s <a href="http://requirejs.org/docs/node.html">here</a>. Also, read r.js instructions for CLI use.</li>
<li><strong>require(&#8216;grunt&#8217;);</strong> &#8211; <a href="http://gruntjs.com/">GruntJS</a> is &#8230; something else. A fully blown task runner, Grunt provides a platform of config-based tasks that can aid your project in many things, including building, testing, linting, minfication, templating / generators, hot-reloaders and much more. Have a read, install <code>grunt-cli</code> and get going. P.S. sometimes, it is easier to do things w/o grunt, rather than figuring out how various grunt task runners work. Don&#8217;t use grunt for the sake of using grunt &#8211; use it when it makes sense. Make sure you scan the list of available <code>grunt tasks</code> before making your own.</li>
<li><strong>Yeoman</strong> &#8211; a whole workflow manager, using Yo (template  / generators), GruntJS and Bower for packaging. <a href="http://yeoman.io/">http://yeoman.io/</a> for hipster development. A must in your toolkit and a must on your C.V.</li>
</ul>
<p>To be continued&#8230; WIP.</p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/tooling-for-the-node-js-generation-part-ii_1625.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>primish. It&#8217;s like mootools prime but for the intarnets</title>
		<link>http://fragged.org/primish-its-like-mootools-prime-but-for-the-intarnets_1628.html</link>
		<comments>http://fragged.org/primish-its-like-mootools-prime-but-for-the-intarnets_1628.html#respond</comments>
		<pubDate>Tue, 16 Jul 2013 22:15:33 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[primish]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1628</guid>
		<description><![CDATA[We waited for ages for MooTools prime to come out and to get adopted and for web builds to show up and to become more MooTools-y. And then, we thought (me and the Grookedge who&#8217;s also a MooTools fanboi): So primish was born. Primish is just like a fork of prime that works in a browser. Out of the box.....<span class="path-read-more"><a class="more-link" href="http://fragged.org/primish-its-like-mootools-prime-but-for-the-intarnets_1628.html" title="primish. It&#8217;s like mootools prime but for the intarnets">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>We waited for ages for <a href="https://github.com/mootools/prime/" target="_blank">MooTools prime</a> to come out and to get adopted and for web builds to show up and to become more MooTools-y. And then, we thought (me and the <a href="https://github.com/grookledge">Grookedge</a> who&#8217;s also a MooTools fanboi):</p>
<p><img src="http://cdn.meme.li/instances/300x300/39768609.jpg" alt="our own prime" /></p>
<p>So <a href="http://dimitarchristoff.github.io/primish/" target="_blank">primish</a> was born. Primish is <del datetime="2013-07-16T22:42:52+00:00">just like</del> <em>a fork of</em> prime that works in a browser. <strong>Out of the box.</strong>. With AMD loaders (RequireJS, almond etc). Or without (yeah, pesky global exports). It still works in node.js as an npm module &#8211; <code>npm install primish</code>.</p>
<p>It also does a few things differently to prime and tries to be more MooTools 1.x-ish. Eg. <code>emitter</code> AND <code>options</code> mixins as standard. The <code>options</code> mixin knows of <code>emitter</code> and does the <code>onEventname</code> sugar for you. <code>implement</code> as standard as method or mutator key! <code>.parent(&#8216;methodname&#8217;, args)</code> as standard. Emitter events support pseudos as standard, eg <code>this.on(&#8216;load:once&#8217;, fn)</code>. Multiple events to same callback can be added on a single line <code>this.collection.on(&#8216;change add remove&#8217;, this.render)</code>. </p>
<p>That&#8217;s the sort of thing we were thinking. But just read the docs page, play with the live examples and have fun. It does not try to be a library and shim / do things to Types etc. It does Class and that&#8217;s it. For everything else, there is lodash.</p>
<p>Oh yes, and bower support, thanks to that <a href="https://github.com/simonsmith/">Simon Smith guy</a> that is a regular on JavaScript Daily. <code>bower install primish</code> will add just the 3 .js files you may use. No extra baggage, you won&#8217;t download the web when you init your bower!</p>
<p>One more time. The link is <a href="http://dimitarchristoff.github.io/primish/" target="_blank">here</a>.</p>
<blockquote><p>
Chances are, Kamicane, Arian and Kentaromiura will knock something amazing up with prime. Until then, primish all the things.
</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/primish-its-like-mootools-prime-but-for-the-intarnets_1628.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tooling for the node.js generation, part I</title>
		<link>http://fragged.org/tooling-for-the-node-js-generation-part-i_1607.html</link>
		<comments>http://fragged.org/tooling-for-the-node-js-generation-part-i_1607.html#comments</comments>
		<pubDate>Thu, 27 Jun 2013 13:03:00 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[nodejs]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1607</guid>
		<description><![CDATA[If you are a front-end developer that has dabbled a little bit in node and like it, you probably need to build a list of tools (npm modules etc) you can use in your day-to-day development. Here&#8217;s a small list of things I find I often reuse in different projects. anything in a require() is an npm module, installable via...<span class="path-read-more"><a class="more-link" href="http://fragged.org/tooling-for-the-node-js-generation-part-i_1607.html" title="Tooling for the node.js generation, part I">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>If you are a front-end developer that has dabbled a little bit in node and like it, you probably need to build a list of tools (npm modules etc) you can use in your day-to-day development. </p>
<p>Here&#8217;s a small list of things I find I often reuse in different projects.</p>
<blockquote><p>anything in a <strong>require()</strong> is an <strong>npm</strong> module, installable via <strong>npm install name</strong></p></blockquote>
<h3>Working with files</h3>
<ul>
<li><strong>require(&#8216;fs&#8217;);</strong> &#8211; obvious but the default <a href="http://nodejs.org/api/fs.html" target="_blank">node fs</a> is useful</li>
<li><strong>require(&#8216;fs-extra&#8217;);</strong> &#8211; an <a href="https://npmjs.org/package/fs-extra" target="_blank">extended file system</a> util that lets you do a lot more, like make files and directories and make files in paths that don&#8217;t exist yet, work with JSON etc.</li>
<li><strong>require(&#8216;watch&#8217;);</strong> &#8211; an awesome file system <a href="https://npmjs.org/package/watch">watch</a> tool you can configure to fire events on file change, creation etc. with various patterns and callbacks.</li>
</ul>
<h3>Headless browsers and DOM</h3>
<p>Being in node does not mean you cannot work on a DOM or on a DOM-like abstraction to either open HTML documents, parse them etc.</p>
<ul>
<li><strong>require(&#8216;jsdom&#8217;);</strong> &#8211; <a href="https://npmjs.org/package/jsdom" target="_blank">jsdom</a> is great, if you can get it to work in a hurry. It is also slow and has a dependency list longer than the Nile (including contextify, which is hard to build on WIN32 due to node-gyp and python). But it lets you get a very reasonable DOM to work with, loaded with JavaScript etc.</li>
<li><strong>require(&#8216;cheerio&#8217;);</strong> &#8211; a light <a href="https://npmjs.org/package/cheerio" target="_blank">pseudo-DOM</a> implementation that can load a document and allow you to use a jQueryLite-like version to query and manipulate it. For those that have given up on jsdom.</li>
<li><strong>PhantomJS</strong> &#8211; An actual headless implementation of webkit. <a href="http://phantomjs.org/" target="_blank">PhantomJS</a> is very useful for testing and CI. Powers frameworks like <a href="http://casperjs.org/" target="_blank">CapserJS</a></li>
</ul>
<h3>Working with Class</h3>
<p>Goes without saying but. It&#8217;s much nicer to use a more classical OOP interface in your nodejs modules.</p>
<ul>
<li><strong>require(&#8216;mootools&#8217;);</strong> &#8211; <a href="https://npmjs.org/package/mootools" target="_blank">mootools-server</a>, comes with Class (global) as well as the mixins Events, Options and some prototype enhancements to String etc. As you&#8217;d expect. No return value, just <code>require(&#8216;mootools&#8217;)</code> then use as per client.</li>
<li><strong>require(&#8216;prime&#8217;);</strong> &#8211; Kamicane and MooTools&#8217; <a href="https://github.com/mootools/prime">next gen micro lib</a> that does OOP style classes but is more lightweight. Don&#8217;t forget to also install Arian&#8217;s <strong>prime-utils</strong> for some sugar like supers, setOptions etc. </li>
<li><strong>require(&#8216;primish&#8217;);</strong> &#8211; My own version of prime, which does <a href="http://fragged.org/primish-its-like-mootools-prime-but-for-the-intarnets_1628.html">a lot</a> on top of prime to make it nicer and easier to use in the browser, as well as sugar around emitter, supers and options</li>
</ul>
<h3>Working with CLI</h3>
<p>Working on build tools often requires you to do several things: process arguments and format stuff nicely.</p>
<ul>
<li><strong>require(&#8216;clintish&#8217;);</strong> &#8211; <a href="https://npmjs.org/package/clintish">Clintish</a> is a fork of <code>clint</code> &#8211; also by Kamicane, it&#8217;s a micro processor for arguments with events and parsers, helper syntax etc. Very nifty.</li>
<li><strong>require(&#8216;colors&#8217;);</strong> &#8211; a very <a href="https://npmjs.org/package/colors">clever implementation</a> that prototypes the String native with some getters for default colour names. Allows you to do stuff like <code>console.log(&#8220;hello&#8221;.red + &#8221; there&#8221;.blue);</code>, no return value &#8211; just require once.</li>
</ul>
<p>In the <a href="http://fragged.org/tooling-for-the-node-js-generation-part-ii_1625.html">next part</a>, I will cover a lot of tools like growl notifiers, build tools / minifiers, linters, (trans)compilers, HTTP / socket servers, streaming and so forth.</p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/tooling-for-the-node-js-generation-part-i_1607.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>localStorage and sessionStorage events to send messages acrosss browser instances</title>
		<link>http://fragged.org/localstorage-and-sessionstorage-events-to-send-messages-acrosss-browser-instances_1574.html</link>
		<comments>http://fragged.org/localstorage-and-sessionstorage-events-to-send-messages-acrosss-browser-instances_1574.html#comments</comments>
		<pubDate>Fri, 21 Jun 2013 10:09:05 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[localStorage]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1574</guid>
		<description><![CDATA[This is a somewhat underused and lesser known feature of HTML5 localStorage API. The spec says: The storage event is fired when a storage area changes, as described in the previous two sections (for session storage, for local storage). When this happens, the user agent must queue a task to fire an event with the name storage, which does not...<span class="path-read-more"><a class="more-link" href="http://fragged.org/localstorage-and-sessionstorage-events-to-send-messages-acrosss-browser-instances_1574.html" title="localStorage and sessionStorage events to send messages acrosss browser instances">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>This is a somewhat underused and lesser known feature of HTML5 <code>localStorage</code> API. The <a href="http://www.w3.org/TR/webstorage/#the-storage-event" target="_blank">spec</a> says:</p>
<blockquote><p>
The storage event is fired when a storage area changes, as described in the previous two sections (for session storage, for local storage).</p>
<p>When this happens, the user agent must queue a task to fire an event with the name storage, which does not bubble and is not cancelable, and which uses the StorageEvent interface, at each Window object whose Document object has a Storage object that is affected.
</p></blockquote>
<p>This allows for a neat inter-browser window communication trick that can let multiple window instances of the same domain (same origin applies) to talk to each other.</p>
<p>Imagine you have the following situation: same site is open twice, the user then logs off in one of the two instances. Ideally, instance #2 should also find out about the fact they logged off and adjust accordingly.</p>
<pre>
// some imaginary event handler on an element
$('.log-off').on('click', function(){
    // pretend to do something on an app controller
    App.controller.logOff();

    // store something in localStorage
    localStorage.setItem('state', 'logged out');
});

// listen for this event
window.addEventListener('storage', function(storageEvent){
    // the event seems not to fire on own state changes, only other windows
    console.log(storageEvent);
    App.controller.setLoginState(storageEvent.newValue);
}, false);
</pre>
<p>The event object itself looks like this:</p>
<pre>
type storage
target Window /_display/
currentTarget Window /_display/
eventPhase 2
bubbles false
cancelable false
timeStamp 1371809245502028
defaultPrevented false
stopPropagation stopPropagation()
preventDefault preventDefault()
initEvent initEvent()
stopImmediatePropagation stopImmediatePropagation()
originalTarget Window /_display/
explicitOriginalTarget Window /_display/
preventBubble preventBubble()
preventCapture preventCapture()
getPreventDefault getPreventDefault()
isTrusted true
key state
oldValue logged in
newValue logged out
url http://localhost/_display/
storageArea 1 item in Storage state="logged out"
</pre>
<p>Type can be session or local. You can reconcile paths and more.</p>
<p>To play with it, open this <a href="http://jsfiddle.net/dimitar/jTfdq/">http://jsfiddle.net/dimitar/jTfdq/</a> twice and open your console, then keep on running the fiddles in alternative windows.</p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/localstorage-and-sessionstorage-events-to-send-messages-acrosss-browser-instances_1574.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Epitome now available as npm and under CommonJS</title>
		<link>http://fragged.org/epitome-now-available-as-npm-and-under-commonjs_1567.html</link>
		<comments>http://fragged.org/epitome-now-available-as-npm-and-under-commonjs_1567.html#respond</comments>
		<pubDate>Thu, 20 Jun 2013 10:12:11 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[Epitome]]></category>
		<category><![CDATA[npm]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1567</guid>
		<description><![CDATA[Just a quick update, Epitome now supports nodejs. Here&#8217;s an example creating a server via express and socket.io with a collection and a model that can be shared on the client as well: #!/usr/bin/env node 'use strict'; var express = require('express'), app = express(), http = require('http'), server = http.createServer(app), io = require('socket.io').listen(server); // load mootools globals and extend protos...<span class="path-read-more"><a class="more-link" href="http://fragged.org/epitome-now-available-as-npm-and-under-commonjs_1567.html" title="Epitome now available as npm and under CommonJS">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>Just a quick update, <a href="http://epitome-mvc.github.io/Epitome/">Epitome</a> now supports nodejs.</p>
<p>Here&#8217;s an example creating a server via <code>express</code> and <code>socket.io</code> with a collection and a model that can be shared on the client as well:</p>
<pre>
#!/usr/bin/env node
'use strict';

var express = require('express'),
    app = express(),
    http = require('http'),
    server = http.createServer(app),
    io = require('socket.io').listen(server);

// load mootools globals and extend protos
require('mootools');

io.set('log level', 1); // disable debug from socket.io

// example server root at dist.
app.use(express.static('./dist'));

server.listen(3333);

// use some epitome models and collections
var epitome = require('epitome'),
    Model = epitome.Model,
    Collection = epitome.Collection;

var User = new Class({
    Extends: Model,
    options: {
        defaults: {
            title: 'Mr.'
        }
    }
});

var Users = new Class({
    Extends: Collection,
    model: User
});

var users = new Users([{
    name: 'Bob',
    surname: 'Roberts'
}]);

// example adds to collection when a data:add message arrives from client
io.on('connection', function(socket){
    socket.on('data:add', function(model){
        users.addModel(model);
        console.log('added new model', model);
    });

    socket.emit('data', users.toJSON());
});
</pre>
<p>To get this to work, you need to install a few npms first</p>
<pre>
$ npm install mootools express socket.io epitome
</pre>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/epitome-now-available-as-npm-and-under-commonjs_1567.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Doctor, MD &#8211; updated for recess 1.1.8 and BootStrap 2.3.2</title>
		<link>http://fragged.org/doctor-md-updated-for-recess-1-1-8-and-bootstrap-2-3-2_1565.html</link>
		<comments>http://fragged.org/doctor-md-updated-for-recess-1-1-8-and-bootstrap-2-3-2_1565.html#respond</comments>
		<pubDate>Thu, 20 Jun 2013 09:24:10 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[doctor]]></category>
		<category><![CDATA[markdown]]></category>
		<category><![CDATA[npm]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1565</guid>
		<description><![CDATA[Just a quick note, updated my nodejs Markdown to HTML site generator Doctor to support the latest recess and BootStrap 2.3.2, latest stable published npm is v0.1.14 The grunt-doctor-md grunt task has also been updated to use doctor-md@0.1.14. $ npm install -g doctor-md $ doctor]]></description>
				<content:encoded><![CDATA[<p>Just a quick note, updated my nodejs Markdown to HTML site generator <a href="http://dimitarchristoff.github.io/doctor/">Doctor</a> to support the latest recess and BootStrap 2.3.2, latest stable published npm is v0.1.14</p>
<p>The <a href="https://github.com/DimitarChristoff/grunt-doctor-md">grunt-doctor-md</a> grunt task has also been updated to use doctor-md@0.1.14.</p>
<pre>
$ npm install -g doctor-md
$ doctor
</pre>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/doctor-md-updated-for-recess-1-1-8-and-bootstrap-2-3-2_1565.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hiding enumerables after MooTools changes prototypes</title>
		<link>http://fragged.org/hiding-enumerables-after-mootools-changes-prototypes_1552.html</link>
		<comments>http://fragged.org/hiding-enumerables-after-mootools-changes-prototypes_1552.html#respond</comments>
		<pubDate>Mon, 03 Jun 2013 12:40:07 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1552</guid>
		<description><![CDATA[One of the most common complaints of people when using 3-rd party code that breaks on MooTools pages is when somebody incorrectly tries to iterate through an Array with the for (var in) operator and the methods and properties added by the framework also show up. When you cannot change the code to add hasOwnProperty, it leaves you with very...<span class="path-read-more"><a class="more-link" href="http://fragged.org/hiding-enumerables-after-mootools-changes-prototypes_1552.html" title="Hiding enumerables after MooTools changes prototypes">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>One of the most common complaints of people when using 3-rd party code that breaks on MooTools pages is when somebody incorrectly tries to iterate through an Array with the <code>for (var in)</code> operator and the methods and properties added by the framework also show up. When you cannot change the code to add <code>hasOwnProperty</code>, it leaves you with very little options. Or&#8230; you could fix things.</p>
<pre>
var foo = ['one','two'],
    key;

for (key in foo){
    // lists all mootools methods and properties as well as 0, 1
    console.log(key, foo[key]); // needs hasOwnProperty etc, ppl complain.
}

// protect enumerables under ES5 in Array
(function(){
    // set mootools expandos to non-enumerables under ES5
    var key,
        a = [];
    
    for (key in a) a.hasOwnProperty(key) || Object.defineProperty(Array.prototype, key, {
        enumerable:false
    });
}());

console.info('trying again...');

for (key in foo){
    console.log(key, foo[key]);    
}
</pre>
<p>See this <a href="http://jsfiddle.net/dimitar/sK7Rd/">in action</a> on jsfiddle.</p>
<p>An alternative approach may be available by patching MooTools core. You need to mod the implement function in Core.js here: <a href="https://github.com/mootools/mootools-core/blob/master/Source/Core/Core.js#L192-L209">https://github.com/mootools/mootools-core/blob/master/Source/Core/Core.js#L192-L209</a> and adding something like:</p>
<pre>
if (previous == null || !previous.$protected) this.prototype[name] = method;
Object.defineProperty && Object.defineProperty(this, name, { enumerable: false });
</pre>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/hiding-enumerables-after-mootools-changes-prototypes_1552.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extend Slick pseudo selector to find data-attributes</title>
		<link>http://fragged.org/extend-slick-pseudo-selector-to-find-data-attributes_1537.html</link>
		<comments>http://fragged.org/extend-slick-pseudo-selector-to-find-data-attributes_1537.html#respond</comments>
		<pubDate>Tue, 18 Sep 2012 18:12:19 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[motools]]></category>
		<category><![CDATA[slick]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1537</guid>
		<description><![CDATA[This is a relatively simple idea. Select elements with data-attributes that match a pattern, for example, div[data-media-*]. The problem is, CSS selectors don;t allow you to wildcard attributes themselves so we need to be creative. We will extend the Slick selector engine with a data pseudo selector, which will look at the outerHTML of the element and find a match...<span class="path-read-more"><a class="more-link" href="http://fragged.org/extend-slick-pseudo-selector-to-find-data-attributes_1537.html" title="Extend Slick pseudo selector to find data-attributes">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>This is a relatively simple idea. Select elements with data-attributes that match a pattern, for example, div[data-media-*]. The problem is, CSS selectors don;t allow you to wildcard attributes themselves so we need to be creative.</p>
<p>We will extend the Slick selector engine with a data pseudo selector, which will look at the outerHTML of the element and find a match for the attrbute, starting with data-value*:</p>
<pre>
Slick.definePseudo('data', function(value){
    // wildcard data-startswith search
    var outer = this.outerHTML || new XMLSerializer().serializeToString(this);
    return outer.test('data-' + value);
});

console.log($$("div:data(media-)")); // return all divs with data-media-* attribute
</pre>
<p>This is it at a first reading. Now, given how performance is important, especially if used on a large DOM without a qualified selector, let&#8217;s see if we can optimise it by using a closure where the setup takes place. We will cache the strings we reuse so no new strings need to be made for each element passed to Slick, as well as a single instance of the XMLSerializer, used by the fallback when outerHTML is not available. We also go to Array.join instead of string concatenate for small gains in IE6/7/8</p>
<pre>
(function(){
    // cache reusable strings 
    var data = 'data',
        hyphen = '-',
        // set the fallback via XMLSerializer, if no outerHTML (eg. FF 2 - 10)
        XS = this.XMLSerializer && new XMLSerializer();

    Slick.definePseudo(data, function(value){
        return (this.outerHTML || XS.serializeToString(this)).test([data, value].join(hyphen));
    });
}());
</pre>
<p>Happy coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/extend-slick-pseudo-selector-to-find-data-attributes_1537.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spying unobtrusively on Class instance events in MooTools</title>
		<link>http://fragged.org/spying-unobtrusively-on-class-instance-events-in-mootools_1531.html</link>
		<comments>http://fragged.org/spying-unobtrusively-on-class-instance-events-in-mootools_1531.html#respond</comments>
		<pubDate>Tue, 21 Aug 2012 13:44:05 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[fireEvent]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1531</guid>
		<description><![CDATA[Ever needed to debug how your Class instances fire Events? It can be frustrating and messy, especially if you do not have access to the original Class prototype source. But, you can hack your way around this and create a transparent spy on all fireEvent methods on any Class instance. Here is how: (function() { var spyId = 'spyEvent'; Class.extend({...<span class="path-read-more"><a class="more-link" href="http://fragged.org/spying-unobtrusively-on-class-instance-events-in-mootools_1531.html" title="Spying unobtrusively on Class instance events in MooTools">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>Ever needed to debug how your Class instances fire Events? It can be frustrating and messy, especially if you do not have access to the original Class prototype source. But, you can hack your way around this and create a transparent spy on all fireEvent methods on any Class instance. Here is how:</p>
<pre>
(function() {
    var spyId = 'spyEvent';
    
    Class.extend({
        addEventSpy: function (instance) {
            /* 
            accepts one argument - Class instance. 
            works by adding a local fireEvent method on the instance  
            instead of going TO proto chain to Class.Event::fireEvent 
            */

            // check if there's a local fireEvent method or already installed spy
            if (instance.hasOwnProperty('fireEvent') && instance.fireEvent.name == spyId) {
                console.log('ERROR: Already have a local fireEvent method');
                return;
            }          
            // Events need to be mixed in.
            if (!instance.fireEvent) {
                console.log('ERROR: Can only spy on class instances with an Events mixin');
                return;                
            }
            // store original
            var orig = instance.fireEvent;
            instance.fireEvent = function spyEvent() {
                // log to console or do your own observer logic
                console.log('EVENT SPY', this, 'fired', arguments);
                // allow chaining.
                return orig.apply(this, arguments);
            };
                        
        },
        removeEventSpy: function(instance) {
            // clean up that restores orignal if possible.
 
            // not needed? already using proto one.
            if (!instance.hasOwnProperty('fireEvent')) return;

            // it has a local fireEvent but it needs to be our spy, else it's unsafe.
            if (!instance.fireEvent.name || instance.fireEvent.name != spyId) {
                console.log('ERROR: Somebody else has done this fireEvent');
                return;
            }          
            // remove it.
            delete instance.fireEvent;            
        }
    });
    
}());
</pre>
<p>This is the setup code. Now, you can use it on a Class and test it:</p>
<pre>
// define a class that uses events
var a = new Class({

    Implements: Events,
    
    initialize: function() {
        this.events = 0;    
    },
    
    doEvent: function() {
        this.events++;
        console.log('do event', this.events);
        return this.fireEvent('awesome');    
    }
});

// make the instance
var b = new a();

// subscribe to all events
Class.addEventSpy(b)

// try firing 2 quick events    
b.doEvent().doEvent();    

// clean up spy.
Class.removeEventSpy(b);

// test spy is gone.
b.doEvent();
</pre>
<p>I hope it is of some use to you. See it in action in this <a href='http://jsfiddle.net/dimitar/8Rmk4/'>fiddle</a></p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/spying-unobtrusively-on-class-instance-events-in-mootools_1531.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Epitome does todo</title>
		<link>http://fragged.org/epitome-does-todo_1529.html</link>
		<comments>http://fragged.org/epitome-does-todo_1529.html#respond</comments>
		<pubDate>Fri, 13 Jul 2012 10:16:23 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[Epitome]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[todo]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1529</guid>
		<description><![CDATA[Just a quick update, my MooTools MVP library Epitome now has its own Epitome-todo repository as a submodule, an implementation of the popular TodoMVC demo. You can see it live here. If you checkout Epitome from git, you can use: git submodule init git submodule update &#8230; and point your browser to your local example/todo/epitome/ folder.]]></description>
				<content:encoded><![CDATA[<p>Just a quick update, my MooTools MVP library <a href="https://github.com/DimitarChristoff/Epitome" target="_blank">Epitome</a> now has its own <a href="https://github.com/DimitarChristoff/Epitome-todo" target="_blank">Epitome-todo</a> repository as a submodule, an implementation of the popular TodoMVC demo.</p>
<p>You can see it live <a href="http://fragged.org/Epitome/example/todo/epitome/#!/">here</a>. </p>
<p>If you checkout Epitome from git, you can use:</p>
<pre>
git submodule init
git submodule update
</pre>
<p>&#8230; and point your browser to your local <code>example/todo/epitome/</code> folder.</p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/epitome-does-todo_1529.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Epitome goes CI via buster.js and Travis CI</title>
		<link>http://fragged.org/epitome-goes-ci-via-buster-js-and-travis-ci_1526.html</link>
		<comments>http://fragged.org/epitome-goes-ci-via-buster-js-and-travis-ci_1526.html#respond</comments>
		<pubDate>Fri, 06 Jul 2012 14:50:25 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[buster.js]]></category>
		<category><![CDATA[travis-ci]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1526</guid>
		<description><![CDATA[Just a quick note &#8211; the MooTools MV* framework I wrote for QMetric called &#8216;Epitome&#8216; is now covered by Travis CI automated testing. Read more about how to implement this in your javascript projects in this blog post on the QMetric Tech Blog.]]></description>
				<content:encoded><![CDATA[<p>Just a quick note &#8211; the MooTools MV* framework I wrote for QMetric called &#8216;<a href="https://github.com/DimitarChristoff/Epitome/" target="_blank">Epitome</a>&#8216; is now covered by Travis CI automated testing. </p>
<p>Read more about how to implement this in your javascript projects in <a href="http://tech.qmetric.co.uk/automating-javascript-ci-with-buster-js-and-travisci_205.html">this blog post</a> on the QMetric Tech Blog.</p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/epitome-goes-ci-via-buster-js-and-travis-ci_1526.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>So you want delayed events in your mootools class?</title>
		<link>http://fragged.org/so-you-want-delayed-events-in-your-mootools-class_1520.html</link>
		<comments>http://fragged.org/so-you-want-delayed-events-in-your-mootools-class_1520.html#respond</comments>
		<pubDate>Wed, 13 Jun 2012 11:28:20 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[fireEvent]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1520</guid>
		<description><![CDATA[I recently found that in the context of Class, .fireEvent() accepts a 3-rd argument, delay. Firing deferred events can be useful but you need to understand the full difference between the patterns available at your disposal. Pattern one. It relies on delay creating a function and passing arguments to that function at the time of invocation. Does not actually fire...<span class="path-read-more"><a class="more-link" href="http://fragged.org/so-you-want-delayed-events-in-your-mootools-class_1520.html" title="So you want delayed events in your mootools class?">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>I recently found that in the context of Class, <strong>.fireEvent()</strong> accepts a 3-rd argument, <strong>delay</strong>. Firing deferred events can be useful but you need to understand the full difference between the patterns available at your disposal.</p>
<p>Pattern one. It relies on delay creating a function and passing arguments to that function at the time of invocation. Does not actually <strong>fire</strong> until time is due, but the arguments will be saved during invocation (unless they are objects, therefore by reference).</p>
<pre>
var a = new Class({
   
    Implements: [Events],
    
    initialize: function() {
        this.foo = 1;
        this.fireEvent.delay(1000, this, ['event', [this.foo, 'moar']]);
        // won't actually fire until time is due.
        this.addEvent('event', function() {
            console.log(arguments, this);
        });
        
        this.foo = 2;
    }
    
});


new a();
</pre>
<p>In pattern #2, we use the delayed event provided by MooTools. The key thing here is that the event actually <code>fires</code> at the time of invocation but does not arrive until the due time. The problem is, &#8216;just-in-time&#8217; adding of the event after won&#8217;t work as there is no event handler prior to calling .fireEvent. In this example, nothing will log &#8211; but you can add your event before firing. Arguments will be the same as at the of invocation. </p>
<pre>
var b = new Class({
   
    Implements: [Events],
    
    initialize: function() {
        this.foo = 1;
        this.fireEvent('event', [this.foo, 'moar'], 1000);
        // has already fired, so adding the event handler now is pointless
        this.addEvent('event', function() {
            console.log(arguments, this);
        });
        
        this.foo = 2;
    }
    
});


new b();
</pre>
<p>In pattern 3, we wrap things into an anonymous function that is deferred for later via setTimeout (well, Function.delay() which is the same thing). The bonus to this pattern is that it will dispatch the value at the time of firing, not at the time of deferral. </p>
<pre>
var c = new Class({
   
    Implements: [Events],
    
    initialize: function() {
        this.foo = 1;
        (function() {
            this.fireEvent('event', [this.foo, 'moar']);
        }).delay(1000, this);
        
        // only pattern that uses fresh enough data
        this.addEvent('event', function() {
            console.log(arguments, this);
        });
        
        this.foo = 2;
    }
    
});

new c();
</pre>
<p>Hope this gives you something to take away in your app development. Look at the jsfiddle and your console here: <a href="http://jsfiddle.net/dimitar/mTkvE/">http://jsfiddle.net/dimitar/mTkvE/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/so-you-want-delayed-events-in-your-mootools-class_1520.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Epitome: an example MooTools model / MVC tutorial</title>
		<link>http://fragged.org/epitome-an-example-mootools-model-mvc-tutorial_1517.html</link>
		<comments>http://fragged.org/epitome-an-example-mootools-model-mvc-tutorial_1517.html#respond</comments>
		<pubDate>Mon, 11 Jun 2012 09:30:44 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1517</guid>
		<description><![CDATA[I have been a little busy at work but we recently built a small Model class to support our question set and I turned it into a tutorial on how to build your own MV* framework on top of MooTools. It is called &#8216;Epitome&#8216; and is available on GitHub here: https://github.com/DimitarChristoff/Epitome. Keep in mind that it may turn out to...<span class="path-read-more"><a class="more-link" href="http://fragged.org/epitome-an-example-mootools-model-mvc-tutorial_1517.html" title="Epitome: an example MooTools model / MVC tutorial">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>I have been a little busy at work but we recently built a small Model class to support our question set and I turned it into a tutorial on how to build your own MV* framework on top of MooTools. It is called &#8216;<a href="http://dimitarchristoff.github.com/Epitome/" title="Epitome Groc Documentation" target="_blank">Epitome</a>&#8216; and is available on GitHub here: <a href="https://github.com/DimitarChristoff/Epitome" target="_blank">https://github.com/DimitarChristoff/Epitome</a>. Keep in mind that it may turn out to be MVP/MVVM and not semantic MVC&#8230;</p>
<p>You can read the 2 blog posts I wrote on <a href="http://tech.qmetric.co.uk/creating-your-own-mvc-like-data-model-class-in-mootools_59.html" target="_blank">creating the Model</a> and <a href="http://tech.qmetric.co.uk/building-a-mootools-micro-mvc-part-2-adding-sync-to-your-model_132.html" target="_blank">adding the Sync</a>. More coming when I get time&#8230; </p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/epitome-an-example-mootools-model-mvc-tutorial_1517.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>new mootools github repos for handy little tools</title>
		<link>http://fragged.org/new-mootools-github-repos-for-handy-little-tools_1514.html</link>
		<comments>http://fragged.org/new-mootools-github-repos-for-handy-little-tools_1514.html#respond</comments>
		<pubDate>Mon, 28 May 2012 21:50:14 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1514</guid>
		<description><![CDATA[Right then. If you don&#8217;t follow me on github, this will be news to you. Storage. https://github.com/DimitarChristoff/Storage &#8211; it&#8217;s a class that allows you to API localStorage or sessionStorage, when available &#8211; with a fallback to using window.name in older browsers like IE6/7. It can be used as standalone or as a mixin (implemented) class within any other class. It...<span class="path-read-more"><a class="more-link" href="http://fragged.org/new-mootools-github-repos-for-handy-little-tools_1514.html" title="new mootools github repos for handy little tools">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>Right then. If you don&#8217;t follow me on github, this will be news to you.</p>
<p>Storage. <a href="https://github.com/DimitarChristoff/Storage">https://github.com/DimitarChristoff/Storage</a> &#8211; it&#8217;s a class that allows you to API localStorage or sessionStorage, when available &#8211; with a fallback to using window.name in older browsers like IE6/7. It can be used as standalone or as a mixin (implemented) class within any other class. It also namespaces each instance within the storage so it can occlude nicely.</p>
<p>And&#8230; </p>
<p>Do you remember <a href="https://github.com/xrado/Router">Router</a>? I had liked it some months back. Turned out, it benefited from a rewrite / refactor and is now <a href="http://dimitarchristoff.github.com/Router/">a lot more mootoolish</a>. Though Rado accepted my pull request so I can probably delete my fork, leaving it there for now in case I think of anything else.</p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/new-mootools-github-repos-for-handy-little-tools_1514.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Preloading images using javascript, the right way and without frameworks</title>
		<link>http://fragged.org/preloading-images-using-javascript-the-right-way-and-without-frameworks_744.html</link>
		<comments>http://fragged.org/preloading-images-using-javascript-the-right-way-and-without-frameworks_744.html#comments</comments>
		<pubDate>Fri, 18 May 2012 10:15:31 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[fragged]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[IE]]></category>
		<category><![CDATA[onload]]></category>
		<category><![CDATA[pre-loading]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=744</guid>
		<description><![CDATA[There are two scenarios here. Case 1: you just want to load all your images prior to displaying the rest of your page. Whether that&#8217;s because you like it this way or you need to get the browser to &#8216;know&#8217; your images widths and heights first, preload a gallery of images, it does not matter. The arguments for &#8216;speeding up&#8217;...<span class="path-read-more"><a class="more-link" href="http://fragged.org/preloading-images-using-javascript-the-right-way-and-without-frameworks_744.html" title="Preloading images using javascript, the right way and without frameworks">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>There are two scenarios here. <strong>Case 1:</strong> you just want to load all your images prior to displaying the rest of your page. Whether that&#8217;s because you like it this way or you need to get the browser to &#8216;know&#8217; your images widths and heights first, preload a gallery of images, it does not matter. The arguments for &#8216;speeding up&#8217; page loads are a bit moot now, with modern connections and modern browsers there are no great benefits to this. Either way, you need to arrange your code in a way that allows you to <em>trigger some event or function </em>when the loading is complete in order to continue displaying your site.</p>
<p>And then, there&#8217;s <strong>case 2:</strong> pre-emptive image loading / cache priming, which is the more interesting use. This is a relatively new trend that involves examining the user&#8217;s browsing pattern and anticipating what they do next. For instance, if they are browsing product listings as a result of a search with 100 results (20 per page), it is almost safe to assume they <em>may </em>want to go to page 2 or 3. It is also safe to assume the average user would take a while to finish appraising their results, scroll down and locate the &#8216;next&#8217; link. This idle slot is where you can put their connection to better use by priming the browser cache with the product thumbnails of the next results page. In this instance, you don&#8217;t really care for any onload / oncomplete events, the benefits of the cache will be reaped on the next page instead.</p>
<blockquote><p><strong>Alternatives for priming cache are available for HTML5 browsers!</strong><br />
You can now use the HTML5 <code>link prefetching</code> API: <a href="https://developer.mozilla.org/en/docs/Link_prefetching_FAQ">MDN Link Prefetching</a></p>
<pre>
&lt;link rel="prefetch" href="/images/big.jpeg">
</pre>
</blockquote>
<p>Now, we&#8217;ve established why you may want to preload images, let&#8217;s focus on the how instead. </p>
<p>There are some considerations we need to be aware of here: </p>
<ol>
<li>It needs to be threaded in parallel (to use the browser&#8217;s maximum threads, normally 6 per domain)</li>
<li>It needs to also be sequential (pipelined) for when you want to use a single thread</li>
<li>It needs to handle individual image events &#8211; <code>onload</code>, <code>onabort</code>, <code>onerror</code></li>
<li>Work cross-browser and without any dependencies</li>
<li>We need to clean up resources and memory, not leak memory and prevent <a href="http://webbugtrack.blogspot.co.uk/2007/11/bug-208-onload-event-fires-for-every.html" target="_blank">IE GIF onload</a> from firing multiple times</li>
</ol>
<p>First of all, it&#8217;s important to understand that you need to assign the <code>onload</code> event BEFORE you set the <code>src</code> property of the image object:</p>
<pre>
// a common mistake seen, adding event after src assign:
var image = new Image();
image.src = 'image.jpg';
image.onload = function(){ 
    // won't work if image already cached, it won't trigger
    // ...
};

// correct way:
var image = new Image();
image.onload = function(){ // always fires the event.
    // ...
};
// handle failure
image.onerror = function(){

};
image.src = 'image.jpg';
</pre>
<p>And second, in Internet Explorer 5/6/7, the <code>onload</code> event fires <a href="http://webbugtrack.blogspot.co.uk/2007/11/bug-208-onload-event-fires-for-every.html" target="_blank">ALL THE TIME</a> for animated GIFs. That&#8217;s right, on each animation loop it fires an <code>onload</code> for you. Which is why you need to make sure you release your image objects for GC by not saving a reference &#8211; or should you need to store them as objects into a new array &#8211; remove all <code>onload</code> and other events attached to them.</p>
<p>Anyway, without further ado, the code. </p>
<blockquote><p>
See the this in action at <a href="http://jsfiddle.net/dimitar/mFQm6/">this jsfiddle</a>, now also available as a repository on GitHub: <a href="https://github.com/DimitarChristoff/pre-loader">pre-loader</a>. Please note the demo needs a HTML5 browser but the preLoader class does not and should work IE6 and up.
</p></blockquote>
<pre>
// define a small preLoader class.
(function(){
    'use strict';

    var preLoader = function(images, options){
        this.options = {
            pipeline: false,
            auto: true,
            /* onProgress: function(){}, */
            /* onError: function(){}, */
            onComplete: function(){}
        };

        options && typeof options == 'object' && this.setOptions(options);

        this.addQueue(images);
        this.queue.length && this.options.auto && this.processQueue();
    };

    preLoader.prototype.setOptions = function(options){
        // shallow copy
        var o = this.options,
            key;

        for (key in options) options.hasOwnProperty(key) && (o[key] = options[key]);

        return this;
    };

    preLoader.prototype.addQueue = function(images){
        // stores a local array, dereferenced from original
        this.queue = images.slice();

        return this;
    };

    preLoader.prototype.reset = function(){
        // reset the arrays
        this.completed = [];
        this.errors = [];

        return this;
    };

    preLoader.prototype.load = function(src, index){
        var image = new Image(),
            self = this,
            o = this.options;

        // set some event handlers
        image.onerror = image.onabort = function(){
            this.onerror = this.onabort = this.onload = null;

            self.errors.push(src);
            o.onError && o.onError.call(self, src);
            checkProgress.call(self, src);
            o.pipeline && self.loadNext(index);
        };

        image.onload = function(){
            this.onerror = this.onabort = this.onload = null;

            // store progress. this === image
            self.completed.push(src); // this.src may differ
            checkProgress.call(self, src, this);
            o.pipeline && self.loadNext(index);
        };

        // actually load
        image.src = src;

        return this;
    };

    preLoader.prototype.loadNext = function(index){
        // when pipeline loading is enabled, calls next item
        index++;
        this.queue[index] && this.load(this.queue[index], index);

        return this;
    };

    preLoader.prototype.processQueue = function(){
        // runs through all queued items.
        var i = 0,
            queue = this.queue,
            len = queue.length;

        // process all queue items
        this.reset();

        if (!this.options.pipeline) for (; i < len; ++i) this.load(queue[i], i);
        else this.load(queue[0], 0);

        return this;
    };

    function checkProgress(src, image){
        // intermediate checker for queue remaining. not exported.
        // called on preLoader instance as scope
        var args = [],
            o = this.options;

        // call onProgress
        o.onProgress &#038;&#038; src &#038;&#038; o.onProgress.call(this, src, image, this.completed.length);

        if (this.completed.length + this.errors.length === this.queue.length){
            args.push(this.completed);
            this.errors.length &#038;&#038; args.push(this.errors);
            o.onComplete.apply(this, args);
        }

        return this;
    }


    if (typeof define === 'function' &#038;&#038; define.amd){
        // we have an AMD loader.
        define(function(){
            return preLoader;
        });
    }
    else {
        this.preLoader = preLoader;
    }
}).call(this);
</pre>
<p>This can be in a separate file or as part of your utilities. Use is up to you, the API supports the following:</p>
<blockquote><p>
new preLoader(['image1.jpg', 'image2.jpg'], /*optional*/options);
</p></blockquote>
<p>In a more comprehensive example, it can be used to load multiple images, display a progress indicator (HTML5 browsers) and fire a function when cache is primed.</p>
<pre>
// assign 50 non-cache-able images via an image generator
var imagesArray = new Array(50).join(',').split(',');
imagesArray = imagesArray.map(function(el, i){
    return 'http://dummyimage.com/600x400/000/' + i + '?' + +new Date();
});

// create a HTML5 progress element
var progress = document.createElement('progress');
progress.setAttribute('max', imagesArray.length);
progress.setAttribute('value', 0);
document.body.appendChild(progress);

var legend = document.createElement('span');
document.body.appendChild(legend);
var imageContainer = document.getElementById('images');

// instantiate the pre-loader with an onProgress and onComplete handler
new preLoader(imagesArray, {
    onProgress: function(img, imageEl, index){
        // fires every time an image is done or errors. 
        // imageEl will be falsy if error
        console.log('just ' +  (!imageEl ? 'failed: ' : 'loaded: ') + img);
        
        var percent = Math.floor((100 / this.queue.length) * this.completed.length);
        
        // update the progress element
        legend.innerHTML = '&lt;span>' + index + ' / ' + this.queue.length + ' ('+percent+'%)&lt;/span>';
        progress.value = index;
        
        imageContainer.appendChild(imageEl);
        // can access any propery of this
        console.log(this.completed.length + this.errors.length + ' / ' + this.queue.length + ' done');
    }, 
    onComplete: function(loaded, errors){
        // fires when whole list is done. cache is primed.
        console.log('done', loaded);
        imageContainer.style.display = 'block';
        
        if (errors){
            console.log('the following failed', errors);
        }
    }
});
</pre>
<p>The preLoader supports two different modes of operation: parallel and pipeline (pass it in the options). In parallel, it just dumps the queue to the browser and lets it manage threads/concurrency on its own. When <strong>pipeline: true</strong> is passed, it will only use a single thread and won't start downloading the next image until the previous has finished or errored out. For more info, look at the example folder on the repository to see the difference.</p>
<div style="width: 1443px" class="wp-caption alignnone"><img src="https://raw.github.com/DimitarChristoff/pre-loader/master/example/images/parallel-waterfall.jpg" width="1433" height="248" class /><p class="wp-caption-text">parallel waterfall</p></div>
<div style="width: 1405px" class="wp-caption alignnone"><img src="https://raw.github.com/DimitarChristoff/pre-loader/master/example/images/pipeline-waterfall.jpg" width="1395" height="250" class /><p class="wp-caption-text">pipeline waterfall</p></div>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/preloading-images-using-javascript-the-right-way-and-without-frameworks_744.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>StrongPass: A password strength helper class</title>
		<link>http://fragged.org/strongpass-a-password-strength-helper-class_1495.html</link>
		<comments>http://fragged.org/strongpass-a-password-strength-helper-class_1495.html#respond</comments>
		<pubDate>Fri, 27 Apr 2012 13:01:59 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[fragged]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[password]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1495</guid>
		<description><![CDATA[Good news, everyone (I miss Futurama). Three years ago I wrote a mootools plugin for password strength checking, based upon a stack overflow jquery post. I just had cause to revisit this for work at QMetric and refactored it (read, rewrote from scratch) for MooTools 1.4+ The Class is on the forge, it&#8217;s fairly flexible and can either be styled...<span class="path-read-more"><a class="more-link" href="http://fragged.org/strongpass-a-password-strength-helper-class_1495.html" title="StrongPass: A password strength helper class">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>Good news, everyone (I miss Futurama). </p>
<p>Three years ago I wrote a mootools plugin for password strength checking, based upon a stack overflow jquery post. I just had cause to revisit this for work at QMetric and refactored it (read, rewrote from scratch) for MooTools 1.4+</p>
<p>The Class is on the forge, it&#8217;s fairly flexible and can either be styled to use the default strength indicator or to output whatever you like based upon pass/fail events and scores. </p>
<p>You can check it out here: <a href="http://mootools.net/forge/p/strongpass">http://mootools.net/forge/p/strongpass</a> or if you prefer, head to the GitHub repo directly here instead: <a href="https://github.com/DimitarChristoff/StrongPass">https://github.com/DimitarChristoff/StrongPass</a></p>
<p>Links to demos are in the README.md as well as a basic buster.js test suite. Use responsibly!</p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/strongpass-a-password-strength-helper-class_1495.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>mailcheck for mootools: suggestive email auto correction</title>
		<link>http://fragged.org/mailcheck-for-mootools-suggestive-email-auto-correction_1491.html</link>
		<comments>http://fragged.org/mailcheck-for-mootools-suggestive-email-auto-correction_1491.html#respond</comments>
		<pubDate>Fri, 23 Mar 2012 21:35:30 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[fragged]]></category>
		<category><![CDATA[email]]></category>
		<category><![CDATA[mailcheck]]></category>
		<category><![CDATA[mootools]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1491</guid>
		<description><![CDATA[Every now and then, a plugin comes about that has a good idea. Recently, this has been the mailcheck jquery plugin by Kicksend. According to their claims, it has reduced typos in emails during user signups by over 50%. The plugin works by comparing the domain typed vs a list of pre-configured popular TLDs for email, such as gmail.com, hotmail.com...<span class="path-read-more"><a class="more-link" href="http://fragged.org/mailcheck-for-mootools-suggestive-email-auto-correction_1491.html" title="mailcheck for mootools: suggestive email auto correction">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>Every now and then, a plugin comes about that has a good idea. Recently, this has been the <a target=_blank href="http://blog.kicksend.com/how-we-decreased-sign-up-confirmation-email-b">mailcheck</a> jquery plugin by Kicksend. According to their claims, it has reduced typos in emails during user signups by over 50%.</p>
<p><img src="https://github.com/Kicksend/mailcheck/raw/master/doc/example.png?raw=true" /></p>
<p>The plugin works by comparing the domain typed vs a list of pre-configured popular TLDs for email, such as gmail.com, hotmail.com and so forth &#8211; and providing recommendations based upon string similarity. As a result, typing &#8216;foo@gnail.com&#8217; ought to offer a suggestion &#8216;Did you mean foo@gmail.com?&#8217;</p>
<p>We decided to implement it <a href="http://www.policyexpert.co.uk/" title="home insurance compare" target="_blank">at work</a> and I sat down to convert it to mootools. Regretfully, none of the code of the original plugin remains, including the string distance algo &#8216;sift3&#8217;, which proved inaccurate and failing in IE7. </p>
<p>The result? A brand-spanking-new <a href="https://github.com/DimitarChristoff/mailcheck" title="mailcheck for mootools" target="_blank">mootools.mailcheck.js (on github)</a> for your pleasure (specific github project pages <a href="http://dimitarchristoff.github.com/mailcheck/">here</a> </p>
<p>The mootools version now features a few improvements over the original, namely:</p>
<ul>
<li>choice of method for determining string distance between Levenstein (the default choice) and sift3</li>
<li>more performant</li>
<li>look-up cache &#8211; any strings compared that return a match are cached</li>
<li>shared cache &#8211; any new instances created will benefit from old lookups, useful for use in single page applications</li>
<li>automated testing via buster.js &#8211; all included with <a href="https://github.com/DimitarChristoff/mailcheck/tree/master/test">a kick start guide.</a></li>
</ul>
<p>Visit the repo and give it a go, it&#8217;s a solid idea now. I have even included a jsfiddle demo and it comes with little mysql query that will grab the most popular email domains from your existing user database so you can set it up to suit your own target audience. </p>
<div class="download">
      <a href="https://github.com/DimitarChristoff/mailcheck/zipball/master"><br />
        <img border="0" width="90" src="https://github.com/images/modules/download/zip.png"></a>
    </div>
<p>View a video of CI auto testing via buster.js on this plugin:</p>
<p><iframe width="480" height="360" src="http://www.youtube.com/embed/gKVej9SAzH4" frameborder="0" allowfullscreen></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/mailcheck-for-mootools-suggestive-email-auto-correction_1491.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MooTools plugins round-up</title>
		<link>http://fragged.org/mootools-plugins-round-up_1482.html</link>
		<comments>http://fragged.org/mootools-plugins-round-up_1482.html#respond</comments>
		<pubDate>Mon, 13 Feb 2012 10:42:18 +0000</pubDate>
		<dc:creator><![CDATA[Dimitar Christoff]]></dc:creator>
				<category><![CDATA[fragged]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[plugins]]></category>

		<guid isPermaLink="false">http://fragged.org/?p=1482</guid>
		<description><![CDATA[Time for a round-up of interesting / quality plugins on the MooTools forge or github. Again. First off, my favourite find over the last month has to be the MooTools Router. What it does is handle application paths for hashes in the style of the Backbone.js router but it&#8217;s really a normal MooTools class. It can tackle dynamic parameters rather...<span class="path-read-more"><a class="more-link" href="http://fragged.org/mootools-plugins-round-up_1482.html" title="MooTools plugins round-up">  Read more &#8594; </a></span>]]></description>
				<content:encoded><![CDATA[<p>Time for a round-up of interesting / quality plugins on the MooTools forge or github. Again.</p>
<p>First off, my favourite find over the last month has to be the <a href="http://mootools.net/forge/p/router">MooTools Router</a>. What it does is handle application paths for hashes in the style of the Backbone.js router but it&#8217;s really a normal MooTools class. It can tackle dynamic parameters rather well and raises some warnings / events you can work with. For example:</p>
<pre>
BO.Router = Router.implement({
    // routes definition
    routes: {
        '#!customer/:id/'           : 'loadCustomer',
        '#!customer/:id/cancel/'    : 'cancelCustomer',
    },

    // router init
    init: function(){
        console.log('init')
    },

    loadCustomer: function() {
        console.log("loading customer with id " + this.param.id);

        BO.user.model.set({
            id: this.param.id
        });

        BO.user.model.on("change", function() {
            BO.user.view.render();
        });

        BO.user.model.fetch({
            success: function() {
                BO.user.model.off("change");
                BO.user.model.trigger("fetch");
            }
        });

    }
});
</pre>
<p>Second. <a href="http://mootools.net/forge/p/twipsy">Twipsy</a> &#8211; It&#8217;s a port of the Twitter Bootstrap Twipsy tooltip plugin (now renamed in BootStrap 2.0 to bootstrap-tooltip.js). Rather nice and just works. Also, extendible so you can implement the boostrap-popover.js through it.</p>
<p>Third. A plugin by yours truly and Arian from mootools-core &#8211; it&#8217;s <a href="http://mootools.net/forge/p/moostrapscrollspy">scrollspy</a>. That&#8217;s not David Walsh&#8217; scrollspy, it&#8217;s a port of the Twitter Bootstrap scrollspy instead. It allows you to react to elements of interest that come into view and do things to them or your nav items that are somehow related. </p>
<p>Fourth. &#8220;<a href="http://mootools.net/forge/p/moostrap">MooStrap</a> offers the initialization function of large-scale application from middle-scale. Every one initialization processing is performed and it secures that initialization of application is ensured.&#8221; &#8211; well, perhaps english is not their strong part but if you can get past things like &#8216;paturn&#8217;, it does provide a nice platform to build on. </p>
<p>Last but not least. <a href="https://github.com/lyonbros/composer.js">Composer.js</a> is a nice alternative to Backbone.js in MooTools. It is early days but it&#8217;s looking promising for the lyonbros plugin. There are some <a href="http://lyonbros.github.com/composer.js/#overview:diff">differences</a> in terms of approaches vs Backbone or Spine but it gets the job done. Only downside is, not mature enough and lack of tests supplied make it difficult to build on it and contribute. Hopefully, easily fixed.</p>
]]></content:encoded>
			<wfw:commentRss>http://fragged.org/mootools-plugins-round-up_1482.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk: enhanced (Session started)

 Served from: fragged.org @ 2022-09-25 06:40:15 by W3 Total Cache -->