Skip to content

Commit

Permalink
Add eTypes with event
Browse files Browse the repository at this point in the history
  • Loading branch information
Quinten committed Aug 20, 2024
1 parent 1f2e783 commit 96e1635
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 17 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ https://en.wikipedia.org/wiki/Web_colors
- 4267 / 13312
- 4315 / 13312
- 4313 / 13312
- 4311 / 13312
24 changes: 15 additions & 9 deletions game/js/events.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
export default () => {
export default (obj = {}, eTypes = []) => {

let listeners = {};

let on = (type, callback) => {
obj.on = (type, callback) => {
if (!listeners[type]) {
listeners[type] = [];
}
listeners[type].push(callback);
};

let off = (type, callback) => {
obj.off = (type, callback) => {
if (!type && !callback) {
listeners = {};
return;
Expand All @@ -29,17 +29,17 @@ export default () => {
}
};

let once = (type, callback) => {
obj.once = (type, callback) => {
let disposableCallback = e => {
callback(e);
off(type, disposableCallback);
obj.off(type, disposableCallback);
};
on(type, disposableCallback);
obj.on(type, disposableCallback);
};

let lastEmission = {};

let emit = (type, e = {}) => {
obj.emit = (type, e = {}) => {
if (lastEmission[type]) {
Object.assign(lastEmission[type], e);
} else {
Expand All @@ -50,12 +50,18 @@ export default () => {
}
};

let last = (type) => {
obj.last = (type) => {
if (!lastEmission[type]) {
return {};
}
return lastEmission[type];
};

return {on, off, once, emit, last};
eTypes.forEach(eType => {
obj[eType] = e => {
obj.emit(eType, e);
};
});

return obj;
};
9 changes: 1 addition & 8 deletions game/js/statemachine/state.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import events from '../events.js';
export default () => {
let active = false;
let {on, off, once, emit, last} = events();
let state = {
on, off, once, emit, last,
get active() {
return active;
},
Expand All @@ -16,11 +14,6 @@ export default () => {
}
}
};
let eTypes = ['start', 'stop'];
eTypes.forEach(eType => {
state[eType] = e => {
state.emit(eType, e);
};
});
events(state, ['start', 'stop']);
return state;
};

0 comments on commit 96e1635

Please sign in to comment.