jri*_*iro 3 javascript backbone.js backbone-views
我在点击事件中使用我的收藏时遇到问题.为每个模型触发并执行排序功能,但是不会触发重置事件,也不会在视图上更改集合.
我在我的收藏中定义了多个排序标准,例如:
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");
}
});
Run Code Online (Sandbox Code Playgroud)
在我的视图文件中:
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;
}
Run Code Online (Sandbox Code Playgroud)
关于如何解决这个问题的任何想法?
编辑 在下面的答案后,渲染现在被触发,但是对象只在初始化时被排序.任何后续排序都按初始顺序返回集合 - this.changeSort("name");
我的模特:
feNoRequire.Models.CompetitionModel = Backbone.Model.extend({
initialize: function(){
this.attributes.events = new feNoRequire.Collections.EventCollection(this.attributes.events);
}
});
Run Code Online (Sandbox Code Playgroud)
从精细手册:
分类
collection.sort([options])[...]调用sort会触发
"sort"集合上的事件.
所以调用sort不会触发"reset"事件(因为集合没有得到reset),它会触发一个"sort"事件.所以你想:
this.collection.on('sort', this.render, this);
Run Code Online (Sandbox Code Playgroud)
以及绑定到"reset".
演示:http://jsfiddle.net/ambiguous/34Ena/
我看到你正在打电话changeSort('nameReverse'),那个排序就是这样:
nameReverse: function (competition) {
return -competition.get("name");
}
Run Code Online (Sandbox Code Playgroud)
这不会做你认为它做的事情,否定一个非数字字符串会给你NaN.这意味着你最终会尝试对NaNs 列表进行排序,所有这些都是false:
NaN < NaN
NaN > NaN
NaN == NaN
Run Code Online (Sandbox Code Playgroud)
因此排序NaNs 列表没有任何用处.如果要反向排序字符串,则必须使用两个参数比较器函数:
nameReverse: function(a, b) {
a = a.get('name');
b = b.get('name');
return a < b ? 1
: a > b ? -1
: 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4291 次 |
| 最近记录: |