diff --git a/lib/mixins/event.js b/lib/mixins/event.js index f17642f53c..0e8284d0f9 100644 --- a/lib/mixins/event.js +++ b/lib/mixins/event.js @@ -21,34 +21,38 @@ var EventMixin = { return this._super ? this._super.apply(this, arguments) : this; }, applyEvents:function(){ - var emitter = this._rubberDuck = rubberduck.emitter(this); - var self = this; - - self._serviceEvents = []; - - // Pass the Rubberduck error event through - // TODO deal with error events properly - emitter.on('error', function (errors) { - self.emit('serviceError', errors[0]); - }); - - _.each(eventMappings, function (event, method) { - if (typeof self[method] === 'function') { - // The Rubberduck event name (e.g. afterCreate, afterUpdate or afterDestroy) - var eventName = 'after' + method.charAt(0).toUpperCase() + method.substring(1); - self._serviceEvents.push(event); - // Punch the given method - emitter.punch(method, -1); - // Pass the event and error event through - emitter.on(eventName, function (results) { - if (!results[0]) { // callback without error - self.emit(event, results[1]); - } else { - self.emit('serviceError', results[0]); - } - }); - } - }); + // Don't run if the service already has _serviceEvents. + if (!this._serviceEvents) { + + var emitter = this._rubberDuck = rubberduck.emitter(this); + var self = this; + + self._serviceEvents = []; + + // Pass the Rubberduck error event through + // TODO deal with error events properly + emitter.on('error', function (errors) { + self.emit('serviceError', errors[0]); + }); + + _.each(eventMappings, function (event, method) { + if (typeof self[method] === 'function') { + // The Rubberduck event name (e.g. afterCreate, afterUpdate or afterDestroy) + var eventName = 'after' + method.charAt(0).toUpperCase() + method.substring(1); + self._serviceEvents.push(event); + // Punch the given method + emitter.punch(method, -1); + // Pass the event and error event through + emitter.on(eventName, function (results) { + if (!results[0]) { // callback without error + self.emit(event, results[1]); + } else { + self.emit('serviceError', results[0]); + } + }); + } + }); + } } };