« Versionshelf has landed |  main  | I've had it with iChat video chat... »

Applying Behaviour without Behaviour.js

Posted by dom on Thu Sep 14 19:01:34 +0200 2006

In June 2005 Ben Nolan made my web-development live more joyful by releasing behaviour.js – a little javascript library that helps you keep your HTML clean. With behaviour.js you add all the javascript behaviour and magic after the page is loaded via CSS selectors.

So, instead of adding the onclick=”something()” attribute directly to the HTML you can put clean images into your HTML with classes like “removehandle” and apply this behaviour:

var often = {

    '.removehandle' : function(el) {
        el.onclick = function() {
            Element.remove(this.parentNode.parentNode)

            return false;
        }
    },
    
    '.optionlist_removeitem' : function (el) {
        el.onclick = function() {
            Element.remove(this.parentNode)

            return false;
        }
    }
}

Very nice. But what is even nicer is, that the current prototype version 1.5.0_rc0 features the $$() function which can do exactly the same in combination with the each() method. Interstingly enough, the easiest way to get your hands on this prototype version is the rails repository .

function applyRemoveBehaviour() = {
    $$('.removehandle').each(function(el) {
        el.onclick = function() {
            Element.remove(this.parentNode.parentNode)

            return false
        }
    })
    $$('.optionlist_removeitem').each(function (el) {
        el.onclick = function() {
            Element.remove(this.parentNode)

            return false
        }
    })
}

3 responses to 'Applying Behaviour without Behaviour.js'

  1. Interesting. Tried this myself yesterday, to avoid including behaviour.js (was using prototype already). However, with both rc0 and the latest svn, it doesn’t seem viable at this time (at least for me):

    1) IE 6 produces weird JS errors

    2) the thing is dead-slow, takes on the order of a second for a single assignment.

    Let’s hope they iron this out. For me, it’s back to behaviour.js.

  2. Interesting. For me this worked great with IE – but I only had simple css selectors, nothing fancy. Reminder to self: look at the code of both and comment on the differences.

  3. yeah, very simple stuff here, too. Got the impression that it wasn’t a problem with the selectors, but with the content of the page. After all, I assume that $$(...) has to perform some sort of search on the DOM.

    In terms of slowless, this could also at least partially be because I had to throw in some try {} catch {} block to stop IE from crapping out.

write a comment.... (textile enabled)
author
email
url
Body