在渲染之前对主干集合进行排序

Sorting Backbone collections prior to render

本文关键字:集合 排序      更新时间:2023-09-26

编辑:要对主干集合进行排序,您只需指定一个比较器(无需定义sortBy 机制(,如下所示: dictionary.add(entry); dictionary.comparator = 'word';


我在对使用 .add(((未预加载(推送新模型的集合进行排序时遇到问题。我试图在下面使用下划线的排序方法

 var sorted = _(dictionary).sortBy("word");

但我无法让集合响应。 下面是我的代码。 我在底部注释掉了我的不起作用的代码。

(function($){
    //---------SINGLE ENTRY MODEL----------
            var Entry = Backbone.Model.extend({
                defaults: function(){
                    return{
                        word: '',
                        definition: ''
                    }
                }
            });
        //------------ENTRY MODEL COLLECTION------------
            var EntryList = Backbone.Collection.extend({
                model: Entry
            });
        //-----INSTANCIATE COLLECTION----
        var dictionary = new EntryList();
        //-----SINGLE ENTRY VIEW------
        var EntryView = Backbone.View.extend({
            model: new Entry(),
            tagName:'div',
            events:{
                'click .edit': 'edit',
                'click .delete': 'delete',
                'keypress .definition': 'updateOnEnter'
            },
            delete: function(ev){
                ev.preventDefault;
                dictionary.remove(this.model);
            },
            edit: function(ev){
                ev.preventDefault;
                this.$('.definition').attr('contenteditable', true).focus();
            },
            close: function(){
                var definition = this.$('.definition').text();
                this.model.set('definition', definition);
                this.$('.definition').attr('contenteditable', false).blur();
            },
            updateOnEnter: function(ev){
                if(ev.which == 13){
                    this.close();
                }
            },
            initialize: function(){
                this.template = _.template($("#dictionary_template").html());
            },
            render: function(){
                this.$el.html(this.template(this.model.toJSON()));
                return this;
            }
        });
        //--------------DICTIONARY VIEW------------
        var DictionaryView = Backbone.View.extend({
            model: dictionary,
            el: $('#entries'),
            initialize: function(){
                this.model.on('add', this.render, this);
                this.model.on('remove', this.render, this);
            },
            render: function(){
                var self = this;
                self.$el.html('');
                _.each(this.model.toArray(), function(entry, i){
                    self.$el.append((new EntryView({model: entry})).render().$el);
                });
                return this;
            }
        });

        //-------BINDING DATA ENTRY TO NEW MODEL VIEW-------
        $(document).ready(function(){
            $('#new-entry').submit(function(ev){
                var entry = new Entry({word: $('#word').val(), definition: $('#definition').val() });
                dictionary.add(entry);
                //var sorted = _(dictionary).sortBy("word");
                //console.log(sorted.toJSON());
                console.log(dictionary.toJSON());
                $('.form-group').children('input').val('');
                return false;
            });
            var appView = new DictionaryView();
        });
    })(jQuery);
</script>

我认为你的问题是你正在应用直下划线.js sortBydictionary在 Underscore.js理解它的意义上不是一个collection。相反,这是一个Backbone.Collection(J. Ashkenaz同时写了Backbone和Underscore.js并没有帮助(。因此,不幸的是,在dictionary上运行sortBy会给你带来不可预测的结果(因为除了models道具之外,你在Backbone.Collection上还有各种其他父属性。 所以...

使用sort

我认为最简单,可能最稳定的解决方案是使用 Backbone.Collection.sort() .这一切的美妙之处在于,一旦您提供了comparator,Backbone 将自动为您排序集合(我不是在责备您,请查看文档(。(顺便说一句,您可以通过传入{ sort: false }Backbone.Collection.add()上禁用此功能。

使用比较器

根据文档(强调我的(:

比较器可以定义为 sortBy (传递接受单个参数的函数(、排序(传递需要两个参数的比较器函数(或指示要作为排序依据的属性的字符串

在您的情况下,如果您添加行

dictionary.comparator = "word";

在第一个 Add 函数之前(例如在实例化集合之后(,您应该已经全部设置好了。