The event
Events are the primary way in which javascript interacts with the browser. Events are a design pattern called observer, which is a technique for creating loosely coupled code. Objects can publish events that indicate an interesting time in the object’s life cycle. Other objects can then watch the object, wait for these interesting moments and respond by running code.
Observer model
The observer pattern consists of two types of objects, subjects and observers. The principal is responsible for publishing events, and observers observe the principal by subscribing to these events. A key concept of this model is that the subject knows nothing about the observer, that is, it can exist on its own and function without the observer. On the other hand, the observer knows the body and can register the event’s callback function. When it comes to the DOM, the DOM is the subject and your event handling code is the observer.
Custom events
concept
Now that we know the basic concept of events, we know what custom events are: the concept is to create an object that manages events and have other objects listen for those events
Code implementation
EventBus.js
function EventTarget() {
Handlers are used to store event handlers
this.handlers = {};
}
EventTarget.prototype = {
constructor: EventTarget,
/ * * *@name: addHandler Registers the event handler * for the given event@msgWhen this method is called, a check is made to see if an array of the event type already exists in the Handlers property; if not, a new array is created and the handler is added to the end of the array using push *@param {*} Type Indicates the event type *@param {*} Handler The function */ that handles the event
addHandler: function (type, handler) {
if (typeof this.handlers[type] === "undefined") {
this.handlers[type] = [];
}
this.handlers[type].push(handler);
},
/ * * *@name: fire is used to trigger an event *@msg: Gives the event object a target property if it is not already specified * then looks up a set of handlers for the corresponding event class, calls each function, and gives the event object *@param {*} Event contains at least the */ attribute object of type
fire: function (event) {
if(! event.target) { event.target =this;
}
if (this.handlers[event.type] instanceof Array) {
var handlers = this.handlers[event.type];
for (let i = 0, len = handlers.length; i < len; i++) {
handlers[i](event)
}
}
},
/ * * *@nameRemoveHandler is an aid to the addHandler method, which takes the same arguments *@msg: Searches the array of event handlers to find the location of the handler to delete, and then deletes *@param {*} Type Indicates the event type *@param {*} Handler The program that processes events */
removeHandler: function (type, handler) {
if (this.handlers[type] instanceof Array) {
var handlers = this.handlers[type];
for (var i = 0, len = handlers.length; i < len; i++) {
if (handlers[i] === handler)
break;
}
handlers.splice(i, 1)}}}export default new EventTarget();
Copy the code
- We implemented it in the above files
EventTarget
, corresponding methodaddHandler
Register/subscribe to events,fire
Trigger event,removeHandler
Delete events
The React to implement
File directory
| | - App. Js # root components - pages | -- - | -- login. Js # login page | - EventBus | -- - | -- index. Js # event bus file... Other documents will not be described...Copy the code
The test method
To make it easier to post the code, I wrote two test components in login.js page. Instead of sending values through login, component A subscribes to events, and component B fires
login.js
import React from 'react';
import EventBus from ".. /EventBus";
export default() = > {return (
<React.Fragment>
<div>The login module<Com1 />
<Com2 />
</div>
</React.Fragment>)}function Com1() {
// Trigger the event
function emit() {
EventBus.fire({
type: "login".data: { code: "200".massage: "Login successful"}})}return (
<React.Fragment>
<div>COM1</div>
<button onClick={emit}>Com1 is triggered</button>
</React.Fragment>)}function Com2() {
React.useEffect(() = > {
// Register/subscribe to events
EventBus.addHandler("login".(event) = > {
console.log(event.data, "[COM2 module accepted]")})return () = > EventBus.removeHandler('login'.null)}, []);return (
<React.Fragment>
<div>
COM2
</div>
</React.Fragment>)}Copy the code
- As above, I am
Com2
The component is mounted and subscribedlogin
The event,Com1
Is triggered by a click eventlogin
Event, let’s take a look at the effect screenshot.
- We are in
React
To achieve a custom event bus value
Vue implemented
File directory
| | - App. Vue # root components - component | -- - | -- Sidebar. Vue # Sidebar components | -- - | -- Header. Vue # page head component | - EventBus | -- - | -- - Index.js # event bus file... Other documents will not be described...Copy the code
The test method
I’m going to clickHeader
Component button A pairSideBar
Component’s fold/expand function to test custom events inVue
The implementation in
// Paste only relevant code
Sidebar.vue
created() {
// Register/subscribe to collapse events after component instance creation
EventBus.addHandler('collapse'.(event) = > {
this.collapse = event.data;
});
}
Header.vue
// The click event for the sidebar collapse button A
collapseChage() {
this.collapse = !this.collapse;
EventBus.fire({ type: 'collapse'.data: this.collapse });
},
Copy the code
- As above, I am
SideBar
Register the subscription after the instance is createdcollapse
Event in the componentHeader
Triggered by the component midpoint button A click eventcollapse
The event
- We are in
Vue
To achieve a custom event bus value
Conceptual text references JavaScript Advanced Programming
The above