Skip to content

Instantly share code, notes, and snippets.

@ainsofs
Created April 26, 2015 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ainsofs/fd5954ebfa6a992fd5b8 to your computer and use it in GitHub Desktop.
Save ainsofs/fd5954ebfa6a992fd5b8 to your computer and use it in GitHub Desktop.
Sample knockout script
(function () {
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
}
function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
self.newTaskText = ko.observable();
self.incompleteTasks = ko.computed(function () {
return ko.utils.arrayFilter(self.tasks(), function (task) { return !task.isDone() && !task._destroy });
});
// Operations
self.addTask = function () {
self.tasks.push(new Task({ title: this.newTaskText() }));
self.newTaskText("");
};
self.removeTask = function (task) { self.tasks.destroy(task) };
$.getJSON("/tasks", function (allData) {
var mappedTasks = $.map(allData, function (item) { return new Task(item) });
self.tasks(mappedTasks);
});
self.save = function () {
$.ajax("/tasks", {
data: ko.toJSON(self.tasks),
type: "post",
contentType: "application/json",
success: function (result) { alert(result) }
});
};
}
ko.applyBindings(new TaskListViewModel());
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment