[OpenLayers-Dev] A generic button class:

Jeff Dege jdege at korterra.com
Fri Jul 27 17:49:22 EDT 2007


The OpenLayers source is collecting a useful bunch of controls, but most
of them are designed to do something specific.

What I've found is a need for generic buttons - click on them, and they
do something.  But what they do is different, and specific to the
particular application.  I've been adding them to a Panel control,
alongside Navigation, Zoombox, etc.  But building a distinct class
seemed like overkill, and taking advantage of Javascripts ability to
extend an object at runtime struck me as a nightmare for future
maintainers.

So I built a very simple little control:

/**
 * @class
 * 
 */
GenericButton = OpenLayers.Class.create();
GenericButton.prototype = 
  OpenLayers.Class.inherit( OpenLayers.Control, {
    onClick: null,
    type: OpenLayers.Control.TYPE_BUTTON,
	
    trigger: function() {
      if (this.onClick)
        this.onClick();
    },
    /**
    * @param {Event} evt
    */
    /** @final @type String */
    CLASS_NAME: "OpenLayers.Class.GenericButton"
});


Usage is simple:

  var nav = new OpenLayers.Control.Navigation();
  var panel = new OpenLayers.Control.Panel({defaultControl: nav});
  panel.addControls([nav,
    new OpenLayers.Class.GenericButton(
      {'displayClass': 'MyGenericButton', 'onClick': myFunction});
  ]);

  openLayersMap.addControl(panel);

The 'displayClass' option is what is used in building the className,
which you'd used in the css to set the background image, etc.  In this
case, it'd be .MyGenericButtonItemInactive.  (These buttons never become
active, so there's no need for .MyGenericButtonItemActive.  The
'onClick' function is a javascript function that's called when the
button is clicked.

It's pretty simple stuff, and I'm sure everyone has their own ways of
handling this problem.  But I thought I'd throw out mine.




More information about the Dev mailing list