3
我有一個簡單的backbone.js twitter應用程序,需要按相反的順序對推文進行排序。我目前使用日期實現了比較器排序。當點擊「反向」按鈕時(如視圖中所示),如何反向排序所有推文而無需返回比較器?我的印象是,當我調用排序時,它會嘗試重新呈現列表(這意味着比較器會再次對數據進行排序,這是不可取的)。我如何覆蓋這個?覆蓋Backbone.js比較器
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();
});
我在這裏創造一個解決方案,兩個數字和字符串,也許它的工作原理與工程日期?它適用於時代! http://stackoverflow.com/questions/5013819/reverse-sort-order-with-backbone-js/#21434708 – Fasani