Prototype extensions

Prototype may be ubiquitous, but there’s some functionality it has yet to cover. Here are a couple of useful extensions I’ve run across lately to fill in the gaps:

Cookie, by Carlos Reche

JavaScript already does a pretty good job of getting and setting cookie values on its own, but this extension makes it trivial. The simple Cookie object gives you access to get(), set(), erase(), and accept() methods.

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)s*' + escape(name) + '=([^;s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

Event.wheel(e), by Frank Monnerjahn

This tiny extension (about a dozen lines) adds support for mouse wheel events—handy for any number of things, like manipulating a gauge or slider, or scrolling something sideways. Frank based this code on an example by Adomas Paltanavičius.

Object.extend(Event, {
  wheel:function (event) {
    var delta = 0;
    if (!event) {
      event = window.event;
    }
    if (event.wheelDelta) {
      delta = event.wheelDelta/120;
      if (window.opera) {
        delta = -delta;
      }
    } else if (event.detail) {
      delta = -event.detail/3;
    }
    return Math.round(delta); //Safari Round
  }
});

And a usage example:

Event.observe(document, 'mousewheel', yourCallbackFunction, false);
Event.observe(document, 'DOMMouseScroll', yourCallbackFunction, false); // Firefox
Like this post? You might also like Coalmine, my centralized error tracking service for your apps. Coalmine captures errors and all kinds of helpful debugging information, notifies you, and makes it all searchable. Check it out!

Tags: , ,

Leave a comment