Martin Ström
my-domain.se

Quicker way to observe events in prototype.js

Here’s a shorter way to listen for events in prototype.js.


Copy Paste Character

Two weeks ago we (me and Konst & Teknik) launched copypastecharacter.com—a site to make it dead easy to copy those special characters which otherwise can be hard to find. We just pushed an update and I realized I hadn’t mentioned it here.

The character you click will automatically get copied into your clipboard, thanks to the flash technique mentioned here. However, I wrote my own JavaScript class to handle the clipboard and the buffer of clicked characters since you can hold down ‹alt› to copy multiple characters at once.

Here’s the source for the copy buffer class in case anyone’s interested:


Multi-dimensional array sorter

The other day when working on some small updates on konst-teknik.se I wanted to sort the projects in a multi dimensional way, and take the other factors than the first into account. JavaScript’s Array#sort only supports one dimensional sorting so I wrapped my own sorter.

The results turned up pretty good (at least compared to the first test), or perhaps I just like recursing functions.



var sortOrder = {
  'cat-no': ['cat-no', 'name', 'type', 'year'],
  'name':   ['name',   'type', 'year', 'cat_no'],
  'year':   ['year',   'name', 'type', 'cat_no'],
  'type':   ['type',   'name', 'year', 'cat_no']
};

function sort(order) {
  var ordering = sortOrder[order], length = ordering.length;
  $$('#projects > li').sort(function(left, right) {
    left = Project.find(left), right = Project.find(right);
    return (function(index) {
      var a = left.getSortValue(ordering[index]),
          b = right.getSortValue(ordering[index]);
      return a < b ? -1 : a > b ? 1 :
        index < length ? arguments.callee(++index) : 0;
    })(0);
  }).each(function(project) {
    project.parentNode.appendChild(project);
  });
}


Ajax.CachedRequest

Recently I wanted to cache the results (responseText) from a lot of Ajax.Requests since the returning data would not change and made the roundtrip to the server unnecessary. Maybe there are others out there interested so here’s the code. It’s not very well tested except the project where it is in use so there might be some bugs or tweaks needed.


Ajax.CachedRequest = Class.create(Ajax.Request, {
  initialize: function($super, url, options) {
    options = options || {};
    var onSuccess = options.onSuccess || Prototype.K;
    if (!Ajax.CachedRequest.cache[url] || options.reload) {
      options.onSuccess = function(transport) {
        Ajax.CachedRequest.cache[url] = transport.responseText;
        onSuccess(transport);
      }
      $super(url, options);
    } else {
      eval(Ajax.CachedRequest.cache[url]);
      this.dispatch.defer();
      [onSuccess, options.onComplete].each(function(m) { m && m() });
    }
  },

  dispatch: function() {
    Ajax.Responders.dispatch('onComplete', null);
  }
});

Ajax.CachedRequest.cache = {};

Of course this assumes you’re using the brand new Prototype 1.6


Prototype & Script.aculo.us SVN checkins RSS feed

Thanks to Yahoo Pipes I created two RSS feeds for the Ruby on Rails checkins (changesets). One containing only the Rails-spinoffs checkins (that is Prototype and Script.aculo.us right now) and another without the spinoffs. This way I can follow the JavaScript-related changes as they happen but watch the Ruby-stuff every now and then.


What's new in Prototype svn?

Just after posting this I saw that sam tagged the 1.5.1 release in svn so I guess this means that 1.5.1 is final. Great work!

There has been a lot of action the past days in the Prototype SVN; the release of 1.5.1 RC4, the new DOM and Position branches and a lot of other work. Since I watch most of the tickets and changesets I thought I write something about what’s (might be) in the future for Prototype.

DOM branch

I was happy to see a patch I’ve been working on (#7476) to get included some days ago. It will define a new Element#writeAttribute method which will work together as the already existing #readAttribute to work around many issues browsers having with the native set/getAttribute methods (as always mostly in IE) but also to make chaining work:

$('my_image').writeAttribute('src', 'new-image.png').show();

The method will also accept a hash for the attributes to let you set multiple attributes at once:

$('my_image').writeAttribute({src: 'new-image.png', custom_attr: 'foo'}).show();

The patch will also make the Element object into a constructor for very easy and fast element creation (i.e. document.createElement wrapper):

var header = new Element('h1');

The constructor will also accept an optional attributes hash for the attributes (as seen above in the #writeAttribute method):

var header = new Element('h1', {id: 'myHeader'});

Of course chaining will work so for a simple image switcher with preloading you could do this:

<!-- html -->
<img src="thumbnail.jpg" id="thumbnail" hires="big.jpg">

// javascript
$('thumbnail').observe('click', function(event) {
    var thumb = Event.element(event),
      preloader = new Element('img', {src: thumb.readAttribute('hires')});
    preloader.observe('load', function(event) {
        thumb.writeAttribute('src', preloader.readAttribute('src'));
    });
});

Event Branch

I haven’t followed the event branch very closely but from the code and messages on the ML I’ve seen there should be new functionality for better garbage collection (to prevent memory leaks) and for e.g. easier removal of observers from elements.

Where you before had to manually collect all an element’s event listeners to be able to remove them later:

var listener1 = function(event) {...}.bindAsEventListener();
var listener2 = function(event) {...}.bindAsEventListener();

// start listening
$('myElement').observe('click', listener1);
$('myElement').observe('click', listener2);

// stop listening
$('myElement').stopObserving('click', listener1);
$('myElement').stopObserving('click', listener2);

you will now be able to remove all event listener for a specfic event:

$('myElement').stopObserving('click'); // or Event.stopObserving('myElement', 'click');

Other

Some other new additions worth mentioning are:

But to not make this post too long you’ll have to read about it on your own (check the source and/or the changesets manually).

Please notice that all these are subject to change since it’s under development right now and might never get into any future release of Prototype.


One animated background image for multiple elements in Safari

I’ve found out that Safari can’t handle the same animated gif as background for multiple elements, it will just animate one of them at the same time. On a project I’m currently working on my I use the following trick to make all requests to the background image (in this case indicator_black.gif) unique.

[...]
var text = transport.responseText;
if (Browser.WebKit) {
    text = text.gsub('indicator_black.gif', function(match) {
        return match + '?' + new Date().valueOf() +
          Math.round(Math.random() * 5000);
    });
}
[...]

Note that it uses Prototype JavaScript framework and you should too.

Update:

This is fixed in WebKit nightly (and therefore Safari 3 but I haven’t tested yet).

Rails' time extensions ported to JavaScript

I’ve ported Rails’ Numeric Time extensions to JavaScript since I needed to do some date calculations for a project I’m working on. Now one should be able to calculate dates in JS like this:

(5).seconds() // => 5000
(2).weeks() + (2).hours() + (15).seconds() // => 1216815000
(1).week().fromNow().toDate() // => Fri Sep 22 2006 19:16:32 GMT+0200 (CEST)
var date = new Date(2000, 11, 18, 18, 15, 23);
(2).years().since(date).toDate() // => Thu Dec 19 2002 06:15:23 GMT+0100 (CET)

Thought it could be useful for others as well. You’ll need the latest prototype library, unit tests are included.

Download a zip with both .js file and unit tests or just the .js-file.


TextMate Prototype & Scriptaculous Bundle

This the first version of a TextMate bundle for Prototype and script.aculo.us JavaScript libraries. The language grammar is based on from Justin Palmers Prototype Bundle but the other commands/snippets are all new. Please let me know if you have any comments and/or improvements.

Download here

Update 2006-07-16

The bundle is now added to TextMates official svn repository.

CSS is in progress