关于回调

  前言

b6022cf5ad3088e5e814661ac8a9b910.png

 我是歌谣 最好的种树是十年前 其次是现在 今天继续给大家带来的是闭包的讲解

环境配置

7a4b25c4ead74b4c5be237619c5781f4.png

npm init -y

yarn add vite -D

修改page.json配置端口

b8312d547cf78006709f19799c79456c.png

{
  "name": "demo1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "vite --port 3002"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "vite": "^4.4.9"
  }
}

 基本案例

df9af028571b6cd17d6ae9a418c98672.png

function test(callback){
   var a=1
   callback(a)
}




test(function(a){
    console.log(a)
})

 运行结果

b5025fcdb207bb6fd210e035d19ae28f.png

6c33daace0442b62b7db6dcafe2458b8.png

回调案例

b482274896f8249aa043821b39480dee.png

function test(title,callback,callback2){
    var _title=`Title:${title}`
    var _zhtitle=`标题:${title}`
    callback(_title)
    callback2(_zhtitle)
 }
 test("我是 歌谣",function(title){
     console.log(title)
 },function(title){
    console.log(title)
})

 运行结果

b1d9e4e321def4165f119a42cc4f74de.png

a334f6201b531fe7cff624ab75be0180.png

计算

ef7ae0b7e541b8f85e8a112c512f12e9.png

function calculate(a, b, type,callback) {
    let res = 0;
    let sign = '+';
    switch (type) {
        case 'PLUS':
            res = a + b;
            sign = '+'
            break
        case 'MINUS':
            res = a - b;
            sign = '-'
            break
        case 'MUL':
            res = a * b;
            sign = '*'
            break
        case 'DIV':
            res = a / b;
            sign = '/'
            break
        default:
            res = a + b;
            sign = '+'
            break
    }
    callback&&callback(a,b,sign,res)
    return {
        a, b, sign, res
    }
}
// const {a,b,sign,res}=calculate(1,2,'DIV')
// console.log(`${a}${b}${sign}${res}`)
calculate(1,2,'DIV',(a,b,sign,res)=>{
    console.log(`${a}${b}${sign}${res}`)
})

 运行结果

5435c6a1dd51c1aab38cb5d2c2e441ca.png

1dc2ff13d1cadc608d3bd79f3d948f8b.png 

验证

4f1a6018c2a5a7abba47c97b432d7d59.png

  index.html

fecbf17429c83f260df4f5660a232e3b.png

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>回调</title>
</head>
<body>
    <input type="test" id="username">
    <input type="password" id="password">
    <button id="loginBtn">登录</button>
    <script type="module" src="./index3.js"></script>
</body>
</html>

index3.js

95759b61a4ad770ea979a716e20fd45b.png

import { checkUserInfo, checkCommet } from "./validate"
const OUsername = document.querySelector("#username")
const OPassword = document.querySelector("#password")
const OLoginbtn = document.querySelector("#loginBtn")




function validate(field) {
    debugger
    return function (data) {
        switch (field) {
            case 'USER_INFO':
                return checkUserInfo(data)
            case 'USER_COMMET':
                return checkCommet(data)
            default:
                throw new Error("验证失败")




        }
    }
}
function loginAction(userInfo, validate) {
    const { errCode, errMsg, value } = validate(userInfo)
    console.log(errCode, errMsg, value)
    if(errCode==1){
        throw new Error(errMsg)
    }
    console.log(value)
}




OLoginbtn.addEventListener('click', () => {
    const username = OUsername.value
    const password = OPassword.value
    console.log(username,password,"data is")
    loginAction({ username, password }, validate('USER_INFO'))
}, false)

 validate.js

25a9a2eeb96225ac0db20660a8363781.png

export function checkUserInfo({username,password}){
   
    if(username.trim().length<6){
        return {
            errCode:1,
            errMsg:"username不能小于6",
            value:username
        }
    }
    if(password.trim().length<6){
        return {
            errCode:1,
            errMsg:"password不能小于6",
            value:password
        }
    }
    return {
        errCode:0,
        errMsg:"ok",
        value:{
            username,password
        }
    }
}




export function checkCommet(data){




}

运行结果

c73a021a7f220c3efc73da983b79c61f.png

cb59d79b5b4bc8f95d0c45a5094911f0.png

 阻塞 后端代码

26a9e9907305f3eecf6eef269312d9ea.png

const express=require("express")
const app=express()
app.all('*',(req,res,next)=>{
    res.header('Access-Control-Allow-Origin',"*")
    res.header('Access-Control-Allow-Methods',"POST,GET")
    next();
})




app.get('/getdata',(req,res)=>{
    res.json({
        name:"geyao",
        age:18
    })
})




app.listen(3003,()=>{
    console.log("ok")
})

 启动

0a3b39bf3709f80b7121d6b6c00ab14e.png

2813143c61d038854b732987901c76f4.png

 前端 

d8896a129e28e9050dcd93775a5650fb.png

const data=$.ajax("http://localhost:3003/getdata",{
    async:false,
    // success(data){
    //     console.log(data)
    // }
}).responseJSON
console.log(data)
console.log(123)

 运行结果

9ea26b80f3421d1ce11a6bdfb70fab65.png

593f1d52e78604140500565ae9c11c86.png

 异步问题同步化

ba13be86539f5918a748d1b9a1fa8d87.png

 后端

d815455ab7c3d0edf1e926b1dbb7edc0.png

const express=require("express")
const app=express()
app.all('*',(req,res,next)=>{
    res.header('Access-Control-Allow-Origin',"*")
    res.header('Access-Control-Allow-Methods',"POST,GET")
    next();
})
app.get('/getdata',(req,res)=>{
    res.json({
        name:"geyao",
        age:18
    })
})




app.listen(3003,()=>{
    console.log("ok")
})

前端

a3696ebf3b336f1a65396315ceafaad1.png

function getData(){
    return new Promise((resolve,reject)=>{
        $.ajax("http://localhost:3003/getdata",{
            success(data){
                resolve(data)
            }
        })
    })
}
// getData().then(data=>{
//     console.log(data)
//     console.log(123)
// })
async function test(){
    const data=await getData();
    console.log(data)
    console.log(123)
}
test()
console.log(234)

运行结果

5f4151c0717a84b093e26f9c37ad3cd3.png

df6d00080f48ea285921821ca435bf48.png

 watcher实现

612d6faec733c0c102de55ee9b5d2387.png

  index.js

73421139528c73b99d6d81892b75d1a5.png

const Delfln = (() => {
    const watcher=[




    ]
    function useReactive(state) {
       return new Proxy(state,{
        get(target,key){
            return Reflect.get[target,key]
        },
        set(target,key,value){
            update(watcher[key].collection,value)
            watcher[key].cb(target[key],value)
            return Reflect.set(target,key,value)
        }
       })
    }
    function useWatcher(collection,key,callback) {
        !watcher[key]&&(watcher[key]={})
        !watcher[key].collection&&(watcher[key].collection=[])
        watcher[key].cb=callback
        watcher[key].collection=[...watcher[key].collection,...collection]
        console.log(watcher,"watcher is")
    }
    function update(collection,value){
        collection.forEach(el=>{
            el.innerText=value
        })
    }
    return {
        useReactive,
        useWatcher
    }
})()




const { useReactive, useWatcher } = Delfln
const state = useReactive({
    title: "This is Title",
    content: "This is Content"
})




useWatcher([
    document.querySelector("h1"),
    document.querySelector("h2")
], 'title', (prev, cur) => {
    console.log("watch title"+prev, cur)
})




useWatcher([
    document.querySelector("p"),
    document.querySelector("span")
], 'content', (prev, cur) => {
    console.log("watch content"+prev, cur)
})
function render(){
    document.querySelector('h1').innerText=state.title,
    document.querySelector('h2').innerText=state.title
    document.querySelector('p').innerText=state.content
    document.querySelector('span').innerText=state.content
}




setTimeout(()=>{
  state.title="这是标题",
  state.content="这是内容"
},1000)

index.html

9f92bcb95dd26cd55bcfb8b7d2dde0af.png

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>回调</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
    <!-- <input type="test" id="username">
    <input type="password" id="password">
    <button id="loginBtn">登录</button> -->
    <h1>




    </h1>
    <h2></h2>
    <p></p>
    <span></span>
    <script type="module" src="./index6.js"></script>
</body>
</html>

 运行结果

9b8236b0e5ff95d0cf118786f923e073.png

86e98770d58c9d4b7a45660a85d702fe.png

总结

8775b7fc0a6e2ca73987b9c22f027fb2.png

最好的种树是十年前 其次是现在 想加入前端超强学习交流群私信我

下方查看历史文章

922125fa5a27da06ce23e8e39cf4c5b5.png

关于闭包(完)笔记

关于闭包(壹)

关于react-admin+postgrest小案例

关于react-redux案例

posted @ 2023-09-12 14:57  前端导师歌谣  阅读(16)  评论(0)    收藏  举报  来源