This is the 19th day of my participation in the Genwen Challenge
Observer model
The observer pattern, also known as message pipes, subscription-publish, messaging mechanism, and custom events, is primarily used to deliver messages across modules
Base observer
For example:
// Define objects
var Observer = (function() {
// Define the real observer
var ob = {
};
// Define the return interface
return {
/** * the on method is used to add events to the observer object@type The string represents the event name *@fn Function represents the event function **/
on: function(type, fn) {
ob[type] = fn;
},
/** * the trigge method is used to trigger events in the observer object *@type Name of the event to fire **/
trigger: function(type) { ob[type](); }}}) ();Copy the code
DOM secondary observer mode
For example:
var Observer = (function() {
// Define the real observer
var ob = {
};
// Define the return interface
return {
/** * the on method is used to add events to the observer object@type The string represents the event name *@fn Function represents the event function **/
on: function(type, fn) {
// Check whether the current type is an array. If it is an array, it can be pushed directly into the array
if (ob[type]) {
ob[type].push(fn);
} else {
// Make an array instead of an arrayob[type] = [fn]; }},/** * the trigge method is used to trigger events in the observer object *@type Name of the event to fire **/
trigger: function(type, val) {
// Execute the loop
for (var i = 0; i < ob[type].length; i++) { ob[type][i](val); }}}}) ();Copy the code
Remove event
For example:
The /** * off method cancels the event *@type The name of the event to cancel *@fn The event function to cancel */
off: function(type, fn) {
// Determine whether to delete a group or an event function
if (fn) {
// Delete a function
for (var i = 0; i < ob[type].length; i++) {
if (ob[type][i] === fn) {
// Remove the current item
ob[type].splice(i, 1); }}}else if (type) {
// Delete a set of event functions
ob[type] = [];
} else {
// Clear allob = {}; }}Copy the code
Examples of ways to bind an event that fires only once:
once: function(type, fn) {
// The bound event will only fire once, and the second time will not fire
// Remember the bind method?
// The bind method looks as if it changed the this reference at the time of the definition, but the function returned and the bind function are not the same
// The same is true here
// Define a new function, bind the function, execute the passed fn function in the function, and remove the function when it is finished
function aaa() {
/ / execution fn
fn();
/ / removeObserver.off(type, aaa); } Observer.on(type, aaa); }}Copy the code
The strategy pattern
The policy pattern refers to the encapsulation of groups of algorithms that are interchangeable
If you have a lot of if else statements, and if else statements in each branch, your program will become bloated
Policy mode in jquery
// Use animate function
$("#box1").animate({left: 1000}, 1000."easeInOutBack".function() {});
$("#box2").animate({left: 1000}, 1000."easeInOutElastic".function() {});
$("#box3").animate({left: 1000}, 1000."easeInElastic".function() {});
Copy the code
Login strategy
For example:
// Define objects
var Strategy = (function() {
var s = {
"chunyingwen": function(str) {
// Define a regular expression
var reg = /^[a-zA-Z]+$/g;
/ / verification
if (reg.test(str)) {
return "通过";
} else {
return "Please enter pure English"}},"chunshuzi": function(num) {
// Define a regular match
var reg = /^\d+$/g;
/ / verification
if (reg.test(num)) {
return "通过";
} else {
return "Please enter pure numbers."}}}// Define the interface
return {
use: function(type, str) {
returns[type](str); }}}) ();Copy the code
Delegate pattern
Definition: Give the parent element what the original child element does. This reduces the number of events, predicts future elements, and prevents memory leaks.
Reduce the number of events
Originally, each element should have one event. After the delegate pattern is used, the child element has no events, only the parent element has events of that type.
Prophetic elements
The element added later has no events because no events were added to the element when it was added. After using the delegate pattern, this matter is not considered.
Preventing Memory leaks
If an element also has an event when it is deleted, it can cause a memory leak in some browsers. We now delegate events to the parent element, and the child element itself has no events, so it can’t be leaked at all.
Throttling mode
In some high frequency events, the effect of executing the code multiple times is the same as that of executing it once. Therefore, it is not necessary to execute the code multiple times. In this case, throttling is needed.
For example, in the onScroll event, $(dom).animate({opCity: 1}, 1000, function() {})
For example:
/** * Throttle (fn) * /** * Throttle (fn) *@fn The function to be throttled *@options Is a configuration object * context: the context in which the function is executed (i.e., this) * args: is an array, and each item in the array is the parameter required for the function to execute * time: Determines the delay of the function * * @ to turn off the throttle(false, fn) *@false Is an indication that the throttler should be turned off when false is passed@fn Function **/ to be throttled
function Throttle(fn, options) {
// Check whether fn is a function or a Boolean
if (typeof fn === "function") {
/ / configuration options
options = options || {
context: null.args: [].time: 10000
}
// Clear the timer before starting
clearTimeout(fn.__throttle);
// To enable the throttle
// Since each function corresponds to a throttle, we can add a custom attribute to fn
fn.__throttle = setTimeout(function() {
fn.apply(options.context, options.args)
}, options.time);
} else {
// Turn off the throttle
// fn is false and options is a function
clearTimeout(options.__throttle); }}Copy the code
Iterator pattern
Iterators can simply be thought of as loops
Iterator mode, which exposes an access interface that iterates through the contents of the interior in sequence without exposing the internal structure
Iterators in jquery
$.each(target, fn)
Target: The target to iterate over. It can be an array or an object
Fn: indicates the function to be executed
There are two parameters
The first parameter is the index value
The second parameter is the member value
This refers to the object currently traversed
For example:
// Define an array
var arr = [1.2.3.4.5.6];
// go through the number group
$.each(arr, function(index, value) {
console.log(this.arguments);
// console.log(new Number(value), this)
})
Copy the code
Results:
Iterator in undescore
Undescore is a JS utility library
Once introduced, the _ variable is exposed globally
Usage:
_.each(target, fn)
Target: The target to iterate over. It can be an array or an object
Fn: function to be executed
There are three parameters: the member value, the index value, and the primitive array
Scope: window
For example:
// Define an array
var arr = ["Samsung"."Huawei".The word "apple"."Banana"];
// go through the number group
_.each(arr, function() {
console.log(this.arguments);
})
Copy the code
Output result:
Iterators in ES5
[].foreach (fn)
Fn: function to be executed
The function takes three arguments:
The first parameter is: the member value
The second parameter is the index value
The third argument is: the primitive array
Scope: window
For example:
// Define an array
var arr = ["Samsung"."Huawei".The word "apple"."Banana"];
// go through the number group
arr.forEach(function() {
console.log(this.arguments);
})
Copy the code
Output result:
Iterator of its own
For example:
// Define a function that iterates through arrays and objects
/** * each implements the iterator *@target The target to traverse *@fn The function to execute **/
function each(target, fn) {
// Determine whether the target passed is an array or an object
if (target instanceof Array) {
// An array is passed
for (var i = 0; i < target.length; i++) {
/ / execution fn
// Pass three parameters: the member target[I], the index I, and the original array target
// fn(target[i], i, target);fn.call(target[i], target[i], i, target); }}else if (Object.prototype.toString.call(target) === "[object Object]") {
// How many ways can I identify an object?
// 1 instanceof Object
// 2 constructor Object
// 3 Object.prototype.toString.call(obj) => "[object Object]"
for (var i in target) {
// Pass two argumentsfn.call(target[i], target[i], i); }}}Copy the code
Adapter mode
The transfer of a program on one interface to an interface on another program is called the adapter pattern
For example: There are no two outlets at home, but the iPhone charger is a two plug, so buy a two outlet (adapter), and successfully charge the phone
For example:
<div id="box"> Hello world </div><script type="text/javascript" src="Js/jquery - 1.7.2. Js"></script>
<script type="text/javascript" src="js/ickt.js"></script>
<script type="text/javascript">
// Change the code in the code base to juqery implementation
var ickt = {
// Select the element
$: function(id) {
return $("#" + id)[0];
},
/ / HTML method
html: function(dom, str) {
return $(dom).html(str);
},
css: function(dom, key, value) {
return $(dom).css(key, value);
},
// Click method
click: function(dom, fn) {
return$(dom).click(fn); }}</script>
<script type="text/javascript">
// Get the element
var $box = ickt.$("box");
// console.log($box);
ickt.click($box, function() {
// Change the style
// ickt.css(this, "color", "white");
ickt.css(this, {
"backgroundColor": "blue"."fontSize": "30px"
})
// Change the internal text
ickt.html(this."It's hot today.");
})
Copy the code
Portfolio model
Definition: Also known as parts-whole pattern, it represents an object as “parts” – “whole” represents structure, and parts and whole have consistency.
For example:
// An implementation of the composite pattern: 1 Defines an abstract base class with the common properties and methods of the composite
// All other classes inherit from this base class, but this base class does not implement content
// Define the base class
function Base() {
this.dom = null;
this.children = [];
}
// Define the method
Base.prototype.add = function(child) {
this.children.push(child);
return this;
}
// Render method
Base.prototype.render = function() {
/ / this cache
var me = this;
this.children.forEach(function(value) {
me.dom.appendChild(value.dom);
})
return this;
}
// Define the outermost container
function Container() {
Base.call(this);
this.dom = document.createElement("ul");
}
Container.prototype = Object.create(Base.prototype);
// Define the li container
function Item() {
Container.call(this);
this.dom = document.createElement("li");
}
Item.prototype = Object.create(Container.prototype);
// Define the lowest element
function Leaf(text) {
this.dom = document.createTextNode(text);
}
// combine them
// Create an outer container
var container = new Container();
// Create five Li elements
var li1 = new Item();
var li2 = new Item();
var li3 = new Item();
var li4 = new Item();
var li5 = new Item();
// Create the five bottom elements
var leaf1 = new Leaf(Xi Jinping's Visit to Guangdong);
var leaf2 = new Leaf("What does Xi Jinping mean when he reassures the private economy?");
var leaf3 = new Leaf('Spiderman' weaved the most beautiful skyline at the Expo);
var leaf4 = new Leaf("Quick Review: Speed up the Development of the Guangdong-Hong Kong-Macao Greater Bay Area");
var leaf5 = new Leaf("Mixed-use reform brings century-old steel enterprises back to life, private aerospace refueling for the future.");
li1.add(leaf1).render();
li2.add(leaf2).render();
li3.add(leaf3).render();
li4.add(leaf4).render();
li5.add(leaf5).render();
Copy the code
Command mode
Definition of command pattern: Decouples and encapsulates the implementation of the request from the invocation.
It is similar to the policy pattern
For example:
// Define the command object
var Command = (function() {
// Get the canvas element
var canvas = document.getElementById("myCanvas");
// Get the brush
var ctx = canvas.getContext("2d");
// Define the actual command object
var C = {
"drawMachineCat": function(x, y, r) {
// How to change the line width
this.lineWidth(2);
// Draw the cat head
this.drawCircle(x, y, r);
/ / fill
this.fill("blue");
/ / stroke
this.stroke("black");
// Draw white face
this.drawCircle(x, y + 20, r - 20);
/ / fill
this.fill("white");
this.stroke("black");
// Draw left eye
this.drawCircle(x - 50, y - 150.30);
this.fill("white");
this.stroke("black");
// Draw right eye
this.drawCircle(x + 50, y - 150.30);
this.fill("white");
this.stroke("black");
// Draw the left eye
this.drawCircle(x - 50 + 10, y - 150.8);
this.fill("black");
// Draw the right eye
this.drawCircle(x + 50 - 10, y - 150.8);
this.fill("black");
// Draw the left eye
this.drawCircle(x - 50 + 10, y - 150.2);
this.fill("white");
// Draw the right eye
this.drawCircle(x + 50 - 10, y - 150.2);
this.fill("white");
},
"drawCircle": function(x, y, r) {
// Open the path
ctx.beginPath();
/ / draw arc
ctx.arc(x, y, r, 0.Math.PI * 2);
// Close the path
ctx.closePath();
},
"fill": function(color) {
ctx.fillStyle = color;
ctx.fill();
},
"stroke": function(color) {
ctx.strokeStyle = color;
ctx.stroke();
},
"lineWidth": function(value) { ctx.lineWidth = value; }}// Define the interface
return {
exec: function(type) {
// Get the remaining parameters
var arg = [].slice.call(arguments.1); / / [1, 2, 3].C[type].apply(C, arg); }}}) ();` ``
Copy the code