Skip to content

Instantly share code, notes, and snippets.

@imjoshdean
Created September 20, 2013 21:52
Show Gist options
  • Save imjoshdean/6644425 to your computer and use it in GitHub Desktop.
Save imjoshdean/6644425 to your computer and use it in GitHub Desktop.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://canjs.com/release/latest/can.jquery.js"></script>
<script type="text/javascript" src="http://canjs.com/release/latest/can.fixture.js"></script>
<script type="text/javascript" src="http://canjs.com/release/latest/can.object.js"></script>
</head>
<body>
<div id="todos"></div>
<script type="text/ejs" id="todoTemplate">
<ul>
<% todos.each(function(todo, i) { %>
<li <%= (el) -> el.data('model', todo) %>>
<%= todo.attr('name') %>
<input type="checkbox" <%= todo.attr('complete') ? 'checked' : '' %> />
</li>
<% }) %>
</ul>
<p>There is <%= percentage() %>% left to do</p>
</script>
<script>
var TodoModel = can.Model.extend({
findAll: 'GET /todos',
findOne: 'GET /todos/{id}',
create: 'POST /todos',
update: 'PUT /todos/{id}',
destroy: 'DESTROY /todos/{id}'
}, { })
var todoStore = can.fixture.store(11, function(i) {
i++;
return {
id: i,
name: 'Todo ' + i,
complete: false
}
})
can.fixture({
'GET /todos': todoStore.findAll,
'GET /todos/{id}': todoStore.findOne,
'POST /todos': todoStore.create,
'PUT /todos/{id}': todoStore.update,
'DELETE /todos/{id}': todoStore.destroy
});
var TodoListControl = can.Control.extend({
defaults: { }
}, {
init: function(el, options) {
this.element.html(can.view('todoTemplate', {
todos: this.options.todos,
percentage: this.getPercentage()
}))
},
getPercentage: function() {
return can.compute(can.proxy(function() {
var completed = 0;
this.options.todos.each(function(todo) {
completed += (todo.attr('complete') ? 1 : 0)
})
return 100 - (100 * (completed / this.options.todos.attr('length'))).toFixed(0);
}, this))
},
"input change" : function(el, ev) {
var todo = el.parent().data('model');
todo.attr('complete', el.is(':checked'));
todo.save();
}
});
var todos = new TodoModel.List({});
new TodoListControl('#todos', { todos: todos });
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment