Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,25 @@ EventBus.dispatch(type, target, args ...)

### `getEvents`

For debugging purpose, it prints out the added listeners.
For debugging purposes, it prints out the added listeners.

```js
EventBus.getEvents()
```


### `watch`

For debugging purposes, add callbacks to fire when events are dispatched.

```js
var onDispatch = function(type) { console.log("[EventBus] Dispatching: " + type) }
var onCallback = function(type) { console.log("[EventBus] Handling: " + type) }
var onAdd = function(type) { console.log("[EventBus] Adding Listener: " + type) }
var onRemove = function(type) { console.log("[EventBus] Removing Listener: " + type) }
EventBus.watch(onDispatch, onCallback, onAdd, onRemove)
```

## Usage

```js
Expand Down
18 changes: 17 additions & 1 deletion src/EventBus.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@
var EventBusClass = {};
EventBusClass = function() {
this.listeners = {};
this.watchers = { onDispatch: null, onCallback: null, onAdd: null, onRemove: null };
};
EventBusClass.prototype = {
addEventListener: function(type, callback, scope) {
if (this.watchers.onAdd != null) this.watchers.onAdd(type);

var args = [];
var numOfArgs = arguments.length;
for(var i=0; i<numOfArgs; i++){
Expand All @@ -28,6 +31,8 @@
}
},
removeEventListener: function(type, callback, scope) {
if (this.watchers.onRemove != null) this.watchers.onRemove(type);

if(typeof this.listeners[type] != "undefined") {
var numOfCallbacks = this.listeners[type].length;
var newArray = [];
Expand Down Expand Up @@ -58,6 +63,8 @@
return false;
},
dispatch: function(type, target) {
if (this.watchers.onDispatch != null) this.watchers.onDispatch(type);

var event = {
type: type,
target: target
Expand All @@ -77,6 +84,7 @@
for(var i=0; i<numOfCallbacks; i++) {
var listener = listeners[i];
if(listener && listener.callback) {
if (this.watchers.onCallback != null) this.watchers.onCallback(type);
var concatArgs = args.concat(listener.args);
listener.callback.apply(listener.scope, concatArgs);
}
Expand All @@ -94,7 +102,15 @@
}
}
return str;
}
},
watch: function(onDispatch, onCallback, onAdd, onRemove) {
this.watchers = {
onDispatch: onDispatch,
onCallback: onCallback,
onAdd: onAdd,
onRemove: onRemove
};
}
};
var EventBus = new EventBusClass();
return EventBus;
Expand Down