我开始使用骨干网,并且无法使比较器驱动排序工作。我有一个简单的集合,我用它来填充页面中的导航菜单。它正从MongoDB后端填充。骨干比较器不能正常工作
window.navItem = Backbone.Model.extend({
initialize: function(){
return {
"title": "no title",
"href": "",
"class": "",
"style": "",
"position": -1,
"showLog": false,
"showUnlog": false
}
},
});
window.navList = Backbone.Collection.extend({
url: "../nav",
initialize: function(){
},
model: navItem,
comparator: function(iNavItem){
return iNavItem.position;
},
});
EDIT包括查看代码: 只是,具有用于改变window.loggedIn变量的状态来显示/掩盖基于它们showLog/showUnLog属性视图构件逻辑的骨架。
window.navView = Backbone.View.extend({
el: $('#navBar'),
initialize: function(){
var self = this;
this.model.bind("reset", this.render, this);
this.navTemplate = Handlebars.compile($("#navListTemplate").html());
},
events: {
"click #navLogIn" : "navLogIn",
"click #navLogOut" : "navLogOut"
},
render: function() {
this.json = _.where(this.model.toJSON(),
{showUnlog:(!window.loggedIn),
showLog:(window.loggedIn)});
$(this.el).html(this.navTemplate(this.json));
return this;
},
navLogIn: function() {
window.loggedIn = !window.loggedIn;
this.render();
},
navLogOut: function() {
window.loggedIn = !window.loggedIn;
this.render();
}
});
该菜单填充和一切似乎工作正常,但该集合没有得到'位置'排序。由于在MongoDB中进行了编辑,我有一个菜单项应该位于导航菜单的第二个插槽中,但最后位于集合中。它始终显示在菜单的最后,即使它的'位置'值应该排序到第二位。
的JSON正在从服务器发送的是:
[{
"_id": "50f6fe449f92f91bc1fcbcf6",
"title": "Account",
"href": "",
"htmlId": "",
"class": "nav-header",
"style": "",
"position": 0,
"showLog": true,
"showUnlog": true
},
{
"_id": "50f6fe449f92f91bc1fcbcf7",
"title": "Log In",
"href": "#",
"htmlId": "navLogIn",
"class": "",
"style": "",
"position": 10,
"showLog": false,
"showUnlog": true
},
{
"_id": "50f6fe449f92f91bc1fcbcf8",
"title": "New Account",
"href": "#",
"htmlId": "",
"class": "",
"style": "",
"position": 20,
"showLog": false,
"showUnlog": true
},
喀嚓...
最后一项没有被分类到适当的位置,最后却显示了......
{
"_id": "50f6fe449f92f91bc1fcbcf9",
"class": "",
"href": "#",
"htmlId": "navLogOut",
"position": 10,
"showLog": true,
"showUnlog": false,
"style": "",
"title": "Log Out"
}]
调用NavList.pluck('position')(NavList是navList的实例化副本)给了我[0,10,20,20,30,40,50,60,70,80,90,10]。
我试着在Firefox的集合上手动启动.sort()函数,但是无法在显示的菜单中或集合本身中更正集合中的模型顺序。
我觉得我在这里错过了很简单的东西。
我看着你链接的讨论(URL中的轻微错字,修正版本[这里](https://github.com/documentcloud/backbone/issues/41)),但我不确定是否解决了这个问题我有。 我在集合中有一个收集器功能,我认为它应该在任何更改时自动对集合进行排序。这不是这种情况吗? 此外,当填充集合时,视图设置为重绘。 (编辑原始文章以包含查看代码)另外,嗅探集合显示了非排序发生在集合级别,而不是刷新问题。 – DanHeidel