Merge pull request #500 from 0angelic0/master

Remove and clear Operation Hook observers
This commit is contained in:
Miroslav Bajtoš 2015-03-30 11:26:57 +02:00
commit 517ea875ec
2 changed files with 62 additions and 0 deletions

View File

@ -600,6 +600,30 @@ ModelBaseClass.observe = function(operation, listener) {
this._observers[operation].push(listener); this._observers[operation].push(listener);
}; };
/**
* Unregister an asynchronous observer for the given operation (event).
* @param {String} operation The operation name.
* @callback {function} listener The listener function.
* @end
*/
ModelBaseClass.removeObserver = function(operation, listener) {
if (!this._observers[operation]) return;
var index = this._observers[operation].indexOf(listener);
if (index != -1) this._observers[operation].splice(index, 1);
};
/**
* Unregister all asynchronous observers for the given operation (event).
* @param {String} operation The operation name.
* @end
*/
ModelBaseClass.clearObservers = function(operation) {
if (!this._observers[operation]) return;
this._observers[operation].length = 0;
};
/** /**
* Invoke all async observers for the given operation. * Invoke all async observers for the given operation.
* @param {String} operation The operation name. * @param {String} operation The operation name.

View File

@ -79,6 +79,44 @@ describe('async observer', function() {
}); });
}); });
it('can remove observers', function(done) {
var notifications = [];
function call(ctx, next) {
notifications.push('call');
process.nextTick(next);
};
TestModel.observe('event', call);
TestModel.removeObserver('event', call);
TestModel.notifyObserversOf('event', {}, function(err) {
if (err) return done(err);
notifications.should.eql([]);
done();
});
});
it('can clear all observers', function(done) {
var notifications = [];
function call(ctx, next) {
notifications.push('call');
process.nextTick(next);
};
TestModel.observe('event', call);
TestModel.observe('event', call);
TestModel.observe('event', call);
TestModel.clearObservers('event');
TestModel.notifyObserversOf('event', {}, function(err) {
if (err) return done(err);
notifications.should.eql([]);
done();
});
});
it('handles no observers', function(done) { it('handles no observers', function(done) {
TestModel.notifyObserversOf('no-observers', {}, function(err) { TestModel.notifyObserversOf('no-observers', {}, function(err) {
// the test passes when no error was raised // the test passes when no error was raised