Permalink
Browse files

Fix `#use()`, emit "add", etc.

  • Loading branch information...
1 parent 84ebf1d commit a33ece209f21224a633f9e1201eb432726637d3b Dan Dean committed Oct 26, 2012
Showing with 45 additions and 18 deletions.
  1. +3 −0 Makefile
  2. +1 −1 index.js
  3. +15 −16 lib/memory.js
  4. +1 −1 package.json
  5. +25 −0 test/index.js
View
@@ -3,6 +3,9 @@ REPORTER = dot
test:
mocha
+debug:
+ mocha debug
+
server:
node test/server/server.js
View
@@ -247,7 +247,7 @@ function Tubbs(fn, options) {
use: {
value: function(data, cb) {
- dataStore.use(function(e) {
+ dataStore.use(data, function(e) {
if (cb) cb(e);
if (!e) fn.emit('load');
});
View
@@ -10,11 +10,10 @@ module.exports = Memory;
/**
* new Memory(constructor, data)
* - constructor (Tubbs): Tubbs model constructor.
- * - data (Object): An object containing documents, indexed by ID.
**/
-function Memory(constructor, data) {
+function Memory(constructor) {
this.Model = constructor;
- this.use(data || {});
+ this.data = {};
}
Memory.prototype = Object.create({}, {
@@ -135,23 +134,23 @@ Memory.prototype = Object.create({}, {
use: {
value: function(data, callback) {
+ var Model = this.Model;
+ var primaryKey = Model.primaryKey;
var t = this;
this.data = {};
- if (data) {
- if (Array.isArray(data)) {
- data.forEach(function(item) {
- var instance = new t.Model(item);
- t.data[instance.id] = instance;
- });
- } else {
- Object.keys(data).forEach(function(id) {
- var instance = new t.Model(data[id]);
- t.data[id] = instance;
- });
- }
+ if (Array.isArray(data)) {
+ data.forEach(function(item) {
+ Model.emit('add', t.data[item[primaryKey]] = new Model(item))
+ });
+
+ } else {
+ Object.keys(data).forEach(function(key) {
+ Model.emit('add', t.data[key] = new Model(data[key]));
+ });
}
- if(callback) callback();
+ this.ready = true;
+ if (callback) callback();
},
enumerable: true
}
View
@@ -2,7 +2,7 @@
"author": "Dan Dean <@dandean> (http://dandean.com)",
"name": "tubbs",
"description": "Models with an API that I actually like.",
- "version": "0.1.1",
+ "version": "0.1.2",
"repository": {
"type": "git",
"url": "git://github.com/dandean/tubbs.git"
View
@@ -81,6 +81,31 @@ describe('Tubbs', function() {
assert.notEqual(Type1.dataStore, Type2.dataStore);
});
+ it('should load data from on object', function(done) {
+ var data = {
+ "rad": {
+ "id": 50,
+ "username": 'rad',
+ "firstName": 'Rad',
+ "lastName": 'Radical',
+ "email": 'rad@radical.com'
+ }
+ };
+
+ function User(data) {
+ this.setData(data);
+ }
+
+ Tubbs(User, {
+ primaryKey: 'id',
+ dataStore: new Memory(User)
+ });
+
+ User.use(data, function() {
+ done();
+ });
+ });
+
it('should save and find data', function(done) {
function User(data) {
this.setData(data);

0 comments on commit a33ece2

Please sign in to comment.