Skip to content

Instantly share code, notes, and snippets.

@jwillman
Created October 16, 2012 11:46
Show Gist options
  • Save jwillman/3898818 to your computer and use it in GitHub Desktop.
Save jwillman/3898818 to your computer and use it in GitHub Desktop.
<!-- HTML -->
<div>
<div>
<h3>Tehtävälista:</h3>
<ul data-bind="foreach: todos, visible: todos().length > 0">
<li>
<label data-bind="value: title" />
<a href="#" data-bind="click: $parent.removeTodo">Poista</a>
</li>
</ul>
</div>
<div>
<form data-bind="submit: addTodo">
<input type="text" data-bind="value: newTodoText"/>
<button type="submit">Lisää uusi tehtävä</button>
</form>
</div>
</div>
<!-- JS -->
function Todo(data) {
this.id = data.todoId;
this.title = ko.observable(data.title);
}
function saveTodo(title, success) {
$.post('api/todo',
{ 'title': title },
success);
}
function deleteTodo(id, success) {
$.ajax({
url: 'api/todo/' + id,
type: 'DELETE',
success: function () {
success;
}
});
}
function TodoListViewModel() {
var self = this;
self.todos = ko.observableArray([]);
self.newTodoText = ko.observable();
self.addTodo = function () {
var title = this.newTodoText();
self.todos.push(new Todo({ title: title }));
self.newTodoText("");
saveTodo(title, function() { return null; });
};
self.removeTodo = function(todo) {
deleteTodo(todo.id, function() { self.todos.remove(todo); });
};
$.getJSON("/api/todo", function (allData) {
var mappedTodos = $.map(allData, function(item) { return new Todo(item); });
self.todos(mappedTodos);
console.log(self.todos());
console.log(self.todos().length);
});
}
ko.applyBindings(new TodoListViewModel());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment