Skip to content

Commit

Permalink
Add throw method as emit('error', err) shorcut
Browse files Browse the repository at this point in the history
  • Loading branch information
alsotang authored and JacksonTian committed Jun 15, 2015
1 parent ba69afa commit b31774c
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 1 deletion.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ results
node_modules
npm-debug.log
coverage
.DS_Store
2 changes: 2 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ language: node_js
node_js:
- "0.10"
- "0.11"
- "0.12"
- "iojs"
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,17 @@ ep.bind('error', function (err) {

`fail`方法侦听了`error`事件,默认处理卸载掉所有handler,并调用回调函数。

### 神奇的 throw

`throw``ep.emit('error', err)` 的简写。

```js
var err = new Error();
ep.throw(err);
// 实际是
ep.emit('error', err);
```

### 神奇的done

```js
Expand Down
12 changes: 12 additions & 0 deletions README_en.md
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,18 @@ ep.bind('error', function (err) {
`fail` method listens to `error` event, removes all handlers by default, then invoke callback method.
### Amazing `throw`
`throw` is a shortcut of `ep.emit('error', err)`.
```js
var err = new Error();
ep.throw(err);
// equals
ep.emit('error', err);
```
### Amazing `done`
```js
Expand Down
11 changes: 10 additions & 1 deletion lib/eventproxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,8 @@
*/
EventProxy.prototype.fail = function (callback) {
var that = this;
that.once('error', function (err) {

that.once('error', function () {
that.unbind();
// put all arguments to the error handler
// fail(function(err, args1, args2, ...){})
Expand All @@ -340,6 +341,14 @@
return this;
};

/**
* A shortcut of ep#emit('error', err)
*/
EventProxy.prototype.throw = function () {
var that = this;
that.emit.apply(that, ['error'].concat(SLICE.call(arguments)));
};

/**
* Assign some events, after all events were fired, the callback will be executed first time.
* Then any event that predefined be fired again, the callback will executed with the newest data.
Expand Down
11 changes: 11 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,17 @@ describe("EventProxy", function () {
done();
});
});

it('should work with ep#throw shortcut', function (done) {
var ep = new EventProxy();
ep.fail(function (err, arg1, arg2) {
err.should.be.Error;
arg1.should.be.String;
arg2.should.be.Number;
done();
});
ep.throw(new Error(), 'hello', 42);
});
});

describe('emit later', function () {
Expand Down

0 comments on commit b31774c

Please sign in to comment.