Skip to content

Instantly share code, notes, and snippets.

@gdugas
Created March 17, 2014 13:48
Show Gist options
  • Save gdugas/9599459 to your computer and use it in GitHub Desktop.
Save gdugas/9599459 to your computer and use it in GitHub Desktop.
BackboneJs Progressbar
var ProgressItem = Backbone.Model.extend({
defaults: {
max: 100,
value: 0
},
getValueRatio: function () {
return this.get('value') * 100 / this.get('max');
}
});
var ProgressView = Backbone.View.extend({
initialize: function (options) {
this.$el.empty();
this.$wrapper = $('<div></div>').css({
'position': 'relative',
'width': '100%',
'height': '100%'
});
this.$el.append(this.$wrapper);
this.$remaining = $('<div></div>').css({
'position': 'absolute',
'height': '100%',
'left': 0,
'right': 0
}).addClass('remaining');
this.$wrapper.append(this.$remaining);
},
progressTo: function (percent) {
this.$remaining.css('left', percent + '%');
}
});
var ProgressBar = Backbone.Collection.extend({
model: ProgressItem,
defaults: {
el: null
},
initialize: function (models, options) {
options = _.extend({}, this.defaults, options);
this.view = new ProgressView({
el: options.el
});
this.on('add', this.update);
this.on('remove', this.update);
this.on('change', this.update);
this.update();
},
update: function () {
var max = 0,
value = 0;
for (i = 0; i < this.models.length; i++) {
var item = this.models[i];
max += item.get('max');
value += item.get('value');
}
progression = value * 100 / max;
this.view.progressTo(progression);
this.trigger('progress', progression);
}
});
@gdugas
Copy link
Author

gdugas commented Mar 17, 2014

Require BackboneJs

QuickStart

<style>
  #progressbar {background: blue; width: 100%; height: 4px;}
  #progressbar .remaining {background: red;}
</style>

<div id="progressbar"></div>

<script>
$(document).on('ready', function () {
  var item = new ProgressItem();
       bar =  new ProgressBar([item], {el: $('#progressbar')});

  bar.on('progress', function (progression) {
      // ...
  });

  item.set('value', 30);
});
</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment