Skip to content

Commit

Permalink
Add: Console events #66
Browse files Browse the repository at this point in the history
  • Loading branch information
surunzi committed May 24, 2018
1 parent 1cb8ab6 commit 71ae5d0
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
8 changes: 7 additions & 1 deletion doc/TOOL_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,19 @@ console.config.set('catchGlobalErr', true);

### log, error, info, warn, dir, time/timeEnd, clear, count, assert, table

All these methods can be used in the same way as window.console object.
All these methods can be used in the same way as window.console object.

Note: When called, a corresponding event is triggered.

```javascript
var console = eruda.get('console');
console.log('eruda is a console for %s.', 'mobile browsers');
console.table([{test: 1}, {test: 2}, {test2: 3}], 'test');
console.error(new Error('eruda'));
console.on('log', function ()
{
// Do whatever you want, send to server or save on local storage.
});
```

### filter
Expand Down
10 changes: 6 additions & 4 deletions src/Console/Console.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Logger from './Logger';
import Tool from '../DevTools/Tool';
import {noop, evalCss, $} from '../lib/util';
import {noop, evalCss, $, Emitter} from '../lib/util';
import emitter from '../lib/emitter';
import Settings from '../Settings/Settings';
import stringify from './stringify';
Expand All @@ -11,6 +11,8 @@ export default class Console extends Tool
{
super();

Emitter.mixin(this);

this.name = 'console';
this._scale = 1;

Expand All @@ -37,8 +39,7 @@ export default class Console extends Tool
}
overrideConsole()
{
let logger = this._logger,
origConsole = this._origConsole = {},
let origConsole = this._origConsole = {},
winConsole = window.console;

CONSOLE_METHOD.forEach(name =>
Expand All @@ -48,7 +49,7 @@ export default class Console extends Tool

winConsole[name] = (...args) =>
{
logger[name](...args);
this[name](...args);
origin(...args);
};
});
Expand Down Expand Up @@ -142,6 +143,7 @@ export default class Console extends Tool
methods.forEach(name => this[name] = (...args) =>
{
logger[name](...args);
this.emit(name, ...args);

return this;
});
Expand Down
17 changes: 17 additions & 0 deletions test/console.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,4 +278,21 @@ describe('console', function ()
expect($tool.find('.eruda-logs li')).toHaveLength(1);
});
});

describe('events', function ()
{
it('log', function ()
{
var sum = 0;
function add(num) { sum += num; }
tool.on('log', add);
tool.log(5);
expect(sum).toBe(5);
tool.log(6);
expect(sum).toBe(11);
tool.off('log', add);
tool.log(1);
expect(sum).toBe(11);
});
});
});

0 comments on commit 71ae5d0

Please sign in to comment.