日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

如何正确使用Node.js中的事件

發(fā)布時(shí)間:2023/11/29 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何正确使用Node.js中的事件 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

by Usama Ashraf

通過(guò)Usama Ashraf

如何正確使用Node.js中的事件 (How to use events in Node.js the right way)

Before event-driven programming became popular, the standard way to communicate between different parts of an application was pretty straightforward: a component that wanted to send out a message to another one explicitly invoked a method on that component. But event-driven code is written to react rather than be called.

在事件驅(qū)動(dòng)的編程流行之前,在應(yīng)用程序的不同部分之間進(jìn)行通信的標(biāo)準(zhǔn)方法非常簡(jiǎn)單:一個(gè)組件希望向另一個(gè)發(fā)出消息,而該組件顯式調(diào)用了該組件上的方法。 但是事件驅(qū)動(dòng)的代碼是為了響應(yīng)而不是被調(diào)用而編寫的。

比賽的好處 (The Benefits Of Eventing)

This approach causes our components to be much more decoupled. As we continue to write an application, we identify events along the way. We fire them at the right time and attach one or more event listeners to each one. Extending functionality becomes much easier. We can add on more listeners to a particular event. We are not tampering with the existing listeners or the part of the application where the event was fired from. What we’re talking about is the Observer pattern.

這種方法使我們的組件更加分離 。 在繼續(xù)編寫應(yīng)用程序的過(guò)程中,我們一路確定事件。 我們?cè)谶m當(dāng)?shù)臅r(shí)間解雇它們,并將一個(gè)或多個(gè)事件偵聽(tīng)器附加到每個(gè)偵聽(tīng)器 。 擴(kuò)展功能變得容易得多。 我們可以為特定事件添加更多的偵聽(tīng)器。 我們不會(huì)篡改現(xiàn)有的偵聽(tīng)器或觸發(fā)事件的應(yīng)用程序部分。 我們正在談?wù)摰氖怯^察者模式。

設(shè)計(jì)事件驅(qū)動(dòng)的體系結(jié)構(gòu) (Designing An Event-Driven Architecture)

Identifying events is pretty important. We don’t want to end up having to remove/replace existing events from the system. This might force us to delete/modify any number of listeners that were attached to the event. The general principle I use is to consider firing an event only when a unit of business logic finishes execution.

識(shí)別事件非常重要。 我們不想最終不得不從系統(tǒng)中刪除/替換現(xiàn)有事件。 這可能迫使我們刪除/修改附加到該事件的任意數(shù)量的偵聽(tīng)器。 我使用的一般原則是僅在業(yè)務(wù)邏輯單元完成執(zhí)行時(shí)才考慮觸發(fā)事件。

So say you want to send out a bunch of different emails after a user’s registration. Now, the registration process itself might involve many complicated steps, and queries. But from a business point of view, it is one step. And each of the emails to be sent out are individual steps as well. So it would make sense to fire an event as soon as registration finishes. We have multiple listeners attached to it, each responsible for sending out one type of email.

假設(shè)您要在用戶注冊(cè)后發(fā)送大量不同的電子郵件。 現(xiàn)在,注冊(cè)過(guò)程本身可能涉及許多復(fù)雜的步驟和查詢。 但是從業(yè)務(wù)角度來(lái)看,這只是一步。 而且,要發(fā)送的每封電子郵件都是單獨(dú)的步驟。 因此,在注冊(cè)完成后立即觸發(fā)事件是很有意義的。 我們具有多個(gè)偵聽(tīng)器,每個(gè)偵聽(tīng)器負(fù)責(zé)發(fā)送一種電子郵件。

Node’s asynchronous, event-driven architecture has certain kinds of objects called “emitters.” They emit named events which cause functions called “l(fā)isteners” to be invoked. All objects that emit events are instances of the EventEmitter class. Using it, we can create our own events:

Node的異步事件驅(qū)動(dòng)架構(gòu)具有某些稱為“發(fā)射器”的對(duì)象。 它們發(fā)出命名事件,這些事件導(dǎo)致稱為“偵聽(tīng)器”的函數(shù)被調(diào)用。 所有發(fā)出事件的對(duì)象都是EventEmitter類的實(shí)例。 使用它,我們可以創(chuàng)建自己的事件:

一個(gè)例子 (An Example)

Let’s use the built-in events module (which I encourage you to check out in detail) to gain access to EventEmitter.

讓我們使用內(nèi)置的事件模塊(我建議您詳細(xì)檢查該模塊)來(lái)訪問(wèn)EventEmitter 。

This is the part of the application where our server receives an HTTP request, saves a new user and emits an event:

這是服務(wù)器接收HTTP請(qǐng)求,保存新用戶并發(fā)出事件的應(yīng)用程序的一部分:

And a separate module where we attach a listener:

還有一個(gè)單獨(dú)的模塊,我們?cè)谄渲懈郊恿艘粋€(gè)偵聽(tīng)器:

It’s a good practice to separate policy from implementation. In this case policy means which listeners are subscribed to which events. Implementation means the listeners themselves.

將政策與實(shí)施分開(kāi)是一個(gè)好習(xí)慣。 在這種情況下,策略意味著哪些偵聽(tīng)器訂閱了哪些事件。 實(shí)現(xiàn)是指?jìng)陕?tīng)器本身。

This separation allows for the listener to become re-usable too. It can be attached to other events that send out the same message (a user object). It’s also important to mention that when multiple listeners are attached to a single event, they will be executed synchronously and in the order that they were attached. Hence someOtherListener will run after sendEmailOnRegistration finishes execution.

這種分離也使偵聽(tīng)器也可以重用。 它可以附加到發(fā)出相同消息的其他事件(用戶對(duì)象)。 同樣重要的是要提到, 當(dāng)多個(gè)偵聽(tīng)器附加到一個(gè)事件時(shí),它們將按照附加的順序同步執(zhí)行 。 因此, someOtherListener將在sendEmailOnRegistration完成執(zhí)行之后運(yùn)行。

However, if you want your listeners to run asynchronously you can simply wrap their implementations with setImmediate like this:

但是,如果您希望監(jiān)聽(tīng)器異步運(yùn)行,則可以使用setImmediate包裝它們的實(shí)現(xiàn),如下所示:

保持聽(tīng)眾干凈 (Keep Your Listeners Clean)

Stick to the Single Responsibility Principle when writing listeners. One listener should do one thing only and do it well. Avoid, for instance, writing too many conditionals within a listener that decide what to do depending on the data (message) that was transmitted by the event. It would be much more appropriate to use different events in that case:

編寫偵聽(tīng)器時(shí),請(qǐng)遵循“單一責(zé)任原則”。 一個(gè)聽(tīng)眾應(yīng)該只做一件事,并且做好。 例如,避免在偵聽(tīng)器中編寫太多條件,以根據(jù)事件傳輸?shù)臄?shù)據(jù)(消息)來(lái)決定要做什么。 在這種情況下,使用不同的事件會(huì)更合適:

在必要時(shí)明確分離偵聽(tīng)器 (Detaching Listeners Explicitly When Necessary)

In the previous example, our listeners were totally independent functions. But in cases where a listener is associated with an object (it’s a method), it has to be manually detached from the events it had subscribed to. Otherwise, the object will never be garbage-collected since a part of the object (the listener) will continue to be referenced by an external object (the emitter). Thus the possibility of a memory leak.

在前面的示例中,我們的偵聽(tīng)器是完全獨(dú)立的功能。 但是,如果偵聽(tīng)器與對(duì)象(這是一種方法)相關(guān)聯(lián),則必須將其與已訂閱的事件手動(dòng)分離。 否則,該對(duì)象將永遠(yuǎn)不會(huì)被垃圾回收,因?yàn)樵搶?duì)象的一部分(偵聽(tīng)器)將繼續(xù)被外部對(duì)象(發(fā)射器)引用。 因此存在內(nèi)存泄漏的可能性。

For example, if we’re building a chat application and we want the responsibility for showing a notification when a new message arrives in a chat room that a user has connected to should lie within that user object itself, we might do this:

例如,如果我們正在構(gòu)建一個(gè)聊天應(yīng)用程序,并且我們希望當(dāng)用戶連接到的新消息到達(dá)聊天室時(shí),負(fù)責(zé)顯示通知的責(zé)任應(yīng)該位于該用戶對(duì)象本身內(nèi),我們可以這樣做:

When the user closes his/her tab or loses their internet connection for a while, naturally, we might want to fire a callback on the server-side that notifies the other users that one of them just went offline. At this point, of course, it doesn’t make any sense for displayNewMessageNotification to be invoked for the offline user. It will continue to be called on new messages unless we remove it explicitly. If we don’t, aside from the unnecessary call, the user object will also stay in memory indefinitely. So be sure to call disconnectFromChatroom in your server-side callback that executes whenever a user goes offline.

當(dāng)用戶關(guān)閉其選項(xiàng)卡或暫時(shí)失去其互聯(lián)網(wǎng)連接時(shí),自然地,我們可能希望在服務(wù)器端觸發(fā)回調(diào),以通知其他用戶其中一個(gè)剛下線。 當(dāng)然,在這一點(diǎn)上,為脫機(jī)用戶調(diào)用displayNewMessageNotification沒(méi)有任何意義。 除非我們明確刪除它,否則它將繼續(xù)在新消息上被調(diào)用。 如果我們不這樣做,除了不必要的調(diào)用之外,用戶對(duì)象還將無(wú)限期地保留在內(nèi)存中。 因此,請(qǐng)確保在用戶下線時(shí)執(zhí)行的服務(wù)器端回調(diào)中調(diào)用disconnectFromChatroom 。

謹(jǐn)防 (Beware)

The loose coupling in event-driven architectures can also lead to increased complexity if we’re not careful. It can be difficult to keep track of dependencies in our system. Our application will become especially prone to this problem if we start emitting events from within listeners. This could possibly trigger chains of unexpected events.

如果我們不小心,事件驅(qū)動(dòng)的體系結(jié)構(gòu)中的松散耦合也會(huì)導(dǎo)致復(fù)雜性的增加。 跟蹤我們系統(tǒng)中的依賴關(guān)系可能很困難。 如果我們開(kāi)始從偵聽(tīng)器內(nèi)部發(fā)出事件,我們的應(yīng)用程序?qū)⑻貏e容易出現(xiàn)此問(wèn)題。 這可能會(huì)觸發(fā)一系列意外事件。

翻譯自: https://www.freecodecamp.org/news/using-events-in-node-js-the-right-way-fc50c060f23b/

總結(jié)

以上是生活随笔為你收集整理的如何正确使用Node.js中的事件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。