JSFiddle - React, Tailwind, and code Playground
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,
sort_key: 'id',
initialize: function() {
},
comparator: function(a) {
return a.get(this.sort_key);
},
sortByField: function(fieldName) {
this.sort_key = fieldName;
this.sort();
}
});
var V = Backbone.View.extend({
el: '#view-goes-here',
initialize: function() {
this.collection.on('reset', this.render, this);
this.collection.on('sort', this.render, this);
},
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.sortByField('id');
});
$('#by-s').click(function() {
c.sortByField('s');
});