在尝试复制和改进canjs.org首页中的待办事项列表时,我遇到了一些障碍。该示例未向您展示如何将项目添加到待办事项列表。所以我添加了一个“添加另一个”范围,在单击时执行newTodo。
<h2>Todays to-dos</h2>
{{#selectedTodo}}
<input type="text" can-value="description" can-change="saveTodo">
{{/selectedTodo}}
<ul>
{{#each todos}}
<li>
<input type="checkbox" can-value="complete" can-click="saveTodo">
<span class="description {{#if complete}}done{{/if}}" can-click="select">{{description}}</span>
<button can-click="destroy"><i class="fa fa-close"></i></button>
</li>
{{/each}}
<li>
<span class="description" can-click="newTodo">Add Another</span>
</li>
</ul>
接下来我添加newTodo函数,在保存新Todos列表后重置Todos列表。
var Todo = can.Model.extend({
findAll: 'GET /todo/',
findOne: 'GET /todo/{id}/',
update: 'POST /todo/{id}/',
destroy: 'POST /todo/delete/{id}/',
create: 'POST /todo/new/',
}, {});
can.Component.extend({
tag: 'todolist',
template: can.view("/static/can/todo_list.html"),
scope: {
selectedTodo: null,
todos: new Todo.List({}),
select: function(todo){
this.attr('selectedTodo', todo);
},
saveTodo: function(todo) {
todo.save();
this.removeAttr('selectedTodo');
},
newTodo: function() {
var that = this;
var t = new Todo({}).save(function() { that.attr("todos",new Todo.List({})) });
},
}
})
$(function() {
$("#todo-wrapper").append(can.mustache("<todolist></todolist>")({}));
});
然而,这导致列表被完全擦除然后重写,导致丑陋的闪烁效果。我觉得有更好的方法来做到这一点。