Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement Custom events with js

Shulou Source: shulou.com Published: 2022-06-03 07:35:21 11月03日 Update

This article focuses on "how to use js to achieve custom events", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to implement custom events with js".

1. Specify who is the publisher

2. Add a cache list to the publisher to store the callback to notify the subscriber.

3. When the message is published, the publisher will traverse the list and in turn trigger the subscriber callback function stored in it.

Example

Const salesOffices = {} / / define sales office salesOffices.clientList = [] / / cache list, store subscriber callback function salesOffices.listen = function (fn) {/ / add subscriber this.clientList.push (fn) / / add to cache list} salesOffices.trigger = function () {/ / publish message for (let I = 0, fn; fn = this.clientList [iTunes +] ) {fn.apply (this, arguments) / / arguments is the parameter}} / / Test salesOffices.listen ((price, squareMeter) = > {/ / Xiaoming subscription message console.log ('price =' + price) console.log ('squareMeter=' + squareMeter)}) salesOffices.listen ((price)) SquareMeter) = > {/ / Xiao Hong subscription message console.log ('price =' + price) console.log ('squareMeter=' + squareMeter)}) salesOffices.trigger (2000000, 88) salesOffices.trigger (3000000, 110) so far I believe you have a deeper understanding of "how to use js to achieve custom events". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Subscriptions messages subscribers events publishers caches prices content functions storage learning practicality deeper interests parameters sales offices examples practicality practicality simple operation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Huawei vpn Shulou Information Redmi