"JavaScript" lets events support post-release subscriptions

Source: Internet
Author: User

Previously written an event manager, is the normal first-subscription post-release mode. But in the actual scenario we need to be able to subscribe to the post also receive the message. For example, we are concerned about the public number, or can see historical news. Similar to the QQ offline message, I sent you first, you log on to receive. is to ensure that the method that subscribes to the event can be executed .

 varEventmanger ={cached: {}, Handlers: {},//type, binding eventAddHandler:function(type, handler) {if(typeofHandler!== "function")return; if(typeof  This. handlers[type] = = "undefined") {                 This. handlers[type] = []; }             This. Handlers[type].push (handler);  if (this. Cached[type] instanceof  Array) {  // indicates that a cache can be Row handler.apply (null,   this . Cached[type]); } }, RemoveHandler:function(type, handler) {varEvents = This. Handlers[type];  for(vari = 0, len = events.length; i < Len; i++) {                if(Events[i] = =handler) {Events.splice (i,1);  Break; }}, Trigger:function(type) {//If there is a subscription event, this is the time to trigger the            if( This. Handlers[type]instanceofArray) {                varHandlers = This. Handlers[type]; varargs = Array.prototype.slice.call (arguments, 1);  for(vari = 0, len = handlers.length; i < Len; i++) {handlers[i].apply (NULL, args); }            }            //Default Cache            This  . Cached[type] = Array.prototype.slice.call (arguments, 1); }    };

It's actually adding a few lines of code. The parameters of the cache at the time of the last trigger. Then in the addhandle when the judgment, if the subscription time has been cached parameters, indicating that the method can be executed.

function (res) {    Console.log ("Subscribe first, post 1", res);}) Eventmanger.trigger ("test", 2); Eventmanger.addhandler (function  (res) {    Console.log ("first post, after subscription 2", res);}) Eventmanger.addhandler (function  (res) {    Console.log ("Post first, post subscription 3", res);})

My actual scenario is that after the a event is triggered, the B method can be executed. However, the B method needs to be completed after the C method. That is, B relies on the completion of A and C. And a almost every time will be triggered quickly, of course, you can set two switch variables and a proxy function, and so on after two events are completed and then do B. The code is as follows:

varAready =false;varCready =false; Eventmanger.addhandler ("A",function() {Aready=true; Console.log ("Do A"); PROXYC ();}); Eventmanger.trigger ("A", 2);functionDoB () {Console.log ("Do B"); //the method in actual B needs to be executed after the A event succeeds}functionDoC () {Console.log ("Do C"); Cready=true; PROXYC ();}functionProxyc () {Aready&& Cready &&DoB ();} DoC ();

This function is implemented, but the readability is poor, and the event subscription must be to the location, if before trigger, DOB will never execute, and the code is more than two variables and a method, the most silly is to use a variable plus settimeout to judge the state, which may fall into a dead loop.

varAready =false; Eventmanger.addhandler ("A",function() {Aready=true; Console.log ("Do A");});functionDoB () {Console.log ("Do B"); //the method in actual B needs to be executed after the A event succeeds}functionDoC () {Console.log ("Do C"); if(!aready) {Console.log ("Wating ..."); setTimeout (DoC,  -); return; } DoB ();} DoC (); Eventmanger.trigger ("A", 2);//analog A event triggered late

This approach is the least desirable. Because the external event may be hung up, there is no way out. is equal to digging a hole. But if the event supports publishing first, then subscribing, the problem is simple:

Eventmanger.trigger ("A", 2); function DoB () {    console.log ("do B");     // the method in actual B needs to be executed after the A event succeeds }function  DoC () {    console.log ("Do C");    Eventmanger.addhandler (function  () {        console.log ("do a");        DoB ();    });} DoC ();

That's a lot clearer. The event subscription does not have to be so concerned with the location of the call. The above just remembers the last call parameter, which can be used for post-subscription event firings. This is suitable for one-time events (events that only trigger once in a cycle). If the event is like a push message, it will continue to trigger, and if you want to make sure you get all the history you need to remember all the parameters. This is a situation where there may be more process dependencies and, of course, there are many ways to control the process and many libraries support it. Like promise and Async. This article just illustrates a process-related scenario for an event and method, perhaps enlightening you.

JavaScript lets events support post-publication subscriptions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.