Automating JS behavior registration

I created a behaviors javascript class to handle all my (prototype) Event observe registrations. Annotating DOM elements with the metadata needed to register itself automatically, which would save you from having to call Behavior.register(..).

The behavior class is defined in behavior.js (The idea of parsing the entire DOM came from a co-worker at revolutionhealth.com). This traversal maybe be expensive but if you had a ton of behaviors that register using CSS selectors, this might be faster (Don’t quote me on this though).

If you have a link, and wanted to provide an AJAX call without being obtrusive:


<a class="bvr-observe-click-xhrTheFunction" href="/the/href">The link</a>

The AJAX request:

1
2
3
4
5
6
function xhrTheFunction(event) {  
  var element = Event.element(event);
  var url = element.readAttribute("href");
  new Ajax.Updater("div_to_update", url, { });  
  Event.stop(event);
}

To create and apply the behavior, starting at id=”content”:

1
2
var dclBehavior = new Behavior();
dclBehavior.apply($('content'));

It will automatically register for the event observe. In other words it would do the following for you automatically:


 Event.observe(theLinkElement, "click", function(event) { xhrTheFunction(event) });

You could also handle other common tasks through bvr-* naming conventions. And you could also manually register your behaviors.

I am using this over at dclicio.us, in a couple places, if you want to see it in action.

Update:This is just a proof of concept (not entirely functional). The idea is to parse the DOM all in one shot so if you have a ton of behaviors, you don’t have to deal with alot of selector rules.
You could add other naming conventions, probably make them less verbose, change it to do binding, etc. Its definately not a good solution if you are only observing clicks :)

Tags: ,

Comments are closed.