The*_*net 3 javascript backbone.js underscore.js
我有一个简单的backbone.js twitter应用程序,需要以相反的顺序排序推文.我目前按日期实施了一个比较器排序.单击"反向"按钮时(如视图中所示)如何反转排序所有推文而不返回比较器?我的印象是,当我调用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();
});
Run Code Online (Sandbox Code Playgroud)
Backbone问题的常见解决方案是使用事件.通话sort将触发"reset"事件:
调用sort会触发集合的
"reset"事件,除非通过传递进行静音{silent: true}.
所以你可以在你的集合中有一个"排序顺序"标志:
Backbone.Collection.extend({
//...
initialize: function() {
//...
this.sort_order = 'desc';
//...
}
});
Run Code Online (Sandbox Code Playgroud)
然后你comparator可以注意那个标志:
comparator: function(activity) {
var date = new Date(activity.get('created_at'));
return this.sort_order == 'desc'
? -date.getTime()
: date.getTime()
}
Run Code Online (Sandbox Code Playgroud)
你可以在集合上有一个方法来改变排序顺序:
reverse: function() {
this.sort_order = this.sort_order = 'desc' ? 'asc' : 'desc';
this.sort();
}
Run Code Online (Sandbox Code Playgroud)
然后,您的视图可以侦听"reset"事件,并在更改排序顺序时重新显示集合.一旦完成所有这些,您只需告诉您的反向按钮即可拨打电话view.collection.reverse(),一切都会好起来的.
演示:http://jsfiddle.net/ambiguous/SJDKy/