Prototype Behaviors

by Brian R. Miedlar.   Last updated on 8/23/2007.

This article shows how to separate the javascript behaviour layer from both your client-side model and presentation layer.

Utilizing the Prototype 1.6 Css Selectors for Behaviour Loading

Because prototype 1.6 has improved css selector support there is no longer a need for the Sebastian's Behaviour.js library. The behaviours can be registered to a queue and applied once the dom has been loaded.

var OS = Class.create(); OS.PageLoading = true; OS.PageLoadComplete = function() { OS.PageLoading = false; $A(OS.BehaviourQueue).each(function(selectors) { OS.ApplyBehaviour(selectors); }); OS.BehaviourQueue = []; }; Event.observe(document, 'dom:loaded', function() { OS.PageLoadComplete(); }); OS.BehaviourQueue = []; OS.RegisterBehaviour = function(selectors) { if(!OS.PageLoading) { OS.ApplyBehaviour(selectors); return; } OS.BehaviourQueue.push(selectors); } OS.ApplyBehaviour = function(selectors) { $H(selectors).each(function(item) { var sKey = item.key; $$(sKey).each(function(element) { item.value(element); }); }); };

Using this methodology we can load the behaviours in the same way as done in Sebastian's behaviour.js script

SomeClass.SomeBehaviour = { '#SomeElementId .someClass': function(element) { //code to inject behaviour to the element }, '#AnotherElementId .someClass.withClass': function(element) { //code to inject behaviour to the element } } OS.RegisterBehaviour(SomeClass.SomeBehaviour);

Comments

Nickname:
Message: