Monday, January 12, 2015

A Poor Man's jQuery

Ok, so jQuery isn't exactly expensive - in fact it's free and open source.

But browser's have become more standardized,. New frameworks that don't depend on jQuery - polymer, angularjs, phaser.io - are becoming more common. I find that I seldom need to install jQuery these days.

But I find myself missing the $('something') syntax. Instead, I'm typing document.querySelector all over the place:

document.querySelector('paper-tabs').addEventListener('core-select', function() {
  document.querySelector('core-pages').selected = document.querySelector('paper-tabs').selected;
});

This is much clearer:

$('paper-tabs').addEventListener('core-select', function() {
  $('core-pages').selected = $('paper-tabs').selected;
});


It seems overkill to install jQuery just to get the querySelector shortcut. But I can't just say:

var $ = document.querySelector;

I will get an error that the null object doesn't have a method named 'querySelector'.  This simple assignment in effect unbinds the method from it's 'this' reference. Instead we need to do this:

var $ = document.querySelector.bind(document)

Now, the 'this' reference still points to document, so that this will work:

(function($){

  $('paper-tabs').addEventListener('core-select', function() {
    $('core-pages').selected = $('paper-tabs').selected;
  });

})(document.querySelector.bind(document));

No comments:

Post a Comment