Skip to content

Instantly share code, notes, and snippets.

@nekman
Created February 3, 2014 00:11
Show Gist options
  • Save nekman/8777053 to your computer and use it in GitHub Desktop.
Save nekman/8777053 to your computer and use it in GitHub Desktop.
define([
'jquery',
'backbone',
'lodash',
'handlebars',
'listjs'
],
function($, Backbone, _, Handlebars, List) {
'use strict';
var convertCell = function(cell) {
return _.extend(cell, {
text: this.valueConverter[cell.value] || cell.value,
css: this.cssConverter[cell.value] || ''
});
};
/**
* This is a bit "hacky" and needs refactoring...
*/
return Backbone.View.extend({
el: 'div.container',
events: {
mousemove: 'startPoll',
keydown: 'startPoll',
click: 'startPoll',
focus: 'startPoll',
'click #btnSync': 'togglePoll'
},
initialize: function(options) {
this.$loading = this.$('#loading');
this.$error = this.$('#error');
this.$btnSync = this.$('#btnSync');
this.$icon = this.$('#icon');
this.$container = this.$('#container');
this.template = Handlebars.compile($('#sheet-template').html());
this.polltime = 1000 * 60 * (options.poll || 1);
this.valueConverter = options.valueConverter || {};
this.cssConverter = options.cssConverter || {};
this.shouldPoll = true;
this.model.bind('change', this.render.bind(this));
this.model.bind('request', this.showLoading.bind(this));
this.model.fetch().fail(this.fetchFailed.bind(this));
},
showLoading: function(model, xhr) {
this.$error.hide();
// Handle request fail... (does not gets handled on model fetch)
xhr.fail(this.fetchFailed.bind(this));
this.$loading.fadeIn();
},
fetchFailed: function(err) {
this.$loading.fadeOut();
this.$error.html(err.responseText || 'Network error: ' + err.statusText)
.removeClass('hide').fadeIn();
// Re-start the polling, (if we lost the network...)
this.startPoll();
},
clearPoll: function() {
clearTimeout(this.poll);
this.poll = null;
delete this.poll;
return this;
},
togglePoll: function() {
this.shouldPoll = !this.shouldPoll;
this.$icon.toggleClass('glyphicon-pause').toggleClass('glyphicon-play');
return this.clearPoll().startPoll();
},
startPoll: function() {
if (!this.shouldPoll) {
return;
}
this.clearPoll();
this.poll = setTimeout(this.model.fetch.bind(this.model), this.polltime);
return this;
},
convertToViewModel: function() {
// Format our view from the model...
var self = this,
rows = _.map(this.model.get('sheet'), function(cells) {
return _.map(cells, convertCell.bind(self));
});
return {
headerRows: _.first(rows),
bodyRows: _.rest(rows)
};
},
render: function() {
var viewModel = this.convertToViewModel();
this.model.set('viewModel', viewModel);
this.$container
.html(this.template(this.model.toJSON()));
new List(this.$el[0], {
valueNames: _.map(viewModel.headerRows, function(header) {
return header.column;
})
});
this.$loading.fadeOut();
this.$el.fadeIn();
this.$btnSync.removeClass('hide');
return this.startPoll();
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment