我对集合的渲染有问题。它带有标题和布尔“已完成”的简单模型,当您单击列表项时,它会更改为已完成值(真/假)。值已更改(我知道这是因为当我刷新页面时,在 fetch() 之后进行初始化时,我有 collection.pluck,其中比较器的顺序是正确的),但视图看起来始终相同。
在集合中,我有比较器,其工作方式与我在上面描述的一样,在 collection.fetch() 之后我有 pluck,并且 pluck 给了我排序良好的列表(但在视图中我看到了不好的默认顺序)。我不知道如何刷新集合以进行良好排序。
收藏只是:
var TodolistCollection = Backbone.Collection.extend({
model: TodoModel,
localStorage: new Store('todos-backbone'),
// Sort todos
comparator: function(todo) {
return todo.get('completed');
}
});
型号为:
var TodoModel = Backbone.Model.extend({
defaults: {
title: '',
completed: false
},
// Toggle completed state of todo item
toggle: function(){
this.save({
completed: !this.get('completed')
});
}
});
return TodoModel;
单个 todoView 是:
var TodoView = Backbone.View.extend({
tagName: 'li',
template: JST['app/scripts/templates/todoView.ejs'],
events: {
'click .js-complete': 'toggleCompleted'
},
initialize: function(){
this.listenTo(this.model, 'change', this.render);
},
render: function() {
this.$el.html( this.template( this.model.toJSON() ));
this.$el.toggleClass( 'l-completed', this.model.get('completed') );
return this;
},
// Toggle the `"completed"` state of the model.
toggleCompleted: function() {
this.model.toggle();
}
和应用视图:
var ApplicationView = Backbone.View.extend({
el: $('.container'),
template: JST['app/scripts/templates/application.ejs'],
events: {
'click #add' : 'createOnEnter',
'keypress #addTodo' : 'createOnEnter'
},
// aliasy do DOMu,
// nasluchiwanie w kolekcji czy zaszlo jakies zdarzenie, jesli tak, to wykonuje funkcje
initialize: function() {
this.$input = this.$('.js-input');
this.listenTo(todoList, 'add', this.addOne);
this.listenTo(todoList, 'reset', this.addAll);
this.listenTo(todoList, 'all', this.render);
todoList.fetch();
console.log(todoList.pluck('title'));
},
render: function() {
},
// Generate the attributes for a new Todo item.
newAttributes: function() {
return {
title: this.$input.val().trim(),
completed: false
};
},
// Tworzy nowy model dzieki newAtributes() do localStorage
addTodo: function ( e ) {
e.preventDefault();
if( e.which !== Common.ENTER_KEY || !this.$input.val().trim() ){
return;
}
todoList.create( this.newAttributes() );
this.$input.val('');
},
// Tworzy model i dopisuje go do listy
addOne: function( todo ){
var view = new todoView({ model: todo });
$('.js-todolist').append( view.render().el );
},
// Tworzy nowego todo gdy nacisniemy enter
createOnEnter: function( e ) {
if( e.which !== Common.ENTER_KEY || !this.$input.val().trim() ){
return;
}
todoList.create( this.newAttributes() );
this.$input.val('');
},
// Przy rerenderze, dodaj wszystkie pozycje
addAll: function() {
this.$('.js-todolist').html('');
todoList.each(this.addOne, this);
}
});
return ApplicationView;
当我改变listenTo渲染时: this.listenTo(todoList, 'all', function(){console.log('whateva')}); 我可以看到在我的点击“全部”时触发(甚至每次点击 3 次 ;s )。
我很难把它放在 jsfiddle 上,但这里是所有文件的 git 链接:https ://github.com/ozeczek/ozeczek/tree/master/bb-todo-yo/app/scripts