Overview of JavaScript responsibility chain mode and javascript responsibility Overview
I. Overview
The Chain of responsibility means that multiple objects have the opportunity to process requests, so as to avoid coupling between request senders and recipients. Connect the object to a chain and pass the request along the chain until an object processes it.
It seems like the linked list in the data structure.
However, do not confuse them. The responsibility chain is not the same as a linked list, because the responsibility chain can be searched on any node, and the linked list must be searched from the first node.
For example, the bubble events in the DOM Event Mechanism belong to the responsibility chain, while the capture events belong to the linked list.
2. Use the responsibility chain to simulate bubbling
Suppose we have three objects: li, ul, and div. The relationship between them is as follows:
For example, when we trigger a li object, if li does not prevent bubbling, it will be passed to ul object, to ul, if not, it is passed to the div object (assuming that the div is the root node ). Similarly, ul and div.
As you can see, it is clear that the responsibility chain model is suitable for writing such requirements.
But how can we use JavaScript to implement the responsibility chain mode?
As follows, we can build the basic architecture through the prototype chain:
function CreateDOM(obj){ this.next = obj || null;}; CreateDOM.prototype = { handle: function(){ if(this.next){ this.next.handle(); } }};
Every time we use the CreateDOM constructor to create an object, we will pass the object associated with it (well, this is a linked list ).
Then, when we trigger an object and execute the handle method, we can go down this chain.
However, it should be noted that when the handle attribute of an object overwrites the handle in the prototype chain, how can we continue to pass on?
Use CreateDOM. prototype. handle. call (this.
So, the code for implementing li, ul, and div is as follows:
var li = null, ul = null, div = null;div = new CreateDOM();div.handle = function(stopBubble){ console.log('DIV'); if(stopBubble){ return; }else{ CreateDOM.prototype.handle.call(this); }};ul = new CreateDOM(div);ul.handle = function(stopBubble){ console.log('UL'); if(stopBubble){ return; }else{ CreateDOM.prototype.handle.call(this); }};li = new CreateDOM(ul);li.handle = function(stopBubble){ console.log('LI'); if(stopBubble){ return; }else{ CreateDOM.prototype.handle.call(this); }};
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.