<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns: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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Alex Urdea</title>
	
	<link>http://www.vibesphere.com</link>
	<description>a web developer's BLOG</description>
	<lastBuildDate>Thu, 03 Jan 2013 21:17:43 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/alexurdea" /><feedburner:info uri="alexurdea" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Sandboxing jQuery selection</title>
		<link>http://feedproxy.google.com/~r/alexurdea/~3/uR-auQyuvlM/</link>
		<comments>http://www.vibesphere.com/2012/11/sandboxing-jquery-selection/#comments</comments>
		<pubDate>Mon, 26 Nov 2012 11:55:21 +0000</pubDate>
		<dc:creator>alex</dc:creator>
				<category><![CDATA[article]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sandboxing jQuery]]></category>

		<guid isPermaLink="false">http://www.vibesphere.com/?p=258</guid>
		<description><![CDATA[Recently, I had to come up with an architecture that would allow multiple teams within Sky to write modules for a single page application. They were supposed to host their own JS scripts and CSS, and we'd load them into the app dynamically, when users would visit certain sections of the app. You can imagine]]></description>
			<content:encoded><![CDATA[<p>Recently, I had to come up with an architecture that would allow multiple teams within <a href="http://www.sky.com/" title="Sky.com" target="_blank">Sky</a> to write modules for a single page application. They were supposed to host their own JS scripts and CSS, and we'd load them into the app dynamically, when users would visit certain sections of the app.</p>
<p>You can imagine how without proper sandboxing, this would cause chaos, as a naive approach would allow a team's scripts and CSS to clash with other teams'. The proposed solution I came up with included enforcing modules,  dependency management and dynamic loading via <a href="http://requirejs.org/" title="RequireJS" target="_blank">Require JS</a>, using an MVC framework, hooks in the software versioning system that would trigger integration tests to run, and last, but very important: currying jQuery, so that when a selector was used, it would only select elements under a certain view's root element.</p>
<p>A selector that is too broad can have unforeseen effects, and is more dangerous when it affects parts of the DOM that you don't own. The solution is pretty simple: within a module you declare a local variable "$", or "jQuery", which will actually be a curried version of jQuery.</p>
<p>The jQuery function has multiple signatures: <a href="http://api.jquery.com/jQuery/" title="jQuery API" target="_blank">http://api.jquery.com/jQuery/</a>. When the first argument is a string, and no context is provided, we want to make sure that it can only grab elements that are owned by us. So, based on the parameters passed into our wrapper around jQuery, we decide whether to add our root element as context:</p>
<pre class="brush: jscript; title: ; notranslate">
    getSandboxedJQuery: function($root){
        var selector = null;
    
        return function(){
            var args = Array.prototype.slice.call(arguments);
    
            if (args.length == 1 &amp;&amp; (typeof (selector = args[0]) == 'string')){
                return $.apply(this, args.concat($root));
            }
            
            return $.apply(this, arguments);
        };
    }
</pre>
<p>Here is some more code in a demo (<a href="http://jsfiddle.net/LwFsy/22/" title="Fiddle" target="_blank">http://jsfiddle.net/LwFsy/22/</a>: you have a simple module that is run when the DOM has finished loading, and that receives an Api as a parameter. This is similar to a real life RequireJS module. Then, with the curried version of jQuery, we use a broad selector to find a div. If we'd select it the original jQuery, we'd also get another div outside our restricted tree.</p>
<p><iframe style="width: 100%; height: 300px" src="http://jsfiddle.net/LwFsy/22/embedded/" allowfullscreen="allowfullscreen" frameborder="0"></iframe></p>
<img src="http://feeds.feedburner.com/~r/alexurdea/~4/uR-auQyuvlM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.vibesphere.com/2012/11/sandboxing-jquery-selection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.vibesphere.com/2012/11/sandboxing-jquery-selection/</feedburner:origLink></item>
		<item>
		<title>Taking off dynamically added behavior in Javascript</title>
		<link>http://feedproxy.google.com/~r/alexurdea/~3/RIdEnWNlvwU/</link>
		<comments>http://www.vibesphere.com/2012/08/taking-off-dynamically-added-behavior-in-javascript/#comments</comments>
		<pubDate>Tue, 28 Aug 2012 16:08:32 +0000</pubDate>
		<dc:creator>alex</dc:creator>
				<category><![CDATA[article]]></category>
		<category><![CDATA[decorator pattern]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[removable decorator]]></category>

		<guid isPermaLink="false">http://www.vibesphere.com/?p=190</guid>
		<description><![CDATA[After reading some articles on the Decorator design pattern, I started searching for Javascript implementations that make it possible to remove the dynamically added behaviour. What if we want to use multiple decorators on an object, but want to keep the option to take some of them off later, while keeping others on? I dug]]></description>
			<content:encoded><![CDATA[<p>After reading some articles on the <a title="Decorator pattern Wiki" href="http://en.wikipedia.org/wiki/Decorator_pattern" target="_blank">Decorator design pattern</a>, I started searching for Javascript implementations that make it possible to remove the dynamically added behaviour. What if we want to use multiple decorators on an object, but want to keep the option to take some of them off later, while keeping others on?</p>
<p>I dug deeper on the Web, and found some discutions on this topic (<a title="question example #1" href="http://stackoverflow.com/questions/2166632/can-you-remove-a-decorator" target="_blank">example #1</a>, <a title="question example #2" href="http://stackoverflow.com/questions/186507/flexible-decorator-pattern" target="_blank">example #2</a> etc), but no Javascript implementations. I decided to experiment with this on my own, on the Decorator and Chain of Responsibility design patterns.</p>
<p>First, the <strong>Decorator</strong>. Here is its most common form in Javascript (see <a title="Decorator Wiki - Javascript implementation" href="http://en.wikipedia.org/wiki/Decorator_pattern#JavaScript_.28coffee_making_scenario.29" target="_blank">Wikipedia example</a>):</p>
<pre class="brush: jscript; title: ; notranslate">
var target,
    DemoDecorator1, DemoDecorator2;

// the object to be decorated
target = {
    someNumber: 0,
    getNumberString: function(){
        return &quot;&quot; + this.someNumber;
    }
};

// decorators
DemoDecorator1 = function(objToDecorate){
    var newNumber = objToDecorate.getNumberString() + &quot; 1&quot;;

    objToDecorate.getNumberString = function(){
        return newNumber;
    };

    return objToDecorate;
};

DemoDecorator2 = function(objToDecorate){
    var newNumber = objToDecorate.getNumberString() + &quot; 2&quot;;

    objToDecorate.getNumberString = function(){
        return newNumber;
    };

    return objToDecorate;
};

// The client code, that uses these decorator functions:
console.log(target.getNumberString());  // =&gt; &quot;0&quot;

target = new DemoDecorator2(new DemoDecorator1(target));
console.log(target.getNumberString());  // =&gt; &quot;0 1 2&quot;;
</pre>
<p>Please notice that the decorator functions are used in a <code>new</code> statement, but the decorator instance is not returned from the constructor. Instead, the initial target object is augmented and returned. To return something from a function that is to be used as a constructor is generally an anti-pattern in Javascript, but this is in fact the only kind of good usage that I know of.</p>
<p>Further, you can see that the target has been augmented, and you can imagine a more complicated scenario, where you have a bunch of decorators, and you want to take them off and put them back on. In that scenario, this solution would not work.</p>
<p>Before picking a path towards a solution, I’ve assumed that we might find ourselves in scenarios with swarms of objects that need to be decorated multiple times (perhaps in a Javascript game), so we don’t want to store lots clones of the intermediary states we get by decorating. Therefore, it seems cheaper to override the methods on the original objects, and just store the overridden methods.</p>
<p>Here’s my take on this - since the decorator is a constructor, and therefore creates an instance that <code>this</code> points to inside of it, we can store data on that instance - to be more precise, we will store the backed up methods. Again: there’s the decorator constructor, which creates the decorator instance, which is used to store the backed up methods.</p>
<p>I will stick to the functionality seen in the first code example to demo this - methods that concatenate strings to the string returned by the overridden method. So if the original <code>demo</code> method returns <code>"0"</code>, the <code>demo</code> method that’s defined on the decorator will wrap it, and return <code>"0 1"</code> etc.</p>
<p>The newly decorated object must somehow access the properties available on the target object in it’s previous state. This means that it should have a utility method attached to the target during the decoration - let’s call it <code>overriddenMethod</code>. So if before the wrap the <code>demo</code> method returned <code>"0"</code>, then on the decorator, we can define the new <code>demo</code> method:</p>
<pre class="brush: jscript; title: ; notranslate">
demo: function(){
    var oldDemoFn = this.overriddenMethod('demo');
    return (oldDemoFn ? oldDemoFn() : '') + ' 1';
}
</pre>
<p>Here’s the way we retrieve the overridden methods:</p>
<pre class="brush: jscript; title: ; notranslate">
Decorator.prototype = {
    ...
    overriddenMethod: function(methodName){
        return this.methodsBackup[methodName];
    },
    ...
};
</pre>
<p>I want the methods that are brought from a previous state to access other methods from that same state, not the current one. So here’s the trick to achieve this - binding.</p>
<p>If I have an initial object named <code>target</code>, that is not wrapped by any decorator yet, and I want to decorate it with <code>D1</code>, then when I archive the overridden methods, I will bind them to the object itself. If I want to add another decorator <code>D2</code> on top of that, then I will bind the backed up methods to the <code>D1</code> instance before archiving them:</p>
<pre class="brush: jscript; title: ; notranslate">
Decorator = function(decoratedObject){
    ...
    for (decMethod in this.newMethods){
        ...
        // If the object has already been decorated before (        // methods to the top-most decorator context. Else, bind it to the decorated object.
        if (typeof decoratedObject.decoratorScope == &quot;function&quot;){
            this.methodsBackup[decMethod] = _.bind(decoratedObject[decMethod], decoratedObject.decoratorScope());
        } else {
            this.methodsBackup[decMethod] = _.bind(decoratedObject[decMethod], decoratedObject);
        }
        decoratedObject[decMethod] = this.newMethods[decMethod];
        ...
    }

    return decoratedObject;
};
</pre>
<p>The bind function that I’ve used is from the <a title="Underscore JS" href="http://underscorejs.org/" target="_blank">Underscore JS</a> library. The third utility method, <code>removeDecorator</code>, will just return the current context (decorator instance).</p>
<p>There are a couple of other methods that are needed to make it all work - <code>decoratorScope</code>, which will return the decorator instance, and of course - <code>demoveDecorator</code>:</p>
<pre class="brush: jscript; title: ; notranslate">
Decorator = function(decoratedObject){
    ...
    return decoratedObject;
};
Decorator.extend = Extend.extendMethod;
Decorator.prototype = {
    removeDecorator: function(decoratedObject, decoratorConstructor){
        ...
    },

    overriddenMethod: function(methodName){
        ...
    },

    decoratorScope: function(){
        ...
    }
    ...
};
</pre>
<p>This all starts too look complicated. In fact, it’s too complicated to be called a design pattern. It’s a Decorator library, because one critical aspect of a design pattern candidate is to be simple enough to be easily explained. Well, as long as the client code is simple enough, it’s still useful. Here’s a possible usage:</p>
<pre class="brush: jscript; title: ; notranslate">
var target,
    DemoDecorator, DemoDecorator2;

target = {
    demo: function(){
        return &quot;not decorated&quot;;
    }
};

/* Client code: */
DemoDecorator = Decorator.extend({
    constructor: function(decoratedObject){
        decoratedObject = Decorator.apply(this, arguments);
        return decoratedObject;
    },
    newMethods: {
        demo: function(){
            var oldDemoFn = this.overriddenMethod('demo');
            return (oldDemoFn ? oldDemoFn() : '') + ' : decorated (DemoDecorator)';
        }
    }
});

DemoDecorator2 = Decorator.extend({
    constructor: function(decoratedObject){
        decoratedObject = Decorator.apply(this, arguments);
        return decoratedObject;
    },
    newMethods: {
        demo: function(){
            var oldDemoFn = this.overriddenMethod('demo');
            return (oldDemoFn ? oldDemoFn() : '') + ' : decorated (DemoDecorator II)';
        }
    }
});
</pre>
<p>I’ve used the <a title="Backbone JS inheritance" href="http://github.com/documentcloud/backbone/blob/38991ab5b3da4d5dff6d0de5cf8b6572aef5a437/backbone.js#L1412" target="_blank">Backbone JS</a> inheritance mechanism (extracted to a utility script), so the <code>constructor</code> attribute of the object that’s passed in will contain the constructor function that will be used. The <code>newMethods</code> contains the methods that will be added or that will override the existing ones when the target is decorated.</p>
<p>I don’t really like the fact that I’m sticking utility methods on the decorated object. It’s a bad idea to <a title="NCZ on modifying objects that you don't own" href="http://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/" target="_blank">modify objects that you don’t own</a>. They might interact in an unexpected way with the client code logic that does not expect them to be there, and their names might clash with names for existing methods.</p>
<p>The <code>removeDecorator</code> utility method can get passed a decorator constructor as a parameter, and will search the whole chain, from outermost to innermost decorator, and remove the first occurrence. If no decorator is passed in, it will just assume you want the outermost one removed. Basically, it “visits” one decorator instance at a time, and checks whether the next decorator instance down the line is to be removed (is an instance of the Decorator that was passed in). If so, it grabs it’s <code>methodsBackup</code> property and stores on the current decorator instance. This is enough to ensure that the correct decorator instance is now next in chain.</p>
<p>The code is on <a title="Github repo" href="http://github.com/alexurdea/Decorator-and-CoR-experiments/blob/master/decorator-add-remove-methods.js" target="_blank">github</a> (code above is for <a title="commit for discussed code" href="http://github.com/alexurdea/Decorator-and-CoR-experiments/blob/77de9cafaf1d3be53995d31b695407468e227336/decorator-add-remove-methods.js" target="_blank">this commit</a>), including <a title="unit tests" href="http://github.com/alexurdea/Decorator-and-CoR-experiments/blob/master/test/decorator-add-remove-methods.js" target="_blank">unit testing</a>. In an article that will follow, I will explore removing dynamically added functionality with the <a title="Chain of Responsibility Wiki" href="http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern" target="_blank">Chain of Responsibility</a> design pattern.</p>
<img src="http://feeds.feedburner.com/~r/alexurdea/~4/RIdEnWNlvwU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.vibesphere.com/2012/08/taking-off-dynamically-added-behavior-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.vibesphere.com/2012/08/taking-off-dynamically-added-behavior-in-javascript/</feedburner:origLink></item>
		<item>
		<title>This is the new blog</title>
		<link>http://feedproxy.google.com/~r/alexurdea/~3/nnPbVbw7mpQ/</link>
		<comments>http://www.vibesphere.com/2012/08/this-is-the-new-blog/#comments</comments>
		<pubDate>Mon, 27 Aug 2012 19:06:07 +0000</pubDate>
		<dc:creator>alex</dc:creator>
				<category><![CDATA[projects]]></category>

		<guid isPermaLink="false">http://www.vibesphere.com/?p=195</guid>
		<description><![CDATA[I haven't posted anything on my blog for a looong time, and I scrapped out all the old stuff. This is my new blog, with a new theme (that should respond to all screen resolutions), and hopefully there will be some new content here very soon. I'm not contracting at the moment, so I should]]></description>
			<content:encoded><![CDATA[<p>I haven't posted anything on my blog for a looong time, and I scrapped out all the old stuff. This is my new blog, with a new theme (that should respond to all screen resolutions), and hopefully there will be some new content here very soon. I'm not contracting at the moment, so I should easily find the time.</p>
<img src="http://feeds.feedburner.com/~r/alexurdea/~4/nnPbVbw7mpQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.vibesphere.com/2012/08/this-is-the-new-blog/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.vibesphere.com/2012/08/this-is-the-new-blog/</feedburner:origLink></item>
	</channel>
</rss>
