我有一个简单的backbone.js 推特应用程序,它需要以相反的顺序对推文进行排序。我目前已经实现了按日期排序的比较器。单击“反向”按钮时(如视图中所示),如何在不返回比较器的情况下对所有推文进行反向排序?我的印象是,当我调用 sort 时,它会尝试重新渲染列表(这意味着比较器将再次对数据进行排序,这是不可取的)。我该如何覆盖这个?
Tweet = Backbone.Model.extend();
// Define the collection
Tweets = Backbone.Collection.extend(
{
model: Tweet,
// Url to request when fetch() is called
url: 'http://search.twitter.com/search.json?q=codinghorror',
parse: function(response) {
//modify dates to be more readable
$.each(response.results, function(i,val) {
val.created_at = val.created_at.slice(0, val.created_at.length - 6);
});
return response.results;
},
// Overwrite the sync method to pass over the Same Origin Policy
sync: function(method, model, options) {
var that = this;
var params = _.extend({
type: 'GET',
dataType: 'jsonp',
url: that.url,
processData: true
}, options);
return $.ajax(params);
},
comparator: function(activity){
var date = new Date(activity.get('created_at'));
return -date.getTime();
}
});
// Define the View
TweetsView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
// create a collection
this.collection = new Tweets;
// Fetch the collection and call render() method
var that = this;
this.collection.fetch({
success: function (s) {
console.log("fetched", s);
that.render();
}
});
},
el: $('#tweetContainer'),
// Use an external template
template: _.template($('#tweettemplate').html()),
render: function() {
// Fill the html with the template and the collection
$(this.el).html(this.template({ tweets: this.collection.toJSON() }));
},
events : {
'click .refresh' : 'refresh',
**'click .reverse' : 'reverse'**
},
refresh : function() {
this.collection.fetch();
console.log('refresh', this.collection);
this.render();
},
**reverse : function() {**
console.log("you clicked reverse");
console.log(this.collection, "collection");
this.collection.sort();
//How do I reverse the list without going through the comparator?
**}**
});
var app = new TweetsView();
});