This is the 13th day of my participation in the August More Text Challenge. For details, see “August More Text Challenge”.

preface

JavaScript asynchronous Programming Chapter 2 distributed events

PubSub pattern (Publish, subscribe)

To handle events in practice, add a handler directly to each event. Multiple processing results for a single event can cause the size of the processor to balloon. If a function is implemented, the function will call a lot of methods, and the function will have a lot of lines and be difficult to maintain. This section discusses how to implement events through the PubSub pattern.

Next, we will introduce Node’s EventEmitter object, Backbone’s event-type model, and jQuery’s custom events

Browsers allow you to attach event handlers to DOM elements, such as link.onclick = clickHandler

If you want to attach two click event handlers to an element, you must assemble them yourself with a wrapper function.

link.onclick = function() {
    clickHandler1.apply(this, arguments)
    clickHandler2.apply(this, arguments)
}
Copy the code

The W3C added the addEventListener method to the DOM specification in 2000, and jQuery abstracts it as the bind method.

$(link)
    .bind('click', clickHandler1)    .bind('click', clickHandler2)

$( "button" ).on( "click", notify );
$( "button" ).on( "click", notify );
Copy the code

JQuery publishes the event of the link element to anyone who wants to subscribe to it.

In Nodejs, there is an entity that implements the publish/subscribe pattern. This entity is an EventEmitter, which other objects can inherit. And almost all of the I/O sources in Nodejs are EventEmitter objects: file streams, HTTP servers, and even the application process itself. Refer to an EventEmitter example.

[' room ', 'moon','cow jumping over the moon'] .forEach(function(name){ process.on('exit',function(){ console.log('GoodNight, '+ name)})}) // Publish the exit event to others when it occurs, executing an anonymous function to print the informationCopy the code

(This example is pretty watery)

EventEmitter object

EventEmitter object in Node

1. Add an event handler to the EventEmitter object with the ON method

2. Invoke all handlers for the given event type through the emit method

Events here have nothing to do with events in the queue, nodeJS convention, can only be fired from ‘inside’ the EventEmitter object.

Realize the PubSub

PubSub = {handlers: {}} PubSub.on = function(eventType,handler){ if(! (eventType in this.handlers)){ this.handlers[eventType] = [] } this.handlers[eventType].push(handler) return this } PubSub.emit = function(eventType){ var handlerArgs = Array.prototype.slice.call(arguments, l); for(var i=0; i<this.handlers[eventType].length; i++){ this.handlers[eventType][i].apply(this,handlerArgs) } return this }Copy the code

synchronicity

In JS, events trigger synchronous execution of the processor, and too many processors will result in corresponding sluggishness. A simple solution is provided here, and more sophisticated job queuing techniques are presented later in chapter 4.

var tasks = [] setInterval(function(){ var nextTask if(nextTask = tasks.shift()){ nextTask() } }, 0) // This function will not execute all processors at once // instead, it will execute each processor asynchronously through setInterval and will not block other operations. // For more details, see Chapter 4Copy the code

Eventized model

As long as the object has the excuse of PubSub, it is called an eventalized object.

When the object used to store the data publishes events due to changes in its content, the object used to store the data here is also called a Model.

MVVM, the Model in MVC. So the publish subscribe pattern can be used to implement the MVC, MVVM model.

(Vue two-way binding source code is used)

Old fashioned javaScript relies on input event handlers to modify the DOM directly. The new JavaScript changes the model first, triggering events from the model that result in DOM updates.

Event loops and nested variations

Backbone has two insurances.In case of bidirectional binding, the change event is triggered wirelessly.

1. If the new value is equal to the old value, the change event is not triggered

2. During the change event, the change event is not triggered

Here this book gives an example of backbone frame set/get, personally I think it is relatively shallow, but this framework has not been touched temporarily. Unfortunately, this is not an example of vUE bidirectional binding.

JQuery custom events

Custom events are used as a complement to the DOM event bubbling technique.

JQuery provides a non-bubbling triggerHandler method.

The book gives an example of a progress bar

$('.tooltip').remove() $('.tooltip').remove() $('.tooltip').remove() $('.tooltip').remove() The sidebar displays a new tooltip bar. Tooltips elsewhere are not affected. $container can be $('#sidebar') or $(document) $container.triggerHandler('newTootip') $container.one('newTooltip',function(){ $tooltip.remove })Copy the code

For more information on triggerHandler, see blog.csdn.net/qq\_2285532…

Use custom events when the event bubble technique breaks our intent.

summary

The PubSub event model is difficult to solve for one-off events (one-off events require different handling of the two results of one-off tasks performed by asynchronous functions). Such as Ajax), which is the Promise of the next slide

PS:

When I read this chapter today, I had a good time. Especially when I read the vUE bidirectional binding source code before, in the pubSub mode here, and got to revisit. It’s a kind of relearning.

It’s a pity that the author of this book teaches NodeJS,jquery,backbone. I can only see a lot of content once, clear my mind, or a lot of content is stuck.

I didn’t go deep enough, but I got something. I learned a lot of concepts, and I added to my knowledge.

Finish the book this weekend, just in time to get rid of the promise asynchrony stuff.

Keep reading. It’s still fun to read these obscure books. You never know if you can handle the next chapter. Make sure you gain, do not make you lose. For some reason, it seems like this experience is more interesting than just always learning correctly.