Using MutationObserver API and undo.js to track DOM changes

I was recently working on this project that had a kind of drag and drop builder. Users should be able to drag items into a specific building area to assembly stuff — I’m sorry for not giving more details, by the time I’m writing this the product is not yet released. One of the features I had to implement was a pair of buttons to undo and redo actions.

Every time an item is added to the builder, a DOM change happens. So, I started to look for ways to track changes in the DOM. That’s when I found about MutationObserver API. That web API is implemented by most of the modern browsers, Internet Explorer 11+ included, and allows you to observe DOM changes using a simple approach. The second tool that helped me build this was undo.js. It’s a simple Javascript class that allows developers to implement actions tracking in an exceptionally easy way.

After coding this feature, it seemed to me that combination of tools might be useful for a lot of other use cases. So I wrote this fiddle to demonstrate how they can be used together:

If you have any question, the comments area below is all yours.


Using make to build a NodeJS app

Do you know you can use the good ol’ make to build your NodeJS app? I wrote a little about it in my latest post on Kettle’s Blog:

Passing Node args to Mocha tests

This is a really quick tip. I was looking around on the internet for a way to pass Node arguments when calling Mocha binary. And I couldn’t find anything useful. Then I tried the following and it worked:

$ test node --expose-gc ./node_modules/.bin/mocha [...]

The --expose-gc argument is just an example. You can pass any argument accepted by Node program.

In my specific case, I was trying to load dotenv config. In the end, the project’s MakeFile looked like:

    @NODE_ENV=test node -r dotenv/config ./node_modules/.bin/mocha \
        --require should \
        --reporter spec \
        --harmony \
        --bail \

.PHONY: test

Photo credit: Matt Benson

Mixing HTTP and WebSocket routes in a Koa-based application

I’ve started to use the koa-websocket package. And it took me some time to figure out how to mix HTTP and WebSocket routes in a single Koa-based application. I’m not sure if this solution is obvious, but I’m sharing it anyway.

First of all, we’ll need two separate routers for regular HTTP and WebSocket routes:

// Creating a Koa app instance.
const app = require('koa')();
// "Websockifying" the application.
const socket = (require('koa-websocket'))(app);
// Loading router package
const router = require('koa-router');

// Here they are, our 2 routers
const http = router();
const ws = router();

Then, we can write our routes, plugging them to the specific router:

http.get('/', function *(next) {
    this.status = 200;
    this.body = 'Hello!';

ws.get('/socket', function *(next) {
    this.websocket.on('message', function (message) {

Finally, let’s make the app use the routers we created:


Notice that the second router was added to instead of app directly.

And… That’s it.

Photo credit: Aron Van de Pol

Simple Gallery now as a jQuery plugin

One year ago I wrote a very simple image gallery script, based on jQuery. Now I updated it and completely rewrote it as a jQuery plugin. The code is available on GitHub:

Photo credit: Jessica Ruscello

Simple Gallery — Uma simples galeria baseada em jQuery

Na maioria dos projetos que desenvolvemos na CodeKings, acabamos não conseguindo usar as opções de galerias disponíveis na web. Isso acontece porque a estrutura do plugin não é compatível com o layout ou faz muito mais coisas do que realmente precisamos. Nesses casos, acabamos escrevendo um script simples que resolve mais rapidamente do que se tivermos que adaptar alguma solução pronta. Com o tempo, percebi que esse script não mudava muito de um projeto para outro, então resolvi escrever uma versão genérica que é bem simples de customizar.

Publiquei o projeto no GitHub:

Funções úteis em JS para extrair dados de URLs

Existem bibliotecas bem legais para extrair dados da URL, mas às vezes você não precisa de todas aquelas informações. Para evitar que seu código fique inchado ou a importação de bibliotecas completas, pode ser interessante usar funções específicas que retornam apenas o dados que você precisa. Tem duas delas que uso com bastante frequencia:


function getHash(url)
  if (typeof url != 'string')
    return null;
  return url.replace(/^.*(#.*)$/, '$1');

Parâmetro (GET)

function getParam(url, param)
  if (typeof url != 'string' || typeof param != 'string')
  var regex = new RegExp('[\\?&]' + param + '=' + '(.+?)([&#]|$)', 'i');
  return (value = (regex.exec(window.location.href)||[,null])[1]) 
      ? decodeURIComponent(value) 
      : null;