Skip to content

Commit dad929d

Browse files
committed
docs(decorator): edit decorator/publishEvent
1 parent eeba198 commit dad929d

File tree

1 file changed

+29
-13
lines changed

1 file changed

+29
-13
lines changed

docs/decorator.md

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -476,15 +476,23 @@ person.facepalmWithoutWarning();
476476
我们可以使用修饰器,使得对象的方法被调用时,自动发出一个事件。
477477

478478
```javascript
479-
import postal from "postal/lib/postal.lodash";
479+
const postal = require("postal/lib/postal.lodash");
480480

481481
export default function publish(topic, channel) {
482+
const channelName = channel || '/';
483+
const msgChannel = postal.channel(channelName);
484+
msgChannel.subscribe(topic, v => {
485+
console.log('频道: ', channelName);
486+
console.log('事件: ', topic);
487+
console.log('数据: ', v);
488+
});
489+
482490
return function(target, name, descriptor) {
483491
const fn = descriptor.value;
484492

485493
descriptor.value = function() {
486494
let value = fn.apply(this, arguments);
487-
postal.channel(channel || target.channel || "/").publish(topic, value);
495+
msgChannel.publish(topic, value);
488496
};
489497
};
490498
}
@@ -495,29 +503,37 @@ export default function publish(topic, channel) {
495503
它的用法如下。
496504

497505
```javascript
498-
import publish from "path/to/decorators/publish";
506+
// index.js
507+
import publish from './publish';
499508

500509
class FooComponent {
501-
@publish("foo.some.message", "component")
510+
@publish('foo.some.message', 'component')
502511
someMethod() {
503-
return {
504-
my: "data"
505-
};
512+
return { my: 'data' };
506513
}
507-
@publish("foo.some.other")
514+
@publish('foo.some.other')
508515
anotherMethod() {
509516
// ...
510517
}
511518
}
519+
520+
let foo = new FooComponent();
521+
522+
foo.someMethod();
523+
foo.anotherMethod();
512524
```
513525

514526
以后,只要调用`someMethod`或者`anotherMethod`,就会自动发出一个事件。
515527

516-
```javascript
517-
let foo = new FooComponent();
518-
519-
foo.someMethod() // 在"component"频道发布"foo.some.message"事件,附带的数据是{ my: "data" }
520-
foo.anotherMethod() // 在"/"频道发布"foo.some.other"事件,不附带数据
528+
```bash
529+
$ bash-node index.js
530+
频道: component
531+
事件: foo.some.message
532+
数据: { my: 'data' }
533+
534+
频道: /
535+
事件: foo.some.other
536+
数据: undefined
521537
```
522538
523539
## Mixin

0 commit comments

Comments
 (0)