前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于回调

关于回调

作者头像
爱学习的前端歌谣
发布2023-10-18 11:11:45
1510
发布2023-10-18 11:11:45
举报
文章被收录于专栏:前端小歌谣

前言

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

环境配置

npm init -y

yarn add vite -D

修改page.json配置端口

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

基本案例

代码语言:javascript
复制
function test(callback){
   var a=1
   callback(a)
}


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

运行结果

回调案例

代码语言:javascript
复制
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)
})

运行结果

计算

代码语言:javascript
复制
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}`)
})

运行结果

验证

index.html

代码语言:javascript
复制
<!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

代码语言:javascript
复制
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

代码语言:javascript
复制
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){


}

运行结果

阻塞 后端代码

代码语言:javascript
复制
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")
})

启动

前端

代码语言:javascript
复制
const data=$.ajax("http://localhost:3003/getdata",{
    async:false,
    // success(data){
    //     console.log(data)
    // }
}).responseJSON
console.log(data)
console.log(123)

运行结果

异步问题同步化

后端

代码语言:javascript
复制
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")
})

前端

代码语言:javascript
复制
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)

运行结果

watcher实现

index.js

代码语言:javascript
复制
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

代码语言:javascript
复制
<!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>

运行结果

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-09-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 前端小歌谣 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档