1
0
Fork 0

Before/After events at Repository.save method

This commit is contained in:
Hugo Sarti 2014-11-12 16:05:59 -03:00
parent 54812d1e02
commit 298f7dea1e
2 changed files with 51 additions and 4 deletions

View File

@ -130,8 +130,12 @@ _.extend(Repository.prototype, {
////////////////////////////////////////////////////////////////////////////////
save: function (model) {
'use strict';
model.emit('beforeCreate');
model.emit('beforeSave');
var id_and_rev = this.collection.save(model.forDB());
model.set(id_and_rev);
model.emit('afterSave');
model.emit('afterCreate');
return model;
},

View File

@ -1,14 +1,57 @@
/*global require, describe, expect, it */
/*global require, describe, expect, it, beforeEach, createSpyObj */
var Model = require("org/arangodb/foxx/model").Model;
var FoxxRepository = require("org/arangodb/foxx/repository").Repository,
Model = require("org/arangodb/foxx/model").Model;
describe('Model Events', function () {
'use strict';
var collection, instance;
beforeEach(function () {
collection = createSpyObj('collection', [
'save'
]);
instance = new Model({ random: '', beforeCalled: false, afterCalled: false });
});
it('should be possible to subscribe and emit events', function () {
var instance = new Model();
expect(instance.on).toBeDefined();
expect(instance.emit).toBeDefined();
});
});
it('should emit beforeCreate and afterCreate events when creating the model', function () {
var repository = new FoxxRepository(collection, {model: Model});
addHooks(instance, 'Create');
expect(repository.save(instance)).toEqual(instance);
expect(instance.get('beforeCalled')).toBe(true);
expect(instance.get('afterCalled')).toBe(true);
});
it('should emit beforeSave and afterSave events when creating the model', function () {
var repository = new FoxxRepository(collection, {model: Model});
addHooks(instance, 'Save');
expect(repository.save(instance)).toEqual(instance);
expect(instance.get('beforeCalled')).toBe(true);
expect(instance.get('afterCalled')).toBe(true);
});
});
function addHooks(model, ev) {
'use strict';
var random = String(Math.floor(Math.random() * 1000));
model.on('before' + ev, function () {
expect(this).toEqual(model);
this.set('random', random);
this.set('beforeCalled', true);
});
model.on('after' + ev, function () {
expect(this).toEqual(model);
this.set('afterCalled', true);
expect(this.get('beforeCalled')).toBe(true);
expect(this.get('random')).toEqual(random);
});
}