Chris Ng

Senior Staff Software Engineer at LinkedIn | Ember Learning Core Team | Speaker

Page 4


Event Propagation and Event Delegation

This is a key part of JavaScript functionality outlined in the W3C Document Object Model (DOM) Level 2 Events Specification.

Event Propagation

This flow occurs when an event takes place such as a click, hover, or mousedown. The function is then triggered on each part of each stage of each flow. That was a mouthful. But think of it this way, starting from the topmost to the bottom and back from the bottom to the top (3 -> 2 -> 1 -> 1 -> 2 -> 3). Event capturing first then event bubbling.

<div onclick="foo(this)">3
   <div onclick="foo(this)">2
      <div onclick="foo(this)">1</div>
   </div>
</div>

So each capture down and each bubble up would trigger an onclick and the resulting function foo(this) if the inner most div (with innerText = “1”) was clicked. The scope of this will then change depending on when it was called since this is not assigned a value until the function has been...

Continue reading →


Dojo IE8 Defect: ‘bases’ is null or not an object

This is a Dojo defect where we get the error “‘bases’ is null or not an object” when trying to do a cross iframe call even if the iframes are from the same domain.

From my case, it was two iframes from the same domain with the child calling its parent’s method. It’s pretty well summarized by the thread reply below.

From the Dojo Toolkit mailing list archive at Nabble.com:

I get this error in IE8 (haven’t tried IE7).
I don’t get this error in Firefox, IE9 (IE9 mode or even in IE8 mode) and
Chrome.

Download the 2 html files attached and place them next to each other.
One basically is the iframe src of the other.

http://dojo-toolkit.33424.n3.nabble.com/file/n2752028/test.html test.html
http://dojo-toolkit.33424.n3.nabble.com/file/n2752028/test1.html test1.html

Press the button to show the dialog.
It will fail in IE8 with the above error.
Workaround is to create the options object in...

Continue reading →


IE console.table Functionality

This is a way to enable IE browsers to use the console.table functionality that is given in modern web browsers such as Firefox and Chrome.

This allows us to view data in a table layout, takes an object as an input. There is also an optional ‘columns’ parameter which takes the form of an array of strings similar to the Chrome console.table.

From the example given by Google:

function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
}

var family = {};
family.mother = new Person("Susan", "Doyle", 32);
family.father = new Person("John", "Doyle", 33);
family.daughter = new Person("Lily", "Doyle", 5);
family.son = new Person("Mike", "Doyle", 8);

console.ietable(family, ["firstName", "lastName", "age"]);

We get:

index | firstName | lastName | age
mother | Susan | Doyle | 32
father | John | Doyle | 33
daughter | Lily | Doyle |
...

Continue reading →


Spirally Traversing a Two-Dimensional Array in JavaScript

This is a way to traverse a two-dimensional array (or a matrix) from the top left, spirally in a clockwise manner in JavaScript.

This solution is inspired by functional programming and it uses tail recursion.

Steps:

  • When you start with your matrix, you take the top part off and append it to result.
  • Then you transpose the remaining matrix after taking the top off
  • After that reverse the transposed matrix so that when you take the top off, again in step 1, you actually take the bottom half off (since we’re traversing spirally)
  • Run the transposed reversed remaining matrix through the function again
  • Repeat until you hit the base case and just append the trivial element matrix to result
-= Start =-
            [[1,2,3],       undefined
             [4,5,6],
             [7,8,9]]

Take the top off
            [[4,5,6],       "1,2,3"
             [7,8,9]]

Transpose the remaining
...

Continue reading →


Enhancing JavaScript Arrays: Good or Bad?

This is a way to give JavaScript Arrays some extra functionality to make life easier for development and in turn lead to clear and concise code.

I’ve mentioned some ways to give backwards compatibility functionality (otherwise known as Polyfilling) to the Array object in browsers such as IE8. This is generally considered good and proper. Even the Mozzila MDN advocates for it.

Here are a couple of ways to extend the native JavaScript Object Array with other functions to simplify interactions with an array of objects.

JavaScript

// Checks if the array contains the element e under the property in an array of objects
Array.prototype.has = function(e, property) {
  for (var i=0; i < this.length; i++){
    if (this[i][property] == e) return true;
  }
  return false;
}

// Retrieves the maximum value nested inside an object in an array of objects
Array.prototype.max = function (property) {
...

Continue reading →


LRU Cache in JavaScript

This is an LRU (least recently used) cache implementation in JavaScript.

It’s very efficient and uses two data structures to manage the elements. A doubly-linked list and a map gives us the following:

  • Time complexity: O(1)
  • Space complexity: O(n)

This is achieved by having the doubly-linked list manage when we have to rearrange the elements while the map gives us direct access to the resource. Look-up in a map is O(1) by providing the key. We introduce the concept of the “head”, which is the least recently used entry, and the “tail”, which is the most recently used entry, to keep track of the order when elements are retrieved or added. There are two pointers per node which is relatively low cost to manage the ordering.

API:

  • lru(limit)
    • Initialize LRU cache with default limit being 10 items
  • get(key)
    • Retrieve a single entry from the cache
  • set(key, value)
    • Change or add a...

Continue reading →


Understanding “this”

You often hear it down the hall or across the room. “JavaScript sucks, I don’t understand why I can’t reference my object”. The use of “this” in JavaScript is notorious for confusing JavaScript developers.

We are assuming here that strict mode is not turned on. If strict mode is turned on then this is undefined in global functions and in anonymous functions that are not bound to any objects.

All functions in JavaScript have properties, much like objects in languages such as Java. When a function is executed, it obtains the property this. The property this is not an assigned value until the function has been invoked. Then this will have the methods and properties of the object that invokes the function. Confused yet? Here’s an example to illustrate what I just wrote. Look at the example below and reread the paragraph, it should make sense now.

Simple Example

var duck = {
    noise :
...

Continue reading →


Lyft Programming Challenge

The Lyft programming challenge is an optional part of the job application to be a Software Engineer at Lyft.

This is copy pasted from the job posting:

Calculate the detour distance between two different rides. Given four latitude / longitude pairs, where driver one is traveling from point A to point B and driver two is traveling from point C to point D, write a function (in your language of choice) to calculate the shorter of the detour distances the drivers would need to take to pick-up and drop-off the other driver.

Broken down we have:

  • There are two different trips
  • Consisting of four points (A to B and C to D)
  • Calculate which one is shorter ACDB or CABD

Using the Haversine formula, we can obtain the distance of the trip or from two different points in a plot.

JavaScript

// Config should be taken from an input
var metric = true;
var Radius; // Radius of the Earth
if (metric
...

Continue reading →


Get the nested object in an object literal

This is a way in JavaScript to get a deeply nested object in an object literal. This is especially useful when we are unsure about the data we are receiving. This allows our code to be able to handle one or more instances of data received. So if the optional data is in the object literal, then we can use it if not it won’t break the code nor will it add unnecessary try-catch blocks or if-else clauses to the codebase.

var test = { first:{second:{third:'found it!'}} };

Object.prototype.get = function(path) {
    var arr = path.split('.');
    var obj = this;
    for(var i = 0; i < arr.length; i++) {
        var e = arr[i];
        if(obj[e] === undefined) {
            obj[e] = {};
        }
        obj = obj[e];
    }
    return obj;
}

test.get('first.second.third') == 'found it!'; // true

We are able to use the method get in any object literal as we added it to Object’s prototype...

Continue reading →


Adapter Pattern in JavaScript

The adapter pattern is a concept where two incompatible interfaces are made to work together using the adapter. The adapter is useful for when changing frameworks in large complex projects. Say you started development using Backbone however after management makes an executive decision your team now has to align to the company’s standards which might be Dojo or Ember. This requires massive code change to switch all the Backbone code into Ember. This obviously is not a smart decision so using an adapter, while painful to do, is still better than the former option.

To implement an adapter interface we simply need to return a function or a set of functions that changes the current interface when consumed.

var AjaxLoggerAdapter = {
    log: function(arg) {
        AjaxLogger.sendLog(arg);
    }
};

/* Adjust the LoggerFactory */
var LoggerFactory = {
    getLogger: function() {
        //
...

Continue reading →