Image

multiple behaviors on event handlers

For the curious, here's why I'd like to know how to delete properties. (See my last post.) I'm adding the ability to dynamically add and remove "behaviors" on event handlers. Below is the best way I've come up with, and it works pretty well. If anyone has a better way of accomplishing this, please share.


What it does is this. To add a behavior to some object's event handler, you pass to the daza_add_behavior function four things: (1) the object whose handler to modify, (2) the name of the event, (3) the name of the behavior you're defining, and (4) the function that is the behavior.

The function you pass gets stored in an array, and (if it hasn't been done already) the event handler gets set to a new function which steps through that array of behavior functions.

The part of this that relates to my last post is that after adding and removing several bahaviors, the behavior arrays get bloated with a bunch of empty properties. It shouldn't be a terrible problem, since I don't foresee needing to add and remove hundreds of unique behaviors, but it's one of those little problems that nags.


<html>
<head>
   <title>Behaviors</title>
   <script type="text/javascript">
<!--

onerror = function(e,u,l)
{
   alert(e+','+u+','+l);
}

function daza_add_behavior(obj,event,name,func)
{
   /*
    *   Javascript Event Behaviors
    *   Copyright 2003 Thomas Peri
    *   
    *   Re-use and modify as you like, but keep this credit intact.
    */
   
   var behaviors = event+'_behaviors';
   /* If absent, add the array of behaviors for this event,
      and set the event handler to step through the array. */
   if (!obj[behaviors])
   {
      obj[behaviors] = new Object();
      obj[event] = function()
      {
         for (var i in obj[behaviors])
            if (typeof(obj[behaviors][i])=='function')
               obj[behaviors][i](obj,arguments);
      }
      /* allow removal of behaviors */
      obj[event+'_remove'] = function(name)
      {
         obj[behaviors][name] = null;
      }
   }
   obj[behaviors][name] = func;
}

function example()
{
   /* grab the element */
   var eg = document.getElementById("eg");
   
   /* pick a random color on click */
   daza_add_behavior(eg,'onclick','rand_color',
      function(self,args)
      {
         var colors = new String('red orange yellow green blue purple').split(' ');
         self.style.background=colors[Math.floor(Math.random()*colors.length)];
      }
   );
   
   /* also, size the square randomly on click */
   daza_add_behavior(eg,'onclick','rand_size',
      function(self,args)
      {
         var size = (Math.floor(Math.random()*100)+100)+'px';
         self.style.width = self.style.height = size;
      }
   );
}

// -->
   </script>
</head>
<body onload="example();">
<div id="eg" style="width:100px; height:100px; background:blue;"></div>
</body>
</html>