slider
a backbone + underscore custom control experiment
HTML
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<body>
<div class="label">Slider Demo</div>
<div id="sliderContainer"></div>
</body>
CSS
BODY {
margin: 20px;
}
DIV {
margin: 0px;
}
#sliderContainer {
}
.label {
font-family: Tahoma, Arial;
font-size: 14px;
font-weight: bold;
padding: 4px 4px 6px 4px;
}
.slider {
min-height: 25px;
min-width: 100px;
border-radius: 5px;
background-color: #f6f6f6;
}
.sliderTrack {
position: relative;
top: 11px;
margin: 0px 10px 0px 10px;
height: 2px;
border-radius: 2px;
border: 1px solid #cec3c3;
background-color: #cfcfcf;
}
.sliderThumbContainer {
position: relative;
top: -2px;
width: 22px;
height: 23px;
cursor: pointer;
/* background-color: #cfcfcf; */
}
.sliderThumb {
top: 0px;
left: 0px;
width: 12px;
height: 20px;
margin: 0 auto;
border-radius: 5px;
border: 1px solid #c3c3c3;
background: #ccc;
box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.20);
}
JavaScript
/*
* What does this do?
*
* It started out with me trying to find a reasonably good slider control for a web app. The app has
* a lot of UI that is built dynamically, where the DOM is constructed and styles are set directly via
* javascript. I didn't like that and wanted to try out a template system like what backbone views do
* with _. But there really is no model or collection here -- I could if I streched it all the way, but
* that's not the goal here.
*
* What I ended up with separates the view and CSS from the logic of the actual control. And it turned
* out to be quite similar to how most javascript templating systems work. The control, when instantiated,
* creates a template with appropriate parameters filled in and then uses jQuery to contruct an element
* tree by using the template instance as the HTML input. This is the line that reads like,
*
* _$el = $(_.template(_t, { id: id, width: (width || 100) })),
*
* The rest is straightforward. We get direct references to elements in this tree where we need to bind
* event handlers or change properties later, again using jQuery. This is so that we aren't repeatedly
* execution jQuery selectors which can get a bit slow if we're not careful.
*
* Backbone is also used to expose custom events from this control. This is not wired up yet, but will be
* soon.
*/
function slider(id, width) {
_.extend(this, Backbone.Events);
var _i = this,
// todo - can we refactor to get _thumbWidth from element styles?
_thumbWidth = 24,
_slideRange = width - _thumbWidth,
// View template for control. Typically this would be outside the class,
// so it's reused between multiple instance of this control.
// The id is bound as a paremeter in the template. There may be other parameters.
//
_t = '<div id="<%=id%>" class="slider" style="width:<%=width%>px;">' +
' <div id="<%=id%>_track"...