[model][m]: (fixes #6) create a BackendMemory (local data in memory) and refactor code to use this rather than current hard-coding-of-data approach.

This commit is contained in:
rgrp
2011-11-05 19:48:09 +00:00
parent bd52bb2c58
commit 21d9a1c2dc
4 changed files with 94 additions and 36 deletions

View File

@@ -2,9 +2,7 @@ this.recline = this.recline || {};
// A Dataset model.
recline.Dataset = Backbone.Model.extend({
initialize: function(data, rawDocumentSet) {
this.documentSet = new recline.DocumentSet(rawDocumentSet);
}
__type__: 'Dataset'
});
recline.Document = Backbone.Model.extend({});
@@ -15,9 +13,7 @@ recline.DocumentList = Backbone.Collection.extend({
})
recline.DocumentSet = Backbone.Model.extend({
fetch: function(options) {
options.success(this);
},
__type__: 'DocumentSet',
getLength: function() {
return this.get('rows').length;
},
@@ -35,3 +31,46 @@ recline.DocumentSet = Backbone.Model.extend({
}
});
// Backend which just caches in memory
//
// Does not need to be a backbone model but provides some conveience
recline.BackendMemory = Backbone.Model.extend({
initialize: function() {
this._datasetCache = {}
},
// dataset is object with metadata and data attributes
addDataset: function(dataset) {
this._datasetCache[dataset.metadata.id] = dataset;
},
getDataset: function(id) {
var dataset = new recline.Dataset({
id: id
});
// this is a bit weird but problem is in sync this is set to parent model object so need to give dataset a reference to backend explicitly
dataset.backend = this;
return dataset;
},
sync: function(method, model, options) {
if (method === "read") {
var dfd = $.Deferred();
// this switching on object type is rather horrible
// think may make more sense to do work in individual objects rather than in central Backbone.sync
if (this.__type__ == 'Dataset') {
var dataset = this;
var rawDataset = this.backend._datasetCache[model.id];
dataset.set(rawDataset.metadata);
dataset.documentSet = new recline.DocumentSet(rawDataset.data);
dataset.documentSet.dataset = dataset;
dfd.resolve(dataset);
} else if (this.__type__ == 'DocumentSet') {
dfd.resolve(this);
}
return dfd.promise();
}
}
});
recline.setBackend = function(backend) {
Backbone.sync = backend.sync;
};