I learned a very interesting pattern today, which a lot of the big guys call event delegation, which I’ve only heard and learned about before, procedural programming and object-oriented programming, but now I’ve added delegate. It is a design pattern that differs from class
Event delegation
Principle 1.
Instead of setting event listeners for each child node individually, set them on its parent node and then set each child node using the bubbling principle.
Usage: this is not a direct DOM representation, use code representation
Task = {
setID: function(ID) {
this.id= ID; },outputID: function() {
console.log(this.id); }};// let XYZ delegate Task
XYZ= Object.create(Task);
XYZ. prepareTask = function(ID, Label) {
this.setID(ID);
this.label = Label;
};
XYZ.outputTaskDetails = function() {
this.outputID();
console.log(this.label)
}
//ABC = Object. create (Task); // ABC ... =...
Copy the code
In this code, Task and XYZ are not classes (or functions); they are objects. XYZ through Object.create (..) Create, whose [[Prototype]] delegate Task object.
In delegate behavior: We try to avoid using the same names at different levels of the [[Prototype]] chain, which would require awkward and fragile syntax to disambiguate references. This is the opposite of the class design pattern.
The implicit binding rule for this is that it looks for local XYZ first because it is bound to XYZ first, and if it doesn’t find it, it delegates it to Task via Prototype so it can find the method. Because XYZ delegated Task
Mutual delegation is forbidden, if it is an infinite loop lookup, is not allowed.
Here’s a comparison between the prototype and delegate writing styles
That’s pretty much a new idea I’ve learned