Dynamic super classes (extends) in ES6

tl;dr

Create a class factory which allows dynamic super classes to by applied to an es6 class (dynamic inheritance). This will be transparent to a consumer — meaning they will interact with it in the same way as the initial class.

Problem statement:

I was recently working on some code which extended an asynchronous module to add some additional functionality. The class initially looked like this:

However, testing a module like this is difficult for two reasons.

  1. The async nature of the behavior is challenging to test and mock
  2. The explicit super class Fetcher which is imported in the module is difficult to override without reaching down into the prototype and manually modifying methods during the test. Yuck!

Solution:

Wrap the extending (child) class declaration with a function, which accepts a parameter for its super class, and a default parameter value. Then the inner class can be declared using the SuperClass parameter. This will allow the child class to reference either its default parent, or the custom super class explicitly passed in.

The child class then extends or overwrites any methods from super that are required. Finally, a new’d up instance of the child class is returned with the remaining arguments passed to the class factory function.

For consistency of use, we can force the function to be called using new, making the abstraction completely transparent to any consumer.

Now we can call the extending class (with no SuperClass property) and it will have its default and expected behavior:

Or, with the SuperClass property to dynamically set its parent:

Working Example

 

See the Pen dynamic super class by Michael Jasper (@mdjasper) on CodePen.

ES6 Depth-first object (tree) search

A co-worker recently asked about searching for properties in a JavaScript object, where the properties could be located in unspecified locations within the object (not nested though). This was the job for a depth-first tree search! I don’t get to post about more traditional computer science topics very frequently, so I thought I’d share my little ES6 recursive search function:

Explanation (commented source)

Example

This code can be used like so:

 

Front-end Series: JavaScript debugging tips and tricks

Note: many of these tips are written with Chrome in mind, but are applicable to any modern browser with developer tools.

  1. Understand what is happening in your code
  2. Set and use Breakpoints
  3. Use the Console api
  4. De-minify
  5. Modify scripts locally
  6. Use a Unit-Testing framework

1. Understand what is happening in your code

A prerequisite to debugging is understanding the code in question. Before debugging, you should be able to answer: what is the purpose of this function? What should the parameters be? How will this line affect local and global variables?

Basically, run the code mentally before trying to debug.

2. Set and use Breakpoints

Once you understand how the code should function, set execution breakpoints at key places. When reached, a breakpoint will pause the execution of script on that line. You can then “step-through” the code one line at a time. This view also allows you to inspect any global or local values to ensure they are what you expect them to be. Often times, you can observe a variable which should contain a value, but is undefined. From there it is easy to trace your way back up and see where the error is occurring.

Breakpoints can be set by clicking on the line-number in the script tab of chrome developer tools, or programmatically using the  debugger; directive.

debug-breakpoints

Use the console api

While sprinkling a few  console.log ‘s sparingly throughout your code can be useful, the console api has many useful functions that might serve the purpose better. Here are a few console api methods I have found useful:

console.dir

Displays all the properties of an object.

console.dir

 console.table

Formats arrays and objects as tables, and allows sorting on columns.
console.table

console.time

Starts and stops a timer (string tag based), logs time (in ms) of intermediate code.
console.time

console.memory

Returns heap information for this process.
console.memory

console.trace

Returns a stack trace for the function where it is called.

console.trace

4. De-minify

When debugging, it can be very frustrating to see an error like:

When at all possible, swap out the minified version for a full expanded and commented version of the script.

When a full version is not available, Chrome’s developer tools come to the rescue. The curly brace button below the script will automatically expand lines for better breakpointing and debugging. It does not however rename obfuscated variable names.
de-minify

Minification bugs

Every so often, you can run into the maddening bug of a full script working, and the same minified script breaking. Luckily, these bugs often attributable to one of a few small problems (mostly having to do with missing semicolons).

For example:

These bugs can also creep in from preceding scripts, or when multiple scripts are concatenated together. This is the reason that jQuery plugins typically start with a  ; . It is a preventative measure against misbehaving code above it.

5. Modify scripts locally

Chrome allows you to modify script files and run them locally. Simply double click into source file, type, and CTRL-S to save. Not much more to explain, but very useful trick!

6. Use a Unit Testing framework

There are a handful of very good third-party unit-testing frameworks for JavaScript, each with their own philosophy and syntax.

See this great Stack Overflow post for many more.

Creating your own JavaScript Library – part 2 – Event Handling

write-your-own-javascript-libraryIn Part 1 of Creating your own JavaScript library, we cover the library essentials: library design, creating a solid object constructor, and adding functions by extending the object prototype. This post focuses on extending our basic library with event handling.

Out of the box event handling can be accessed  through Javascript and DOM apis, shown in the first 3 examples:

Simple event handling:

Assigning functions to events this way can be problematic, as only one function can be assigned at any given time. Mozilla Developer Network recommends that the addEventListener method be used instead, because of its flexibility.

Better Event handling

The addEventListener method accepts three parameters:

Assigning an anonymous function:

We can easily wrap this built in functionality with our library by creating a click function with a parameter that is passed to this native DOM event. This parameter will be an anonymous function (like the previous example) that will then bound to the element’s handler.

Handler wrapped by our library:

This pattern can be applied to any event natively exposed, such as:

  • onclick
  • onmouseover
  • blur
  • keydown

Non-standard or browser specific events

In the case where one browsers event api differs, it is simple to account for this in our event handler:

Optimizing our code

Instead of duplicating the addEventListener code in each event wrapper, we can optimize by creating an internal addListener(event, callback) function which will be called by other exposed functions, such as click, onMouseOver, etc

This separates the public wrapper from the internal event binding, allowing us to easily modify or expand the actual event binding code without modifying it in numerous places

 

Custom events system in JavaScript – LightEvents.js

Needing an event subscription and publishing system for a HTML5/canvas game I’m creating, I wrote a very light event system.

Anything than can call JavaScript (link, button, etc) can raise an event:

LightEvents.publishEvent('event name', data);

Subscribing to events is equally easy:

Here is the LightEvents object, demo is embedded below

JS Bin

Quick and reliable ad-rotator

In the course of my work, I’ve created and refined a simple ad rotator. It is built in JavaScript, and does not rely on any library, like jQuery, to function.  In my experience, it defeats ad-block, and loads easily on all mobile, tablet, and desktop browsers.

The rotator can be included multiple places on one page without any conflicts or collisions, so just drop-in where needed. Some coding is required to customize — basically copying and pasting your links and image urls, but nothing too heavy.

 

asp.net – getting user confirmation before a postback

In asp.net web applications, it is common to have dozens — if not hundreds — of user controls that perform postbacks to the server, actions initiated by a user such as a button click. Often before a save, delete, or other critical action is performed, it is desirable to ask the user if they are sure.

In Asp.net web applications, buttons and other controls have two event properties that we are concerned with: onClick , and onClientClick .

The onClick event calls a specified function in the code-behind file. At this point, the postback has occurred, and any confirmation would have to take place with another rendered page — meaning lots of wasted time and wasted resources.  With the onClientClick event, we can interrupt the onClick event with our own javascript function or inline statement.

Using jQuery, we can bind function to all of these “confirm-able” user controls, which will interrupt the default post-back behavior  presenting users with a confirmation dialog box:

Using this method, we can target all user controls with the CSS class confirm. Additionally, if we wanted a broader reach, we could modify the jQuery selector to  input[type=button] or for all buttons, or all links.

The confirm box  var response = confirm("Are you sure?"); used in this example is a default JavaScript confirmation dialog box — which will be rendered differently per browser or platform — but you could easily swap this for any other confirmation script or function that returns a boolean value.

Full-adders, 32-bit adders in JavaScript

Full-Adder circuit diagram
A Full-Adder, courtesy of the Wikimedia Commons

Fascinated by a lecture as part of my CS degree pursuits (there is light at the end of the tunnel!), I  decided to build some digital circuitry beginning with logic gates and ending with a full 32-bit adder. LIVE DEMO

So here’s my question: I’ve got a 32-bit adder… What now?

Beginning with basic AND, and OR functions, (&& and || operators are native to JavaScript), I built a simple XOR function — which is the first building block not built in to JavaScript:

I wanted each gate/function to work with simple Boolean values, as in JavaScript 1==True, 0==False can get a bit messy. For formatting reasons, I return each value + 0, so they results of higher order circuits are displayed numerically in   binary, rather than a series of True, False’s

After implementing, these foundational gates, I coded up a full adder:

 Within the returned object, “c” represents the carry, and “s” represents the sum. Information about how adders function can be found at this great Wikipedia article.

While there are more complex versions, a simple 4-bit adder is just 4 full-adders daisy chained together which each carry leading into the next adder. The final carry is returned from the 4-bit adder:

16, and 32 bit adders function in the same way: several smaller units daisy chained together, returning the final carry along with the sum:

The functions can be used like so:

So here’s where you come in: What do I do with a 32-bit adder, other than build a 64-bit adder?

Convert <address> tag to Google Maps embed automatically with jQuery

Converting an <address> tag into a Google maps link is something I’ve written about in the past, but user “Moose” was wondering if you can do the same thing, but transform it into an embedded map. Quick answer: Yes!

Using jQuery, we search the document for <address> tags,  create some HTML to embed the map with the current address inserted in it, then write that HTML out into the current spot.

Welcome to JS Bin

100% height using jQuery

2016 Edit: This post is really out-dated. If you are looking for a solution for 100% height divs, please use modern css as described here http://www.mikedoesweb.com/2016/modern-100-percent-height-css/

I few years ago, I wrote a post about forcing two divs to be equal height — quite a feat if you’ve ever tried!  Since then, a great jQuery plugin has came out that makes equal div height pretty easy to accomplish.

Using the plugin jQuery.equalHeight, it is as simple as:

Try out a live demo.

Of course, you should make your decision to use this method carefully. It’s quick and easy, but if your aren’t using jQuery already, is it worth the load time for this fix? If you want to check out a non-jQuery solution, check out this vanilla JavaScript solution.

JS Bin