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() {
        // just gotta change what's returned here
        return AjaxLoggerAdapter;
    },
    ...
};

Source

Here the method for getLogger is overwritten to adapt the AjaxLoggerAdapter so that it uses the sendLog method of the object AjaxLogger. This allows us to externalize a function of an object to consume other implementations.

 
12
Kudos
 
12
Kudos

Now read this

Pricelinelabs: omni-slider

This blog is about my experience building and being the author of the first open source project under Pricelinelabs. The omni-slider is a multi-range vanilla javascript slider widget component released on the open source world in GitHub... Continue →