3

クリック イベントでコレクションを再分類する際に問題が発生しています。モデルごとに並べ替え関数がトリガーされて実行されますが、リセット イベントがトリガーされたり、ビューでコレクションが変更されたりすることはありません。

私のコレクションには、次のような複数の並べ替え基準が定義されています。

feNoRequire.Collections.CompetitionCollection = Backbone.Collection.extend({

    model: feNoRequire.Models.CompetitionModel,
    comparator: function (property) {
        return selectedStrategy.apply(model.get(property));
    },
    strategies: {
        name: function (competition) { return competition.get("name"); }, 
        nameReverse: function (competition) { console.log(competition); return -competition.get("name"); }, 
        date: function (competition) { console.log(competition.get("event")); },
    },
    changeSort: function (sortProperty) {
        this.comparator = this.strategies[sortProperty];
    },
    initialize: function () {
        this.changeSort("name");   
    }

});

そして私のビューファイルで:

initialize: function(options){
        this.evnt = options.evnt;

        this.collection.on('reset', this.render, this);     
        this.evnt.bind("orderByDate", this.changeSort, this);
    },

    changeSort: function(){
        this.collection.changeSort('nameReverse')
        this.collection.sort();
    },

    render: function() {
        console.log("going for rendering")
        var renderedContent = this.template({competitions: this.collection.toJSON()});

        $(this.el).html(renderedContent);
        return this;
    }

これを解決する方法について何か考えはありますか?

編集 以下の回答の後、レンダリングがトリガーされますが、オブジェクトは初期化時にのみソートされます。以降の並べ替えでは、最初の順序でコレクションが返されます - this.changeSort("name");

私のモデル:

feNoRequire.Models.CompetitionModel = Backbone.Model.extend({
    initialize: function(){
        this.attributes.events = new feNoRequire.Collections.EventCollection(this.attributes.events);
    }
});
4

3 に答える 3

1

とても素敵なコード設定。戦略オブジェクトを介してソート関数を呼び出す方法が本当に気に入っています。

このコードの問題は、次のセクションに起因していると思います。

comparator: function (property) {
    return selectedStrategy.apply(model.get(property));
},

ドキュメントによると、コンパレーター関数はモデルまたはイテレーター (プロパティではない) を受け取ります。また、selectedStrategy が参照しているものがわからない...これは、提供したコードの外部のどこかに存在する別の関数ですか?

Apply は、"this" として機能するコンテキスト オブジェクトと、引数の配列も受け取ります。適用に関する MDN ドキュメントに従って:

fun.apply(thisArg[, argsArray])

モデルのプロパティが「これ」として使用したいオブジェクトでない限り、これが正しく機能しているとは思えません。モデル定義も見ることができれば、もっと理にかなっているかもしれません。

編集:入ってきた他の応答を読んだ後、ソートではなくリセットイベントを見ていることに気付きました。そのため、私の応答はおそらくコードの誤解であり、問​​題ではありません:)

于 2013-05-04T16:35:48.020 に答える