1. Overview
Chain of responsibility pattern means that multiple objects have the opportunity to process the request, thereby avoiding the coupling relationship between the sender and the receiver of the request. Connect the object into a chain and pass the request along the chain until an object handles it.
It seems to be the same as the linked list in the data structure.
But don't mess it up, the responsibility chain is not equal to a linked list, because the responsibility chain can be searched down at any node, while the linked list must be searched down from the beginning node.
For example, the bubbling events in the DOM event mechanism belong to the chain of responsibilities, while the captured events belong to the linked list.
2. Use the responsibility chain to simulate bubbles
Suppose we have three objects: li, ul, and div. The relationship diagram of the three is as follows:
For example, when we trigger the Li object, if li does not prevent bubbles, it will be passed to the ul object. When it reaches ul, if bubbles are not prevented, it will be passed to the div object (assuming that the div is the root node). Similarly, ul and div.
Seeing this, it is very clear that it is suitable for writing such needs using the responsibility chain model.
But, how to use JavaScript to implement the responsibility chain model?
As follows, we can build the basic architecture through prototype chains:
function CreateDOM(obj){ this.next = obj || null;}; CreateDOM.prototype = { handle: function(){ if(this.next){ this.next.handle(); } }};Whenever we use the CreateDOM constructor to create an object, we pass the associated object in (well, this is very linked list).
Then, when we trigger an object and execute the handle method, we can follow this chain and go on.
However, it should be noted that when the handle attribute of an object covers the handle in the prototype chain, how can you continue to pass it down?
Just use CreateDOM.prototype.handle.call(this);
So, implementing li, ul and div codes are 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 to everyone's learning and I hope everyone will support Wulin.com more.