simplifying localStorage interface a bit.

This commit is contained in:
Jeremy Ashkenas
2010-10-25 16:40:09 -04:00
parent edbdeb1189
commit 6efd643e14
2 changed files with 10 additions and 15 deletions

View File

@@ -6,15 +6,11 @@ $(function(){
// Our basic **Todo** model. Has `content`, `order`, and `done` attributes.
window.Todo = Backbone.Model.extend({
// Toggle the `done` state of this todo item.
toggle: function() {
this.save({done: !this.get("done")});
},
// Pull out the model's attributes from the the *localStorage* representation.
parse: function(resp) {
return resp.model;
},
// Remove this Todo from *localStorage*, deleting its view.
clear: function() {
this.destroy();
@@ -27,29 +23,28 @@ $(function(){
// server.
window.TodoList = Backbone.Collection.extend({
model: Todo,
localStore: new Store("todos"),
model: Todo,
localStore: "todos",
// Returns all done todos.
// Filter down the list of all todo items that are finished.
done: function() {
return this.filter(function(todo){
return todo.get('done');
});
},
// We keep the Todos in sequential order, despite being saved by unordered
// GUID in the database. This generates the next order number for new items.
nextOrder: function() {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
// Todos are sorted by their original order.
comparator: function(todo) {
return todo.get('order');
},
parse: function(resp) {
return resp.models;
},
pluralize: function(count) {
return count == 1 ? 'item' : 'items';
}

View File

@@ -95,7 +95,7 @@ _.extend(Store.prototype, {
this.data = [];
}
return {models: this.data, status: "success"};
return {model: this.data, status: "success"};
},
destroy: function(model) {
@@ -133,7 +133,7 @@ _.extend(Store.prototype, {
Backbone.sync = function(method, model, success, error) {
var resp;
var store = model.localStore ? model.localStore : model.collection.localStore;
var store = new Store(model.localStore ? model.localStore : model.collection.localStore);
switch (method) {
case "read": resp = model.id ? store.find(model) : store.findAll(); break;
@@ -143,7 +143,7 @@ Backbone.sync = function(method, model, success, error) {
}
if (resp.status == "success") {
success(resp);
success(resp.model);
} else if (resp.status == "error" && error) {
error(resp);
}