Skip to content

Commit

Permalink
Code cleanup for Observer class (katspaugh#2041)
Browse files Browse the repository at this point in the history
* Initialize handlers dictionary in constructor and remove conditional assignment

* reset handlers to empty object in unAll

* strict equality check, add type hint comments and cleanup some code
  • Loading branch information
sundayz authored Aug 14, 2020
1 parent 97ec876 commit 590d9cc
Showing 1 changed file with 13 additions and 23 deletions.
36 changes: 13 additions & 23 deletions src/util/observer.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,17 @@ export default class Observer {
*/
constructor() {
/**
* @type {string[]}
* @private
* @todo Initialise the handlers here already and remove the conditional
* assignment in `on()`
*/
this._disabledEventEmissions = [];
this.handlers = null;

/**
* @type {Object.<string, Function[]>} Map of event name to array of handler functions
*/
this.handlers = {};
}

/**
* Attach a handler function for an event.
*
Expand All @@ -29,10 +33,6 @@ export default class Observer {
* @return {ListenerDescriptor} The event descriptor
*/
on(event, fn) {
if (!this.handlers) {
this.handlers = {};
}

let handlers = this.handlers[event];
if (!handlers) {
handlers = this.handlers[event] = [];
Expand All @@ -55,16 +55,11 @@ export default class Observer {
* @param {function} fn The callback that should be removed
*/
un(event, fn) {
if (!this.handlers) {
return;
}

const handlers = this.handlers[event];
let i;
if (handlers) {
if (fn) {
for (i = handlers.length - 1; i >= 0; i--) {
if (handlers[i] == fn) {
for (let i = handlers.length - 1; i >= 0; i--) {
if (handlers[i] === fn) {
handlers.splice(i, 1);
}
}
Expand All @@ -78,7 +73,7 @@ export default class Observer {
* Remove all event handlers.
*/
unAll() {
this.handlers = null;
this.handlers = {};
}

/**
Expand All @@ -94,9 +89,7 @@ export default class Observer {
/* eslint-disable no-invalid-this */
handler.apply(this, args);
/* eslint-enable no-invalid-this */
setTimeout(() => {
this.un(event, fn);
}, 0);
setTimeout(() => this.un(event, fn), 0);
};
return this.on(event, fn);
}
Expand Down Expand Up @@ -131,14 +124,11 @@ export default class Observer {
* @param {...any} args The arguments with which to call the listeners
*/
fireEvent(event, ...args) {
if (!this.handlers || this._isDisabledEventEmission(event)) {
if (this._isDisabledEventEmission(event)) {
return;
}

const handlers = this.handlers[event];
handlers &&
handlers.forEach(fn => {
fn(...args);
});
handlers && handlers.forEach(fn => fn(...args));
}
}

0 comments on commit 590d9cc

Please sign in to comment.