This example shows the how to create a legend for vector layers. Zoom out to see how the legend is updated with changes in scale.
The js is not minified so it is readable. See vector-legend.js.