DRY up event target implementations

Dedupe event target code and make it extensible.

// FREEBIE
This commit is contained in:
lilia 2016-01-14 14:07:00 -08:00
parent 925c1bdb33
commit f7c4fd2fed
5 changed files with 176 additions and 228 deletions

View file

@ -19,10 +19,11 @@
sender.sendRequestContactSyncMessage().then(function() {
sender.sendRequestGroupSyncMessage();
});
this.timeout = setTimout(this.onTimeout.bind(this), 60000);
this.timeout = setTimeout(this.onTimeout.bind(this), 60000);
}
SyncRequest.prototype = {
SyncRequest.prototype = new textsecure.EventTarget();
SyncRequest.prototype.extend({
constructor: SyncRequest,
onContactSyncComplete: function() {
this.contactSync = true;
@ -47,62 +48,8 @@
this.receiver.removeEventListener('contactsync', this.oncontact);
this.receiver.removeEventListener('groupSync', this.ongroup);
delete this.listeners;
},
/* Implements EventTarget */ /// TODO: Dedupe this same code in MessageReceiver
dispatchEvent: function(ev) {
if (!(ev instanceof Event)) {
throw new Error('Expects an event');
}
if (this.listeners === null || typeof this.listeners !== 'object') {
this.listeners = {};
}
var listeners = this.listeners[ev.type];
if (typeof listeners === 'object') {
for (var i=0; i < listeners.length; ++i) {
if (typeof listeners[i] === 'function') {
listeners[i].call(null, ev);
}
}
}
},
addEventListener: function(eventName, callback) {
if (typeof eventName !== 'string') {
throw new Error('First argument expects a string');
}
if (typeof callback !== 'function') {
throw new Error('Second argument expects a function');
}
if (this.listeners === null || typeof this.listeners !== 'object') {
this.listeners = {};
}
var listeners = this.listeners[eventName];
if (typeof listeners !== 'object') {
listeners = [];
}
listeners.push(callback);
this.listeners[eventName] = listeners;
},
removeEventListener: function(eventName, callback) {
if (typeof eventName !== 'string') {
throw new Error('First argument expects a string');
}
if (typeof callback !== 'function') {
throw new Error('Second argument expects a function');
}
if (this.listeners === null || typeof this.listeners !== 'object') {
this.listeners = {};
}
var listeners = this.listeners[eventName];
for (var i=0; i < listeners.length; ++ i) {
if (listeners[i] === callback) {
listeners.splice(i, 1);
return;
}
}
this.listeners[eventName] = listeners;
}
};
});
textsecure.SyncRequest = function(sender, receiver) {
var syncRequest = new SyncRequest(sender, receiver);