Widgets as Backbone views
jQuery UI widgets can behave as though they're Backbone views.
by Adam Boduch
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<label>CPU 1:</label>
<div id="cpu1"></div>
<label>CPU 2:</label>
<div id="cpu2"></div>
<label>Allocated:</label>
<div id="allocated"></div>
CSS
body {
font-size: 0.8em;
}
div {
width: 30%;
margin-bottom: 0.5em;
}
JavaScript
(function( $ ) {
var Capacity = Backbone.Model.extend({
defaults: {
cpu1: 50,
cpu2: 50
},
allocated: function() {
return ( this.get( "cpu1" ) + this.get( "cpu2" ) ) / 2;
}
});
var capacity = new Capacity();
$(function() {
$( "#cpu1" ).slider({
value: capacity.get( "cpu1" ),
change: function( e, ui ) {
capacity.set( "cpu1", ui.value );
}
});
$( "#cpu2" ).slider({
value: capacity.get( "cpu2" ),
change: function( e, ui ) {
capacity.set( "cpu2", ui.value );
}
});
$( "#allocated" ).progressbar({
value: capacity.allocated(),
create: function( e, ui ) {
var self = this;
capacity.on( "change", function( model ) {
$( self ).progressbar( "value", model.allocated() );
});
}
});
});
})( jQuery );