EventBus implements communication between objects
directory
What is EventBus?
A simple example
Code Demo (using jquery)
Inherit EventBus using class encapsulation +
What is EventBus?
EventBus can communicate between objects and automatically listen for events to make changes when data or features change. There’s a lot more that I probably haven’t expanded on yet. How do you communicate? Here’s an example to get the gist of it.
A simple example
add(){
data+=1;
render(data);
},
minus(){
data-=1;
render(data);
},
multiply(){
data*=2;
render(data);
},
divide(){
data/=2;
render(data);
},
Copy the code
- The above code is the operation of addition, subtraction, multiplication and division. After the data data is changed, the data data is rendered and the rendering function is called
render()
; - Do you feel this is very troublesome, the code is very repetitive, but want to express the meaning is the same:
Render () is called once whenever data is updated
Here's the question:
Is there a way to simplify it? As long asThe data change
,Automatically call the render() function
Three, code demonstration examples
const eventbus=$({}); // Create an eventBus using the jQuery library.
let xx = {
data: {n:100,}}updata(data){
Object.assign(xx.data,data); // Batch assignment
eventbus.trigger('updataed:xx.data'); // Trigger an event named 'updataed:xx.data'
}
/* Call the jquer-wrapped event listener */
eventbus.on('updataed:xx.data'.() = >{
render(xx.data);
})
/* Improved addition, subtraction, multiplication, and division functions */
add(){
updata({n:xx.data.n+1});
},
minus(){
updata({n:xx.data.n-1});
},
multiply(){
updata({n:xx.data.n*2});
},
divide(){
updata({n:xx.data.n/2});
}
Copy the code
Eventbus.trigger ('updataed:xx.data') is triggered as soon as the updata() function is called, and the event listener is triggered, automatically calling the render() function to render
Class encapsulates and inherits EventBus
class EventBus{
constructor(){
this.eventbus=$(window); // Use jquery to mount eventBus to the global window
}
on(eventName,fn){
this.eventbus.on(eventName,fn);
}
trigger(eventName){
this.eventbus.trigger(eventName);
}
off(eventName,fn){
this.eventbus.off(eventName,fn); }}const eventbus=new EventBus();
eventbus.trigger('updated:xx.data')
eventbus.on('updated:xx.data'.() = >{
render(xx.data);
})
eventbus.off('updated:xx.data')
/* Inherit EventBus */
class module extends EventBus{
constructor(){
super(a);Constructor must be inherited from the parent class}}module.trigger('updated:xx.data')
module.on('updated:xx.data'.() = >{
render(xx.data);
})
module.off('updated:xx.data')
Copy the code
-
Why class encapsulate and inherit EventBus?
A: To make the code more formatted, you can use EventBus not only here, but also elsewhere. Especially in modular operations, encapsulation + inheritance is very important. This makes the code more maintainable. Other modules that use EventBus can have even more variations, overwriting parent methods or adding more methods.