Category Archives: Uncategorized

Edit the Windows Host File

14 Jun 2017

While working through an issue I learned how to edit my Windows machines hosts file. Its easy enough to do provided you know how to do it. The resources on the Internet that I came across all had bits and pieces of the puzzle. Here I’m documenting them all in one place for the next time I need to do this.

First, lets open notepad with administrator privileges. At your Windows START menu type the word “notepad”. Look for the application icon, right-click it, and choose “Run as administrator”. Notepad will launch.

Next, click “File” then “Open” and type/paste the following path:

  • C:\Windows\System32\drivers\etc

For “File name” enter the word “hosts” without a file extension, then click “Open”.

Your hosts file will open. It already contains a description of how to use it so I wont go over that part. What I will go over is **how** to save the file. If you simply do CTRL+S or “File > Save” you have created a “hosts.txt” file NOT a “hosts” file. Therefore, your edits will have no effect.

To PROPERLY save the file, do the following:

  • Click “File”
  • Click “Save as…”
  • File name should be the word “hosts” with no file extension
  • “Encoding” should be “ANSI”
  • Click “Save”

Next you may need to clear your local DNS cache, to do so start a command prompt (In the START menu type “cmd” then hit ENTER) then type the following:

  • ipconfig /flushdns

Hit enter to execute the command and you will receive a message that the DNS Resolver Cache has been flushed.

To verify your edit worked try browsing to the host that you had setup.

The Pub/Sub Pattern and Event Delegation in jQuery

18 Jan 2014

Recently I had a project that was a single-page micro site. Much of the content changed without reloading so it naturally made use of Ajax. There was DOM manipulation and jQuery was used throughout. I knew I would have a buttons and other elements triggering events. I always delegate events and am always looking for ways to improve upon how I’ve done things in the past. With that in mind and my recent foray into patterns that I don’t usually use I decided to use the PubSub pattern with the usual jQuery event registrations to come up with what I think is a clean method of hooking things up. I’d like to take a moment to talk about how I put it all together.

The Pub/Sub Pattern

The Pub/Sub pattern consists of a system where objects Subscribe to a task of some other object. Once subscribed the Publisher notifies each subscriber that the task they are subscribed to has occurred. In this case the subscription object is an array of objects whose properties are themselves arrays of objects populated with function references. As they are arrays its easy to add (“subscribe”) or remove an index of an array (“unsubscribe”) via the array push and slice methods.

When the pattern is applied we essentially look for the subscription object property that matches the event type. Once found we iterate through all of the function references assigned to it.

We of course have to come up with a method of filtering the events instead of blindly calling all of the subscribers to the given event type. My personal approach to validating an event is two-fold, 1) first validate the type of the event, then 2) look for an expected HTML data attribute and branch out from there. This 2-step approach tends to vary depending on what is happening in any given application but is easily adaptable.

There is more to the subject of Pub/Subs but that’s the gist of it. For a great read on patterns try this link.

Event Delegation with the Pub/Sub Pattern

Lay the foundation

So then lets talk about how to apply this in jQuery while delegating events. I’ll start with some basic JavaScript and create our namespace:

;(function(ns){
    // private
    var _subscriptions= {}; // will hold our subscribers

    // public
    ns.init = function(){
        console.log(typeof _subscriptions);
    }
})(this.app = this.app || {})

Our example is namespaced to “app”. To access its public methods you would use “app.methodName”, for example. Next we need a way to init the app and I’ll do so with jQuery’s document.ready.

;(function(ns){
    // private
    var _subscriptions= {};

    // public
    ns.init = function(){
        console.log(typeof _subscriptions);
    }
})(this.app = this.app || {})

$(document).ready(function(){
    app.init();
});

The above prints the word “object” to the console.

OK, lets whip up a quick HTML page – it will have a single div. It will also contain an unordered list.

<div id="box" style="width:100px;height:100px;background-color:#ccc;border:1px solid #000"></div>
<ul>
    <li>Red</li>
    <li>Blue</li>
    <li>Green</li>
    <li>Orange</li>
    <li>Yellow</li>
</ul>

We will be delegating click events on our LI tags, making them function as our “buttons”. I won’t bother styling them as these are quick and dirty examples, you can make them pretty if you like 😉

The Subscriber Function

Next we need to create a subscriber function to populate the _subscriptions object. The _subscriptions object will hold all the functions (function references, known as “subscriptions” in PubSub lingo) that have “subscribed” to a particular event.

;(function(ns){
    // private
    var _subscriptions= {};

    // public

    /* app.subscribe()
     * This function adds subscribers to the _subscribe object */
    ns.subscribe = function(eType,cb){
        if (!_subscriptions.hasOwnProperty(eType)){
            _subscriptions[eType] = [];
        }
        _subscriptions[eType].push(cb);
    }
    ...
})(this.app = this.app || {})
...

Lets look at the app.subscribe method; it requires 2 arguments:

  • eType – this is the type of the event, such as “click”, or “mouseover”. Yes, its a string.
  • cb – short for callback, this is the function that is waiting to be notified that the associated event took place.

As you can tell from looking at the code we are adding properties to _subscribers that correspond to the event names. If that property doesn’t exist (via hasOwnProperty) then we create it and assign it an empty array. The array will hold the functions (callbacks) that will be notified that the event occurred.

The Publisher Function

The publisher “publishes” events to the subscribers when they occur. I personally prefer to use the word “notify” instead of “publisher”, as in “when the event occurs the subscribers are notified”.

Here’s my app.notify function (aka the “Publisher”):

;(function(ns){
    ...
    /* app.notify()
     * This function notifies those subscribers who have subscribed to a specific event */
    ns.notify = function(e){
        e.stopPropagation(); // stop additional events from firing
        if (!$(e.target).attr('data-action')){ // should we do anything at all?
            e.preventDefault();
            return;
        }
        var cbs = _subscriptions[e.type]; // what type of event are we dealing with?
        for (var i=0;i<cbs.length;i++){ // notify all who have subscribed to the event
            cbs[i](e); // pass along the event object to the subscriber
        }
    }
    ...
})(this.app = this.app || {})
...

One important thing to note is that we need a way of validating that something should happen when an event occurs. As I mentioned previously this is a two-step process. The first thing that I personally do is look for the data-action attribute in the event target. “data-action” is my own personal convention, feel free to use whatever makes sense to you. Anyway, if it exists in the event target – regardless of its value – then I know that it is something that one of my subscribers might want to know about.

The second part of validating the event is within each of the subscribers themselves. I’ll describe this in the next section as it is related to our html.

Setting up your HTML

We need to add the data-action attribute to our LI tags so that we can have something to filter our events against else we won’t be able to qualify that the event is something to pay attention to.

<div id="box" style="width:100px;height:100px;background-color:#ccc;border:1px solid #000"></div>
<ul>
    <li data-action="changeDivColor">Red</li>
    <li data-action="changeDivColor">Blue</li>
    &l;li data-action="changeDivColor">Green</li>
    <li data-action="changeDivColor">Orange</li>
    <li data-action="changeDivColor">Yellow</li>
</ul>

Ok, great, however, if we are planning on changing the color of the div then we need to know the color to use. Lets add another attribute and call it data-color.

<div id="box" style="width:100px;height:100px;background-color:#ccc;border:1px solid #000"></div>
<ul>
    <li data-action="changeDivColor" data-color="cd2027">Red</li>
    <li data-action="changeDivColor" data-color="3252d9">Blue</li>
    <li data-action="changeDivColor" data-color="40b645">Green</li>
    <li data-action="changeDivColor" data-color="e79622">Orange</li>
    <li data-action="changeDivColor" data-color="e7e522">Yellow</li>
</ul>

Ok, we’re done here. By virtue of both data-action and data-color we know that a) we should pay attention to events originating from these elements and b) we know what color to use.

Also please note that data-action serves two purposes – yes, if it exists we’ll notify our subscribers, but also, each subscriber will pay attention to the value of data-action. If it isn’t what the subscriber is expecting then it simply returns and stops executing. This is important as you may have any number of subscribers to the same event but any one of them should only continue if the value of data-action jives with what the subscriber’s role in life is.

Speaking of which, lets look at what a subscriber might look like…..

Event Delegation – Creating Subscriptions and the Subscriber

Well, its about time we delegated an event…. lets delegate the click event by adding some jQuery to our app.init function:

;(function(ns){
    ...
    ns.init = function(){
        // delegate the click event
        $('body').on('click','li',app.notify);
    }
...
})(this.app = this.app || {})
...

We’re delegating the click event such that when it occurs it calls app.notify so that all functions subscribed to the “click” can be notified. Yes, its mapped to the list item element.

Of course we have yet to subscribe to anything so lets create a subscription, again, this happens inside of app.init:

;(function(ns){
    ...
    ns.init = function(){
        // create a subscription
        app.subscribe('click',app.changeColor);

        // delegate the click event
        $('body').on('click','li',app.notify);
    }
})(this.app = this.app || {})
...

We’re missing the changeColor function so lets create it. Note the “if” statement at the top of the following block of code where we’re checking to see if it’s value is what is expected. If not then we return and don’t proceed any further:

;(function(ns){
    ...
    ns.changeColor= function(e){
        if ($(e.target).attr('data-action') != 'changeDivColor'){
            return;
        }
        $('#box').css('background-color','#' + $(e.target).attr('data-color'));
    }
    ...
})(this.app = this.app || {})
...

Thats it – here’s the example followed by the complete javascript:

;(function(ns){
    // private
    var _subscriptions= {}; // holds our subscriptions

    // public

    /* app.subscribe()
     * This function adds subscribers to the _subscribe object */
    ns.subscribe = function(eType,cb){
        if (!_subscriptions.hasOwnProperty(eType)){
            _subscriptions[eType] = [];
        }
        _subscriptions[eType].push(cb);
    }

    /* app.notify()
     * This function notifies those subscribers who have subscribed to a specific event */
    ns.notify = function(e){
        e.stopPropagation(); // stop additional events from firing
        if (!$(e.target).attr('data-action')){ // should we do anything at all?
            e.preventDefault();
            return;
        }
        var cbs = _subscriptions[e.type]; // what type of event are we dealing with?
        for (var i=0;i<cbs.length;i++){ // notify all who have subscribed to the event
            cbs[i](e); // pass along the event object to the subscriber
        }
    }

    /* app.changeColor()
     * This function was subscribed to "click" events */
    ns.changeColor= function(e){
        if ($(e.target).attr('data-action') != 'changeDivColor'){
            return;
        }
        $('#box').css('background-color','#' + $(e.target).attr('data-color'));
    }

    /* app.init()
     * Init the app - setup event subscriptions and event delegation */
    ns.init = function(){
        // create a subscription
        app.subscribe('click',app.changeColor);

        // delegate the click event
        $('body').on('click','li',app.notify);
    }
})(this.app = this.app || {})

$(document).ready(function(){
    app.init();
});
Implications

With this system in place all you have to do to add another subscriber that should be notified of a click event is add the following line in app.init

app.subscribe('click',app.myNewFunction);

Or, if you want something to react to a different event, such as a change event you would need to do the above **and** associate the event with our notify function.

app.subscribe('change',app.myNewFunction);
$('body').on('change','input',app.notify)

and then subsequent subscriptions to the “change” event would just need to do a regular subscription call:

app.subscribe('change',app.myOtherFunction);

In larger apps I use the above as a sort of switchboard between my models, views and utility objects. I don’t have a chain of function calls where func 1 calls func2 which calls func3, all spread out over a large script or multiple files, etc. Instead, my subscribed functions receive their notifications of the desired event, they inspect the event target to see if it is what it they are expecting (via the data-action attribute) and then different function calls are made (i.e. func1, func2, func3). My subscribers all live in my controller object so there’s no function chain to chase down as I can easily go to my controller and see exactly what functions are called for specific events and “actions” (recall my “data-action” convention).

To illustrate, here’s the same example with a few more buttons and events. View the source to review the code:

Logging the _subscriptions object to the console shows that there are 5 subscribers to the “click” event and 1 subscriber to the “mousemove” event.

Object {click: Array[5], mousemove: Array[1]}
  click: Array[5]
    0: function (e){
    1: function (e){
    2: function (e){
    3: function (e){
    4: function (e){
    length: 5
    __proto__: Array[0]
  mousemove: Array[1]
    0: function (e){
    length: 1
    __proto__: Array[0]
    __proto__: Object

Safari JS Engine > Chrome JS Engine?

13 Dec 2012

Got a Parser error in OSX Safari today that didn’t appear in Chrome. On the surface it appears as if its just a silly mistake that I overlooked – another developer used the “default” keyword in his XML, which I converted to JSON and used in my app which appeared similar to this:

...
var something = [{default:'abc'}];
var cat = something[0].default;
...

Chrome on Windows and OSX were fine yet Safari on OSX tripped on it. The answer is rather obvious – the word “default” is a reserved keyword and as such should be avoided. As a quick reference the rest of the keywords are:

break case, catch, continue, debugger, default, delete, do, else, finally, for, function, if, in, instanceof, new, return, switch, this, throw, try, typeof, var, void, while, with

The fix is simple, just treat the object as an associative array and use “default” as the key to get the desired value, like so:

...
var something = [{default:'abc'}];
var cat = something['default'];
...

Simple – and legal and in fact the first example is as well. While it is poor form to use a reserved keyword in the first example it is entirely legal to do so in that manner. The keyword exclusion only refers to using the keywords as identifiers which is not the case here. For reference see ECMAScript 5.1 here.

An example of using a keyword as an identifier (and thus something to be avoided) would be:

...
function default(){
   // wrong!
}
...

It appears that Apple has taken things a bit too far as they often do. See this list of browsers that correctly parse the sample JS with no issues:

Browsers that Accepted the first example:

  1. Windows
    1. Safari 5.1.1
    2. FireFox 17.0.1
    3. Chrome 23.0.1271.97
    4. IE 9
  2. OSX
    1. Chrome 10.0.648.151

Browsers that didn’t:

  1. OSX Safari 5.0.5

So… there it is. Just a quirk of Safari’s JS parser to be aware of. Its yet another example of the “Great Apple Irony” – their supposed adherence to standards. I suppose they are saving us from ourselves in a way as we as developers should know better but its still goes against the grain, so-to-speak.