javascript - 覆盖 Backbone.js 比较器

标签 javascript backbone.js underscore.js

我有一个简单的 backbone.js twitter 应用程序,需要以相反的顺序对推文进行排序。我目前已经实现了按日期排序的比较器。单击“反向”按钮时(如 View 中所示)如何在不返回比较器的情况下对所有推文进行反向排序?我的印象是,当我调用排序时,它将尝试重新呈现列表(这意味着比较器将再次对数据进行排序,这是不可取的)。我该如何覆盖它?

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();
 });

最佳答案

Backbone 问题的通常解决方案是使用事件。来电 sort将触发一个 "reset" 事件:

Calling sort triggers the collection's "reset" event, unless silenced by passing {silent: true}.

所以你可以在你的收藏中有一个“排序顺序”标志:

Backbone.Collection.extend({
    //...
    initialize: function() {
        //...
        this.sort_order = 'desc';
        //...
    }
});

然后你的比较器可以注意那个标志:

comparator: function(activity) {
    var date = new Date(activity.get('created_at'));
    return this.sort_order == 'desc'
         ? -date.getTime()
         :  date.getTime()
}

并且您可以在集合上使用一个方法来更改排序顺序:

reverse: function() {
    this.sort_order = this.sort_order = 'desc' ? 'asc' : 'desc';
    this.sort();
}

然后您的 View 可以监听 “reset” 事件并在您更改排序顺序时重新显示集合。一旦一切就绪,您只需告诉您的 reverse 按钮调用 view.collection.reverse(),一切都会好起来的。

演示:http://jsfiddle.net/ambiguous/SJDKy/

关于javascript - 覆盖 Backbone.js 比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10420986/

相关文章:

javascript - React 中的事件循环是什么?

JavaScript : loop in conditional based on array

javascript - 为什么要定义一个匿名函数并将 jQuery 作为参数传递给它?

javascript - 清除间隔不起作用

javascript - Angular UI 路由器 : child state loaded twice when parent and child take parameter of same name in url

javascript - Backbone/Marionette - 检查模型是否存在

javascript - 如何在不指定模型名称的情况下从该模型的实例调用静态 Backbone.Model 函数?

javascript - 没有唯一键的 lodash indexBy

javascript - 使用 Underscore.js(或使用纯 javascript)减少 javascript 数组

node.js - 如何使用 EJS 呈现使用 Express 和 Node.JS 的 Mongodb 查询结果?