Add abilities to remove and clear observers - Operation Hooks.
This commit is contained in:
parent
159be756ac
commit
befe30f14a
24
lib/model.js
24
lib/model.js
|
@ -578,6 +578,30 @@ ModelBaseClass.observe = function(operation, 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.
|
||||
* @param {String} operation The operation name.
|
||||
|
|
|
@ -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) {
|
||||
TestModel.notifyObserversOf('no-observers', {}, function(err) {
|
||||
// the test passes when no error was raised
|
||||
|
|
Loading…
Reference in New Issue