Working with Vanilla JS in Web Applications

Writing JavaScript for IE and other antiquated browsers means classes and other helpful features of ES6 are not available. A similar effect can be achieved though and it is actually quite easy to do!

Why use Vanilla JS instead of any number of the frameworks available or even TypeScript? The answer is largely irrelevant if a choice has already been made. However, deciding to replace JavaScript with some alternative for all use cases is an absolute missing the mark. This article will describe the use of Vanilla JS leaving the choice of what language to use up to you.

Class Definitions & Namespaces

ES6 classes are not yet fully supported in the browser. Many of the limitations mentioned in this article are most relevant when developing with ES5 – such as developing for Internet Explorer or other antiquated browsers. Even without the full support of classes, a similar effect can be achieved in JavaScript and it is actually quite easy to do!

We first want to make sure that the class definition is contained. This means it should not pollute the global namespace with methods and variables. This can be accomplished by using a closure – a specific one called an IIFE.

(function (global) {
  "use strict";

  global.API = new MyObject();

  function MyObject() {
    var self = this;
    ... var privateVariable ... 
    ... function privateMethod() ... 
    ... self.publicMethod ... 
  }
})((1,eval)('this')); 

Notice that the global namespace is passed to the IIFE – since they are just methods, they can be used as such! If you want to know more about how the global namespace is obtained, check out this enlightening StackOverflow post: (1,eval)(‘this’) vs eval(‘this’) in JavaScript?

"use strict"; //seriously, do it.

The class can be initialized and stored at global scope such as inside a single app-specific namespace:

(function (global,app,http) {
  "use strict";

  global[app] = global[app] || {};
  global[app][http] = new Http();

  // global.App.http.publicMethods()
  function Http() {
    var self = this;
    // var privateVariables ...
    // self.publicMethods = function ...
    // function privateFunctions() ...
  }
})((1,eval)('this'),'App','http');

I find it easier to write client-side JavaScript as an API. Leveraging the design patterns this encourages offers many benefits to code quality and maintenance. In the code above, an Http instance is assigned to the http property in the global.App namespace. Certainly, this should contain our methods for making HTTP calls! Code organization is one of the best things about approaching the application’s client-side JavaScript in this way. Usually, the constructor function, not an instance, would be stored – which allows certain SOLID principles to be applied.

The Constructor Function

The Http function is a special kind – a constructor function. This means an instance can be created using the new operator with the constructor function call.

function MyObject() { }
var instance = new MyObject(); 

This should look familiar if you have ever created an instance in Object-Oriented code before.

Capturing this

The fact this isn’t always the same is both the power and the curse of JavaScript. The first line of the Http constructor function is capturing this in a specific context to help overcome the curse, and leverage the power:

function Http() {
  var self = this;
  ...
}

At the scope of the constructor function, this refers to the Http object. A private variable is declared and initialized to capture it and make it available to all public and private members of Http no matter what this happens to be during the invocation of those members. Capturing this only once and at the scope of the corresponding constructor function will reduce the possibility of this fulfilling its curse!

private Members

The variables and functions created at the scope of the Http constructor function will be available to all public and private members within the Http object.

function Http() {
  var self = this,
      eventHandlers = {};
  
  function addEventHandler(event, handler) { }
  function removeEventHandler(event, handler) { }
}

In this case, self, eventHandlers, and the add/remove event handler functions are private members of Http. They are not accessible to external sources – only public and private members of Http can access the private members of Http.

public Members

The properties and methods exposed from the Http object, that can be accessed from external code are considered public.

function Http() {
  var self = this;
  
  self.get = function (request) { ...
  self.post = function (request, data) { ...
}

Add public members to the self variable within the constructor function. This allows external code to perform the operations of an Http instance.

static Members

Members can be static as well. By declaring a variable on the constructor function itself, it can be assigned a value, instance, or function that is public while not depending on an instance to be created using the constructor function:

function Http() { }
Http.setup = function () { ... }

The static Http member can be used without creating an Http instance:

// ... application code doesn't create an Http instance
Http.setup();
// ... application code doesn't create an Http instance

The member is public and available anywhere the Http constructor function is available.

Execution Contexts

Without going into the depths of execution contexts in JavaScript, there are a few things to note. This section will describe a couple of different execution contexts and integration points at which JavaScript code is executed.

Global Context

There is only 1 global context – or global scope or global namespace. Any variable defined outside a function exists within the global context:

var x = 9;
function XManager() {
  var self = this;
  
  self.getX = function () { return x; }
  self.setX = function (value) { x = value; }
}

The global-scoped x variable is defined outside of the XManager function and assigned the value of 9. When getX is called, it will return the global-scoped x (the value of 9).

Local Scope – Function Execution Context

The alternative to the Global Scope is Local Scope. The local scope is defined by the function execution context:

var x = 9;
function XManager() {
  var self = this,
      x = 10;

  self.getInstanceX = function () {
    return x; // returns 10
  }
}

In this case, a variable x is declared twice. The first time is within the global execution context. This variable is accessible within XManager. Within the XManager constructor function, the private variable x is declared and initialized to 10. The getInstanceX method will return the variable x that is first in its execution context stack:

ecstack
Execution Context Stack (David Shariff)

The getInstanceX method is “Active Now”, XManager‘s private variable x is next, followed by the global-scoped variable x, and finally the global execution context.

All of this is to explain why getInstanceX returns 10 and not 9. Powerful stuff!

let & Block-Level Scope

I cannot discuss execution contexts without mentioning the keyword let. This keyword allows the declaration of block-level scope variables. Like ES6 classes, if antiquated browsers need to be supported, the let keyword will not be available.

function Start() {
  let x = 9; // variable assigned to value 9

  function XManager() {
    let x = 10; // different variable assigned to value 10

    function getX() {
      console.log(x); // return 10
    }

    console.log(x); // return 10
    getX();
  }

  console.log(x); // return 9
  XManager();
}

Start();

A block scope variable is accessible within its context (Start) and contained sub-blocks (XManager). The main difference from var is that the scope of var is the entire enclosing function. This means when using let, XManager and the contained sub-blocks (getX) have access to the new variable x assigned to the value of 10 while the variable x in the context of Start will still have the value of 9.

Event Handlers

Client-side JavaScript code is triggered by the user through DOM events as they interact with rendered HTML. When an event is triggered, its subscribers (event handlers) will be called to handle the event.

HTML – Event Subscription

<button id="submit" onclick="handleClick">Submit</button>

JAVASCRIPT – Event Subscription

var button = document.getElementById("submit");
button.addEventHandler('click', clickHandler);

JAVASCRIPT – Event Handler

function clickHandler() {
  console.log("Click event handled!");
}

Event handling marks the integration point between user interaction with HTML and the application API in JavaScript.

Understanding how to create objects and the Execution Context is important when writing client-side JavaScript. Designing the JavaScript as an API will help to further manage the pros and cons of the language.

Did My Jasmine Expect Method Get Called?

Inspecting expectations in Jasmine

When unit testing with Jasmine, expect() calls are not mandatory. That is, calling expect() at least once is not enforced by Jasmine. I recently ran into a problem which caused me to ask myself “did that expect method get called?”. I couldn’t count on Jasmine for this – in fact, my tests pass whether I include the expect() call or comment it out! So I went digging..

I determined that I could simply create spies for my expect() calls. This is an easy way to leverage Jasmine to inspect your tests. Simply create your spy:

const expectSpy: jasmine.Spy =
   spyOn(window,'expect').and.callThrough();

I am using TypeScript for my unit tests. Since the expect() method is global and I am running my tests in a browser, I use the window object directly. There are ways to obtain the global object without this sort of hard-coding but, that is besides the point.

Moving on, the expect() calls must work properly so and.callThrough() is called. This is important. Without including and.callThrough(), your tests will fail because, rather than Jasmine’s expect() execution, you will be limited to a jasmine.Spy.

Here is a more complete example of a test with an expect spy – slightly modified from a sample Angular 2 application I have been working on:

it('should trigger on selection change', async(() => {
  const expectSpy: jasmine.Spy =
    spyOn(window,'expect').and.callThrough();

  const triggerSpy = spyOn(component, 'triggerThemeChanged');

  const select =
    fixture.debugElement.query(By.css('select.theme-selector'));

  dispatchEvent(select.nativeElement, 'change');

  fixture.whenStable().then(() => {
    expect(triggerSpy).toHaveBeenCalledTimes(1);
  }).then(() => {
    expect(expectSpy).toHaveBeenCalledTimes(2);
  });
}));

There are a few things about this test that are not the point of this article – what the heck is async() and the apparent improper use of dispatchEvent()? The important bits are the use of Promises as implied by the use of then() callbacks, the creation of the expect spy, and the inspection of the expect spy.

The test creates the expect spy and then uses expect() as usual within the test until it finally inspects the expect spy. Remember, the inspection of the expect spy counts as an expect() call! This is why expect(expectSpy).toHaveBeenCalledTimes(2) is called with 2 rather than 1.

I stopped at the call count. This test could be extended to further leverage the Jasmine API by looking at expectSpy.calls with other handy methods to make sure the expect() calls were made properly. I’ll leave that for an exercise for the reader. Just make sure your testing, at a minimum, covers the scope of your problem.

If you have had similar issues or have explored this in more depth I would be very interested in hearing about your journey! Comments are welcomed and appreciated.

Meteor Hang-up: Extracting Package….

An all too common tale of a stalled package installation and the valiant efforts to resolve it

In the world of Node.js and NPM, things can change at an increasingly rapid pace. This causes pain when starting or upgrading projects that require NPM packages. While there are sites like Greenkeeper, I see them as symptoms of a flawed system. Yes, I will say that without offering alternative solutions because at the moment I am aware of exactly zero. Suggestions welcome!

It is a wonderful world of possibility.

Complaining about NPM is not the point of this article. I’ll stop wasting time:

Recently I came across a few excellent tutorials about using Meteor, Ionic 2, Angular and React. They eventually brought me to Telescope Nova. My first thought was: this looks promising.

After forking and cloning and other Gitisms, I was ready to start the application:

npm install
npm run start

Of course, I have a Microsoft development background so when I saw a bunch of red because of ‘.sh’ I wondered why these two letters were such a problem. I ended up having to update my start script to exclude this bit of code. The script I excluded simply renames a sample_settings.json file to settings.json. I figured that was a safe thing to shortcut in this case by renaming it myself.

My next step was to try it again!

> Nova@1.0.0 start C:\Demo\Telescope
> meteor --settings settings.json
 [[[[[ C:\Demo\Telescope ]]]]]
 => Started proxy.
 => Started MongoDB.
 => Extracting std:account-ui@1.2.17

To be honest, I let it try for a few hours and it just could not get that pesky package extracted. Certainly, something had gone wrong before that. After digging into the depths of Nova, Meteor, and NPM, I finally explicitly searched within Stack Overflow for Extracting std:accounts-ui.

The search came up with only 2 results which are both linked at the bottom of this article. Most importantly: following the suggestions solved my problem.

I fixed the issue by relocating the 7z executable (7z.exe) from: C:\Users\[UserName]\AppData\Local\.meteor\packages\meteor-tool\1.4.2_3\mt-os.windows.x86_32\dev_bundle\bin to a place outside of any source code, build code, and tool locations. I relocated it and instead of removing it because I didn’t want to mess up my machine any more than it already may have been. Turns out, the missing 7z.exe was all it took to get my Meteor package installed properly!

It figures that the solution was to create a sort of FileNotFound scenario.

In an effort to spread the word, the following links lead me to this solution:

http://stackoverflow.com/questions/41155583/meteor-1-4-2-3-adding-package-extracts-forever-windows

http://stackoverflow.com/questions/41195227/meteor-package-extracting-forever

https://github.com/studiointeract/accounts-ui/issues/67

https://github.com/meteor/meteor/issues/7688

I hope this helps. It is a rather simple solution in the end. I am very interested in learning about your past issues with our current favorite packaging system and its various dependencies. Feel free to comment if you have hard-fought wisdom to share!

UPDATE: Just a quick update here, turns out this approach can be helpful when updating packages or if you get stuck here ‘Extracting meteor-tool@1.4.2_5’ (after the recent patch). Note: extracting meteor tools can take a while (upward of 30+ minutes) so expect to wait a bit to know if it fails.

Write End-to-End Tests for Your Angular 2 Applications With Protractor

Add E2E testing and make sure your users don’t fail!

Testing your applications is a critical step in ensuring software quality. While many agree, it can be hard to justice the budget for it. This issue can occur when development and testing are imagined as two separable activities. In fact, there are common practices in place designed around their coupling (see TDD). End-to-End (E2E) testing is another common practice designed in this way.

E2E testing can be thought of as an additional direction or angle in which to test an Angular 2 application’s logic. It tests, from a user’s perspective, if the application does what is expected. If these tests fail, your users will fail and the failure will be right in their face. This user-centric approach is critical to ensuring an intended user experience. Writing these tests will produce a detailed user experience specification enforced by simply making sure the tests pass.

End to End testing does not replace QA resources. All software is written by people and people are not perfect – no matter what they say.

Interacting with Your Application

To begin creating the tests we need a way to interact with the application. This is made easier with Protractor. With Protractor, Selenium can be leveraged within JavaScript including integration with Angular applications. A few critical components are exposed to you through Protractor.

browser – browser-scoped operations such as navigating to a particular URL.
element – provides a way to retrieve the UI components of your application from within your tests.
by – What UI component do you want and how should it be found?
promise – support asynchronous operations.
ElementFinder – perform operations on retrieved UI components.
ElementArrayFinder – perform operations on an array of retrieved UI components.

Importing from Protractor

Importing what you need from Protractor is as easy as importing anything else:

import {
   browser, element, by, promise, ElementFinder } from 'protractor';

Navigating to a URL

Get to the correct page using browser.get():

navigateTo() {
  return browser.get('/list');
}

Retrieving and Manipulating UI Components:

Use the Protractor API to retrieve elements and perform operations in your application:

clickEditButton(): promise.Promise {
  return element(by.css('.edit-button')).click();
}

Creating Page Objects

Now that a few fundamentals are out of the way, let’s take a look at organizing our tests. First, we need to create Page Objects. These objects encapsulate interactions with UI components. Implementing Page Objects could be thought of as user experience mapping including structure and operations.

With single-page applications, a “Page Object” could get quite unwieldy! This is why we need to consider the structure of the application. Considering the Angular Components within the application is a great way to begin dividing your Page Objects. Take a simple Todo application shown in Figure 1:

todoscreenshot
Figure 1: Sample todo application

Even with this simple application, there is a lot to include in just a single Page Object. This screen can be divided up into four distinct areas: header, menu, list, and details. Let’s look at how these can be created using separate Page Objects:

Header

todoheader
// header.po.ts
import { promise, ElementFinder } from 'protractor';

export class Header {
  getContainer(): ElementFinder {
    return element(by.css('.header'));
  }
  getHeader(): ElementFinder {
    return this.getContainer().element(by.css('.header-text'));
  }
  getHeaderText(): promise.Promise {
    return this.getHeader().getText();
  }
}

Menu

todomenu
// menu.po.ts
import { element, by, promise,
  ElementFinder, ElementArrayFinder } from 'protractor';

export class Menu {
  getContainer(): ElementFinder {
    return element(by.css('.menu'));
  }
  getMenuItems(): ElementArrayFinder {
    return element.all(by.css('.menu-item'));
  }
  getActiveMenuItem(): ElementFinder {
    return this.getContainer()
       .element(by.css('.menu-item.active-menu-item'));
  }
  getActiveMenuItemText(): promise.Promise {
    return this.getActiveMenuItem().getText();
  }
  getCompletedMenuItem(): ElementFinder {
    return this.getContainer()
       .element(by.css('.menu-item.completed-menu-item'));
  }
  getCompletedMenuItemText(): promise.Promise {
    return this.getCompletedMenuItem().getText();
  }
  getAddMenuItem(): ElementFinder {
    return this.getContainer()
       .element(by.css('.menu-item.add-menu-item'));
  }
  getAddMenuItemText(): promise.Promise {
    return this.getAddMenuItem().getText();
  }
  clickActiveMenuItem(): promise.Promise {
    return this.getActiveMenuItem().click();
  }
  clickCompletedMenuItem(): promise.Promise {
    return this.getCompletedMenuItem().click();
  }
  clickAddMenuItem(): promise.Promise {
    return this.getAddMenuItem().click();
  }
}

List

todolist
// list.po.ts
import { element, by, promise,
  ElementFinder, ElementArrayFinder } from 'protractor';

export class List {
  getContainer(): ElementFinder {
    return element(by.css('.list'));
  }
  getItems(): ElementArrayFinder {
    return element.all(by.css('app-todo'));
  }
  getItem(index: Number): ElementFinder {
    return this.getItems().get(index);
  }
  getEditButton(index: Number): ElementFinder {
    return this.getItem(index).element(by.css('.edit'));
  }
  getDeleteButton(index: Number): ElementFinder {
    return this.getItem(index).element(by.css('.delete'));
  }
  clickEditButton(index: Number): promise.Promise {
    return this.getEditButton(index).click();
  }
  clickDeleteButton(index: Number): promise.Promise {
    return this.getDeleteButton(index).click();
  }
}

Details

tododetails
// details.po.ts
import { element, by, promise, ElementFinder } from 'protractor';

export class Details {
  getContainer(): ElementFinder {
    return element(by.css('.details'));
  }
  getDetailHeader(): ElementFinder {
    return this.getContainer().element(by.css('.detail-header'));
  }
  getDetailHeaderText(): promise.Promise {
    return this.getDetailHeader().getText();
  }
  getDescription(): ElementFinder {
    return this.getContainer().element(by.css('.detail-description'));
  }
  getDescriptionText(): promise.Promise {
    return this.getDescription().getText();
  }
}

Alright, that was a lot of code. Let’s take a step back for a moment. We are creating Page Objects representing the distinct areas of the UI that we have determined. Each Page Object has offered the ability to retrieve (e.g. getContainer) and operate (e.g. clickDeleteButton) on UI elements from their respective areas. The last item we need now is a root Page Object to complete our Page Object hierarchy.

The Page Object Hierarchy

todopageobjecthierarchy

Yes, I can’t seem to help it – there is one additional Page Object that has been included along with the root Page Object. The Item Page Object will encapsulate the structure and logic of each todo item within the List.

An instance of each leaf Page Object (which includes header, menu, list, and details) is stored on the root Page Object (TodoApp). This provides the ability to write complex operations while exposing a simple API to your tests:

// snippet todo-app.po.ts
export class TodoApp {
  constructor() {
    this.list = new List();
  }

  private list: List;

  removeAllItems(): promise.Promise<void[]> {
   let promises: Array<promise.Promise> = new Array<promise.Promise>();

   this.list.getItems().each(item => {
    promises.push(item.clickDeleteButton());
   });

   return promise.all(promises);
  }
}

In removeAllItems() each todo item is found and its Delete button is clicked. We should no longer have any todo items. This is a testable scenario. Testing this would mean answering the question – what happens when there are no items? We can use our Page Objects to create tests around this scenario!

Testing with Page Objects

Creating tests using Page Objects can clean up your tests and allows more explicit definition of your test scenarios. This way also helps keep the user interface definition out of the tests making it easier to maintain – keep in sync with your application!

Jasmine Syntax

If you have written tests using Jasmine before, you know how to create tests for Protractor. It is a great tool for writing unit tests! It is just as good for writing tests with Protractor. Simply follow their tutorials to learn more about Jasmine.

Writing Tests

Now let’s see some tests. We will test the ability to remove all items by clicking their Delete button:

// todo-app.e2e-spec.ts
import { TodoApp } from './todo-app.po.ts'

describe('Todo Item', () => {
 let page: TodoApp;
 
 beforeEach(() => {
   page = new TodoApp();
 });
 
 it('delete button should remove todo item', (done) => {
   page.navigateTo();
   const text: String = 'test text';
   
   page.addItem(text, text).then(() => {
     page.removeAllItems().then(() => {
       expect(page.getItems().count()).toBe(0);
       done();
     });
   });
 });
});

This test sample is following a few common practices. First, the root Page Object is imported:

import { TodoApp } from './todo-app.po.ts';

Next, the top-level test suite is defined. Within this test suite a variable is defined to hold our root Page Object. Then comes the initialization of each test in the suite:

beforeEach(() => {
  page = new TodoApp();
});

This is a fairly rudimentary example but, the initialization code will run once before each test in the suite. Make sure to place any necessary test initialization code within this block such as initializing Page Objects and setting up the UI.

Next comes the fun. The test is defined using typical Jasmine syntax with support for asynchronous test code:

it('delete button should remove todo item', (done) => {
  page.navigateTo();
  const text: String = 'test text';
 
  page.addItem(text, text).then(() => {
    page.removeAllItems().then(() => {
      expect(page.getItems().count()).toBe(0);
      done();
    });
  });
});

The first step in our test is to navigate to the TodoApp and create a variable to hold our new item text and description.

Considering that the test is for ensuring items get deleted when their Delete button is clicked, we need to be sure there is an item to remove! Using a Page Object method for adding an item, a new todo item is added to the screen using the new item text and description defined earlier. Since the method returns a promise, we use then() to continue execution.

We have added an item. Now its time to remove it. We know that the Page Object contains a method that clicks a todo item’s Delete button. We also know that the Page Object provides the ability to remove all of the todo items in the list using this method. This means we can simply call removeAllItems() and check the list to make sure it is empty.

If the test passes we can say the Delete button works for each todo item.

Mean TODO

There is a sample application demonstrating Angular 2 in the MEAN Stack that includes a set of E2E tests. Simply follow the guide on GitHub to get started!

Thank you for reading this far! If you have any comments, questions or concerns please send a message.

 

Angular 2 in the MEAN Stack – A Project Template

Should I leverage my love for JavaScript to develop an application from the ground up? Yes Please!

I recently became aware of the beauty of developing with the MEAN stack. It started with my desire to brush up on Angular 2 and using the Angular CLI. I ended up with a TODO application that runs on Node using MongoDB, Express.js, and Angular 2 (from a foundation found here: https://scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli).

I am also a fan of LESS. It makes writing modular CSS a breeze. I am also not yet sold on the Styled Component approach Angular is now pushing. I do believe Component-based UI architectures make writing modular CSS quite simple. I just don’t think styles should be located across the application when, with an optimally modular UI, the CSS used can be quite minimal. Beyond that, an application should have a look and feel that gives the user at least the illusion of cohesiveness. Easily done when styles are in one place.

Using Feature Modules with Angular 2 makes a lot of sense. Each feature can be created in isolation while still being integrated with the rest of the application. The module structure of the TODO application is shown in Figure 1. This structure allows the application to be extended and makes features easy to find for updates and bug fixes. The approach also provides a more SOLID application.

todofeaturemodule
Figure 1: Module structure

With the focus on Angular 2, the server-side code is quite minimal and I don’t have much to say about it. Figure 2 depicts the main ideas.

todoapi
Figure 2: Server-side

I almost forgot to mention that this app is on GitHub: https://github.com/calebmagenic/ng2-mean. Let me know your thoughts!

I look forward to continuing my work with the MEAN stack and sharing what I find that works – and what doesn’t work so well. Look for more in the future.

UPDATE: After working with later versions of Angular, I found it to be an effective front-end framework that can solve enterprise-level concerns. I enjoy working with TypeScript and creating stunning multi-faceted projects with the help of Nx Workspaces. To make it easier to get up to speed with the MEAN stack, Manning Publications released a new book called Getting Mean with Mongo, Express, Angular, and Node (2nd Ed.) written by two smashing authors and developers in the field Simon Holmes and Clive Harper. After leveraging this book, I am able to create substantial solutions using the MEAN stack. I highly recommend it even if you are just trying it out. It has a ton of immediately actionable information packed into it.

Pad A String In JavaScript Using Augmentation

Ever needed to pad a string in JavaScript with a certain character? This article will describe a simple extension to the String prototype that will do just that! -Perhaps with a bit more flexibility.

To get right to the point, here is the implementation:

if ( "undefined" === typeof String.prototype.pad ) {
  String.prototype.pad = function _String__pad ( obj ) {
    var result = this,
        width = 2,
        padChar = "0",
        prefix = false;
    if ( obj ) {
       if ( "object" === typeof obj ) {
         if ( obj.prefix ) { prefix = obj.prefix };
         if ( obj.width ) { width = obj.width };
         if ( obj.char ) { padChar = obj.char };
       } else if ( "string" === typeof obj ) {
         padChar = obj;
       } else if ( "number" === typeof obj ) {
         width = obj;
       }
    }
    while ( this && width > result.length ) {
      if ( prefix ) {
        result = padChar + result;
      } else {
        result += padChar;
      }
    }
    return result;
  };
} 

Before I get to the guts of the above code snippet, I wish to examine a few reasons it is possible:

  • Instance methods can be created on-the-fly. This means a String object such as “Hello World” would immediately contain the above method named “pad”. The method could be called for example “Hello World”.pad().
  • JavaScript is a dynamic language. In this case, it means any variable can be of any type at any point during runtime.
  • A method exists as a “function”. This can be explicitly tested.
  • Instance methods exist in an Object’s prototype.

Now for the details.

First, it is always wise to make sure your code is not performing unnecessary work. To this end, a check is made to make sure the function does not already exist on String’s prototype. If it does not already exist, it is created.

Four variables are then declared presenting the features of this method:

  • Returns a new string
  • Supports a custom string width
  • Supports a custom padding character
  • Supports either prefix padding or suffix padding

These variables are optionally overridden by the object, String, or Number argument given. This is one of many times when the beauty of JavaScript’s weakly-typed nature really shines. Any of the features can be overridden given the appropriate argument type and value. If the argument is an object, the method expects the object to contain the three properties: prefix, width, and char. If the argument is a String the method assumes the client is attempting to override the padding character. If the argument is a number, the method assumes the client is attempting to override the padded string width.

Let’s talk more about the padded string width. This is important for the next bit of code.

Assume there is a string indicating an order number of “99D”. The requirements say order numbers less than 5 characters must be padded on the left with zeros. The implementation supports this:

"99D".pad({ char: "0", width: 5, prefix: true }); //result: "0099D"

-or-

var orderNumber = "99D";
orderNumber.pad({
  char: "0",
  width: 5,
  prefix: true }); //result: "0099D"

-or-

var padOptions = { char: "0", width: 5, prefix: true };
"99D".pad(padOptions); //result: "0099D"

To get this set width, a while loop is used. While the string is less than the given width, the method adds the specified pad character to either the beginning or the end of the string based on whether it should be a prefix or not. Once the string is at least the length of the specified padded string width, the method breaks out of the while loop and returns the resultant string.

There are other ways to use this implementation of the pad method as well.

Specify the padding character:

"E".pad("T"); //result: "ET"

Specify the padded string width:

"1".pad(2); //result: "10"

There are a few improvements or additional features that could be implemented for this method but, this is a flexible start.

Safe & DRY JavaScript Augmentation

Augmentation is one of my favorite features of JavaScript. Being able to, at any point, add static and instance methods to new and existing types is a wonderful feature of this dynamic language. In this post, I’ll describe two common ways of augmenting JavaScript types and how those ways can be made safer while adhering to the DRY principle.

Instance Methods

One of the most common uses of augmentation is adding instance methods to types. Using a type’s prototype chain, methods can be added to all new and existing instances of the augmented type:

Array.prototype.indexOf = function (item) {
  /* excluded for brevity */
};

In this code snippet, the indexOf function was added to the prototype of the Array object. Each Array instance will have this method (even if the instance was created before the method was defined). This method will also replace any previous implementations of the “indexOf” function. It is best to make sure the function doesn’t already exist:

if (typeof Array.prototype.indexOf === "undefined") {
  Array.prototype.indexOf = function (item) {
    /* excluded for brevity */
  };
}

Here the typeof operator is used to determine whether the method is undefined. If it is, the method implementation is added to the Array object.

Static Methods

Functions can also be added as static methods of a given type:

String.Format = function (format) {
  /* excluded for brevity */
};

In the code snippet above the “Format” method was added as a static method of the String object. Similar to adding instance methods, it is best to make sure this method does not already exist:

if (typeof String.Format === "undefined") {
  String.Format = function (format) {
    /* excluded for brevity */
  };
}

Don’t Repeat Yourself

If your augmentation code is augmenting multiple types or with multiple methods, the type check will be used over and over. Why not make that part of the code reusable? By using augmentation, a reusable method can be implemented to perform this type check and the augmentation:

if (typeof Function.safeAugment === "undefined") {
  Function.safeAugment = function (obj, func, impl) {
    var method = obj[func];
    if (typeof method === "undefined") {
      obj[func] = impl;
    }
  };
}

Here the augmentation code is wrapped inside the “safeAugment” function. This function is implemented as a static method of the “Function” object. The “safeAugment” function takes three parameters: the object to augment, the function name to add to the object, and the implementation of the function. Here is an example of its use:

Function.safeAugment(Array.prototype, "indexOf", function (item) {
  /* excluded for brevity */
});

The safeAugment function is used to define our indexOf instance method for the Array object. The safeAugment function can be used to defined static methods as well:

Function.safeAugment(String, "Format", function (item) {
  /* excluded for brevity */
});

Here the “Format” method is added to the String object as a static method.

Enhancing the Augmentation Code

As it stands now, the safeAugment function performs its duty: augment the given object with the given method with the given implementation. The first and most obvious improvement would be to validate its parameters. This means making sure that each parameter is of an expected type so the object to augment exists, the function name is a string (and not null), and the implementation is a function. Improvements beyond this are more dependent on your given circumstances. Perhaps you want to allow the implementation to be null, or add logging capabilities, or locate the point in which all the elements in the multiverse will collide, etc, etc. The point is to safely augment JavaScript types while adhering to the DRY principle.

Rudimentary Way to Make a WinRT Component Object Bindable in WinJS

When projecting a WinRT Component object to WinJS, I kept running into an exception saying that the WinRT object could not be extended. This post will briefly describe how I got around this issue.

There are a few things known that helped come to this solution:

  • I didn’t need to worry about differences between one-way/two-way binding. All I had to do was present the object onto the screen.
  • Average JavaScript objects are bindable with WinJS
  • JavaScript objects are essentially associative arrays
  • If a member does not exist when referenced in an assignment operation, it is first created, then assigned.
  • I can essentially “clone” objects by iteratively copying members using array syntax.

This last item is exactly what I did! Let me elaborate: It is simple. At this point, we can’t bind to WinRT Objects therefore we need to make them bindable ourselves. The code snippet below shows this.

function _makeBindable(obj) {
  var o = new Object();
  for (m in obj) {
    o[m] = obj[m];
  }
  return o;
}
var winrtObj = Projection.getWinRTObject();
// cannot bind winrtObj
var bindableWinRTObj = _makeBindable(winrtObj);
// use bindableWinRTObj for data-binding scenarios

Lets look at _makeBindable in a little more detail.

First, the function takes an object as a parameter. This object is the WinRT object that is causing issues. Then, a local variable is created assigned to a new Object.

The next part is very important – iterating over the members of the WinRT object. Using a for-in loop, cloning an object is quite easy. In this case, “m” represents the current member name as a string. Since JavaScript objects are essentially associative arrays, “m” can be used to access the current WinRT object’s member using array syntax. The member name is also used to assign to the local variable that was previously created. This effectively copied the current member from the WinRT object to the local variable.

Once all of the members are copied, the local variable is returned for use in data-binding scenarios.

Debugging JavaScript with Web Inspector

Debugging JavaScript can be a nightmare… Unless of course, you know how to effectively use Web Inspector.

Below is a video from Tom Dale (co-author of the JavaScript MVC Framework Ember.js (http://emberjs.com/). He first details debugging JavaScript using Web Inspector.

JavaScript Intellisense Is Not Only for Windows Store Projects

Intellisense is a beautiful thing. Viewing hints, documentation, and available overloads as you type is simply awesome. This is very common in C# and VB but what about JavaScript? Ever wish you had these same rich experiences while writing your JavaScript code? With Visual Studio 2012, you can! Below is an excellent video by Scott Hanselman explaining how this is possible:

http://www.asp.net/vnext/overview/visual-studio/visual-studio-2012-javascript-editor

There is some helpful MSDN documentation on this as well:

Overviewhttp://msdn.microsoft.com/en-us/library/bb385682.aspx

How-tohttp://msdn.microsoft.com/en-us/library/bb514138.aspx

Now JavaScript is beautiful too! ..or at least a little more.