javascript - Re-sorting backbone collection from view -
i'm having problems resorting collection upon click event. sorting function triggered , executes each model neither reset event gets triggered nor collection changes on view.
i have multiple sort criterias defined on collection like:
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"); } });
and on view file:
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 rendering") var renderedcontent = this.template({competitions: this.collection.tojson()}); $(this.el).html(renderedcontent); return this; }
any idea on how solve this?
edit after answers bellow render triggered objected sorted on initialize. subsequent sorts return collection in initial order - this.changesort("name");
my model:
fenorequire.models.competitionmodel = backbone.model.extend({ initialize: function(){ this.attributes.events = new fenorequire.collections.eventcollection(this.attributes.events); } });
from fine manual:
sort
collection.sort([options])
[...] calling sort triggers
"sort"
event on collection.
so calling sort
doesn't trigger "reset"
event (because collection doesn't reset
), triggers "sort"
event. want to:
this.collection.on('sort', this.render, this);
as binding "reset"
.
demo: http://jsfiddle.net/ambiguous/34ena/
i see you're calling changesort('namereverse')
, that sorting this:
namereverse: function (competition) { return -competition.get("name"); }
that won't think does, negating non-numeric string give nan
. means you'll end trying sort list of nan
s , of these false
:
nan < nan nan > nan nan == nan
so sorting list of nan
s nothing useful. you'll have use 2 argument comparator function if want reverse sort strings:
namereverse: function(a, b) { = a.get('name'); b = b.get('name'); return < b ? 1 : > b ? -1 : 0; }
Comments
Post a Comment