JSFiddle - React, Tailwind, and code Playground
by Eric Howe
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<div id="view-goes-here"></div>
<button id="by-id">id</button>
<button id="by-s">s</button>
CSS
#view-goes-here {
padding: 50px;
border: 1px solid black;
}
JavaScript
var M = Backbone.Model.extend({});
var C = Backbone.Collection.extend({
model: M,
initialize: function() {
this.sort_key = 'id';
},
comparator: function(a, b) {
a = a.get(this.sort_key);
b = b.get(this.sort_key);
return a > b ? 1
: a < b ? -1
: 0;
},
sort_by_id: function() {
this.sort_key = 'id';
this.sort();
},
sort_by_s: function() {
this.sort_key = 's';
this.sort();
}
});
var V = Backbone.View.extend({
el: '#view-goes-here',
initialize: function() {
this.listenTo(this.collection, 'sort reset', this.render);
},
render: function() {
this.$el.empty();
this.collection.each(function(m) {
this.$el.append('<p>' + m.get('s') + '</p>');
}, this);
return this;
}
});
var c = new C([
{ id: 1, s: 'where' },
{ id: 4, s: 'house?' },
{ id: 2, s: 'is' },
{ id: 3, s: 'pancakes' }
]);
var v = new V({ collection: c });
v.render();
$('#by-id').click(function() {
c.sort_by_id();
});
$('#by-s').click(function() {
c.sort_by_s();
});