Mixins.Mediator Class
The Mediator utility as a mixin
Item Index
Methods
Methods
publish
(
This
-
channel -
data
Allows to publish information through a channel of the mediator
Parameters:
-
channelStringThe channel to publish information through
-
dataThe data to send through
Returns:
This:
The instance
Example:
import Mediator from './mixins/mediator';
const MyClass = Mediator(class {
constructor() {}
});
let myInstance = new MyClass();
myInstance.publish('channelName', 'foo');
subscribe
(
String
-
channel -
handler
Allows to subscribe to a channel
Parameters:
-
channelStringThe channel to subscribe to
-
handlerFunctionA handler function for incoming data
Returns:
String:
A subscription identifier
Example:
import Mediator from './mixins/mediator';
const Foo = Mediator(class {
constructor() {
this.subscribe('BarChannel', this.handleBar, this);
}
handleBar(data) {
console.log('Foo received:', data);
}
})
const Bar = Mediator(class {
constructor() {
this.subscribe('FooChannel', this.handleFoo, this);
}
handleFoo(data) {
console.log('Bar received:', data);
}
});
let foo = new Foo();
let bar = new Bar();
foo.publish('FooChannel', 'Info from Foo');
// logs "Bar received: Info from Foo"
bar.publish('BarChannel', 'Info from Bar');
// logs "Foo received: Info from Bar"
unsubscribe
(
Boolean
-
identifier
Allows to subscribe to a channel
Parameters:
-
identifierStringA subscription ID returned from subscribe()
Returns:
Boolean:
True on success, false on failure
Example:
import Mediator from './mixins/mediator';
const Foo = Mediator(class {
constructor() {
this.listens = this.subscribe('self', this.handler, this);
}
handler(data) {
console.log('Foo received:', data);
}
unlisten() {
return this.unsubscribe(this.listens);
}
})
let foo = new Foo();
foo.publish('self', 1);
// logs "Foo received: 1"
foo.unlisten()
foo.publish('self', 1);
// nothing happens
