Scrollbars & Code structure - Actionscript 3.0

So this thread actually began from another thread, I am just moving it over here… I got asked to write a tutorial about this, is anyone else interested?

The purpose of this thread is more about the code design then it is about the functionality although this is a very practical and very usable solution.
**
Scrooooooooooollbars**

A scrollbar isn’t nearly as much as people assume it to be. In fact a scrollbar can be broken down into a composite of a few simpler components.

The approach here is to make this as abstract as possible. First thoughts should be focusing on what a scrollbar is and what a scrollbar isn’t. This is important because it relates directly to the complexity of our design. If we couple together a scrollbar with content we have to design specifically for that. Instead we need to assume less.

Scrollbars and Sliders

At the core of just about every scrollbar is the slider. A slider can be described as a track and a marker. The marker can be dragged along the length of the track where it’s position along the track is the visual representation of some percentage that we can read and write.

To promote a more flexible design we will be decoupling the way in which anything becomes aware of the scrollbar. Instead of the scrollbar modifying an object based on it’s percentage we will instead notify objects that the scrollbar has changed, providing them with the new percentage.

At this point we are discussing two agents in the design, a slider (which is itself a component that can be used 100% independently of the scrollbar ), and the event which our slider will broadcast.

These can be defined programatically as Slider and SliderEvent with the following classes:

** Slider
**


package
{
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.geom.Rectangle;

    /**
     * Represents the base functionality for Sliders.
     * 
     * Broadcasts 1 event:
     * -SliderEvent.CHANGE
     */
    public class Slider extends Sprite
    {
        // elements
        protected var track:Sprite;
        protected var marker:Sprite;
        
        // percentage
        protected var percentage:Number = 0;
        /**
         * The percent is represented as a value between 0 and 1.
         */
        public function get percent():Number { return percentage; }
        /**
         * The percent is represented as a value between 0 and 1.
         */
        public function set percent( p:Number ):void
        {
            percentage = Math.min( 1, Math.max( 0, p ) );
            marker.y = percentage * (track.height - marker.height);
                        
            dispatchEvent( new SliderEvent( SliderEvent.CHANGE, percentage ) );
        }
        
        /**
         * Constructor
         */
        public function Slider()
        {
            createElements();
        }
        
        // ends the sliding session
        protected function stopSliding( e:MouseEvent ):void
        {
            marker.stopDrag();
            stage.removeEventListener( MouseEvent.MOUSE_MOVE, updatePercent );
            stage.removeEventListener( MouseEvent.MOUSE_UP, stopSliding );
        }        
        // updates the data to reflect the visuals
        protected function updatePercent( e:MouseEvent ):void
        {
            e.updateAfterEvent();
            percentage = marker.y / (track.height - marker.height);
            
            dispatchEvent( new SliderEvent( SliderEvent.CHANGE, percentage ) );
        }
                
        //  Executed when the marker is pressed by the user.
        protected function markerPress( e:MouseEvent ):void
        {
            marker.startDrag( false, new Rectangle( 0, 0, 0, track.height - marker.height ) );
            stage.addEventListener( MouseEvent.MOUSE_MOVE, updatePercent );
            stage.addEventListener( MouseEvent.MOUSE_UP, stopSliding );
        } 
        
        /**
         * Creates and initializes the marker/track elements.
         */
        protected function createElements():void
        {
            track = new Sprite();
            marker = new Sprite();
            
            track.graphics.beginFill( 0xCCCCCC, 1 );
            track.graphics.drawRect(0, 0, 10, 100);
            track.graphics.endFill();
            
            marker.graphics.beginFill( 0x333333, 1 );
            marker.graphics.drawRect(0, 0, 10, 15);
            marker.graphics.endFill();
            
            marker.addEventListener( MouseEvent.MOUSE_DOWN, markerPress );
            
            addChild( track );
            addChild( marker );
        }
    }
}

SliderEvent


package
{
    import flash.events.Event;

    public class SliderEvent extends Event
    {
        // events
        public static const CHANGE:String = "change";
        
        protected var percentage:Number;
        /**
         * Read-Only
         */
        public function get percent():Number
        {
            return percentage;
        }
        
        /**
         * Constructor
         */
        public function SliderEvent( type:String, percent:Number )
        {
            super( type );
            percentage = percent;
        }
    }
}

This code should be failry intuitive and require very little explanation if at all, so if there is something that is not understood, please ask and I will explain it.

Scrollbars

Since scrollbars are a composite of simpler components, the definition of a scrollbar is going to simply manage these components. We will talk about this design before showing the code.

Think about what differentiates a scrollbar and a slider (minus the context within which they operate). In data scrollbars and sliders represent the same thing, some percentage. The difference is the means in which the percentage can be modified.

A slider has a marker and a track, where the marker’s position is the ‘visual’ representation of the slider’s percentage. This marker can be dragged, allowing the user to modify the percentage.

A scrollbar is everything that a slider is in addition to allowing the user to press ‘arrows’ that increment/decrement the percentage by some predefined or calculated amount. You can remember in the design of the slider we allowed ourselves a means of modifying a sliders percentage programatically. This flexibility is what will allow us to implement the scrollbar.

Since what the scrollbar and slider represent in data are the same thing, we can use the same means of notifying a listener about changes in data. So our scrollbar class will be used merely to encapsulate the composition of the arrows and track. Remember that the way in which we notify the objects is the same, as a note instead of re-broadcasting the events we will simply register listeners for the Slider directly.

A simple implementation of the Scrollbar follows.

** Scrollbar**


package
{
    import flash.display.Sprite;
    import flash.events.MouseEvent;

    public class Scrollbar extends Sprite
    {
        // elements
        protected var slider:Slider;
        protected var up_arrow:Sprite;
        protected var down_arrow:Sprite;
        
        protected var scrollSpeed:Number = .1;
        
        // read/write percentage value relates directly to the slider
        public function get percent():Number { return slider.percent; }
        public function set percent( p:Number ):void { slider.percent = p; }
        
        /**
         * Constructor
         */
        public function Scrollbar()
        {
            createElements();
        }
        
        // executes when the up arrow is pressed
        protected function arrowPressed( e:MouseEvent ):void
        {
            var dir:int = (e.target == up_arrow) ? -1 : 1;
            slider.percent += dir * scrollSpeed;
        }
        
        /**
         * Create and initialize the slider and arrow elements.
         */
        protected function createElements():void
        {
            slider = new Slider();
            
            up_arrow = new Sprite();
            up_arrow.graphics.beginFill( 0x666666, 1 );
            up_arrow.graphics.drawRect( 0, 0, 10, 10 );
            up_arrow.graphics.endFill();
            
            down_arrow = new Sprite();
            down_arrow.graphics.beginFill( 0x666666, 1 );
            down_arrow.graphics.drawRect( 0, 0, 10, 10 );
            down_arrow.graphics.endFill();
            
            slider.y = up_arrow.height;
            down_arrow.y = slider.y + slider.height;
            
            up_arrow.addEventListener( MouseEvent.MOUSE_DOWN, arrowPressed );
            down_arrow.addEventListener( MouseEvent.MOUSE_DOWN, arrowPressed );
            
            addChild( slider );
            addChild( up_arrow );
            addChild( down_arrow );
        }
        
        /**
         * Override the add and remove event listeners, so that SliderEvent.CHANGE events will be 
         * subscribed to the Slider directly.
         * 
         * There is issues with this however, Event.CHANGE events will get subscribed directly too Slider as well.
         */
        public override function addEventListener( type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false ):void
        {
            if ( type === SliderEvent.CHANGE )
            {
                slider.addEventListener( SliderEvent.CHANGE, listener, useCapture, priority, useWeakReference );
                return;
            }
            super.addEventListener( type, listener, useCapture, priority, useWeakReference );
        }
        public override function removeEventListener( type:String, listener:Function, useCapture:Boolean=false ):void
        {
            if ( type === SliderEvent.CHANGE )
            {
                slider.removeEventListener( SliderEvent.CHANGE, listener, useCapture );
                return;
            }
            super.removeEventListener( type, listener, useCapture );
        }
    }
}

Once again this code should be failry intuitive, but I will actually go over this one.

Pretty much all we are doing here is creating the slider and the arrows and assigning their functionality. When either of the arrows are pressed the arrowPressed method gets invoked, we see which arrow was pressed, then we update the slider accordingly. The slider retains all of it’s previous functionality… because we haven’t touched it.

So now we have all of this… but still, it’s really not a scrollbar.

Content?

This part is by far the easiest, and can be thought of as yet another abstraction. We can build a ScrollContent class that is a composition of a scrollbar and some content.

We will assume that all content wishing to be scrolled is a Sprite. We will utilize various properties of the sprite to set up the scroll. The method in which we will scroll the content is simple and is explained in this post: http://www.createage.com/blog/?p=105.

Here is a simple implementation of the ScrollContent class.

ScrollContent


package
{
    import flash.display.Sprite;
    import flash.geom.Rectangle;

    public class ScrollContent extends Sprite
    {
        // elements
        protected var content:Sprite;
        protected var scrollbar:Scrollbar;
        protected var contentHeight:Number;
        
        /**
         * Constructor
         */
        public function ScrollContent( clip:Sprite, scroller:Scrollbar, scrollRect:Rectangle )
        {
            content = clip;
            contentHeight = clip.height;
            content.scrollRect = scrollRect;
            
            scrollbar = scroller;
            
            scrollbar.addEventListener( SliderEvent.CHANGE, updateContent );
        }
        
        public function updateContent( e:SliderEvent ):void
        {
            var scrollable:Number = contentHeight - content.scrollRect.height;
            var sr:Rectangle = content.scrollRect.clone();

            sr.y = scrollable * e.percent;
            
            content.scrollRect = sr;
        }
    }
}

You can see that this is yet again another simple abstraction. It was a little more of a process to get started, but once complete you have a very flexible, very reusable base from which you can implement many different kinds of scrolling components.

The main class that was used to test this follows (it’s simple, you shouldn’t have an issue understanding it).

ScrollbarExample


package {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.geom.Rectangle;

    public class ScrollbarExample extends Sprite
    {
        public function ScrollbarExample()
        {
            var content:Sprite = new Sprite();
            var scrollbar:Scrollbar = new Scrollbar();
            var scroll_rect:Rectangle = new Rectangle( 0, 0, 100, 50 );
            
            content.graphics.beginFill( 0xFF0000, 1 );
            content.graphics.drawRect( 0, 0, 100, 50 );
            content.graphics.beginFill( 0x00FF00, 1 );
            content.graphics.drawRect( 0, 50, 100, 50 );
            content.graphics.beginFill( 0x0000FF, 1 );
            content.graphics.drawRect( 0, 100, 100, 50 );
            content.graphics.endFill();
            
            var rect:Rectangle = new Rectangle( 0, 0, 100, 50 );
            var sc:ScrollContent = new ScrollContent( content, scrollbar, rect );
            
            scrollbar.x = content.width;
            
            addChild( content );
            addChild( scrollbar );
        }
    }
}

Take care, if anyone has any questions I will do my best to answer as quickly as I can.

Michael