Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端设计模式 #93

Open
ZhengXingchi opened this issue Jul 6, 2020 · 3 comments
Open

前端设计模式 #93

ZhengXingchi opened this issue Jul 6, 2020 · 3 comments

Comments

@ZhengXingchi
Copy link
Owner

ZhengXingchi commented Jul 6, 2020

参考文献

JavaScript中常用的设计模式

掌握前端5大常用设计模式,瞬间高大上

前端和设计模式

前端常用的设计模式,看这一篇总结足以

《js设计模式与开发实践》一书

曾探大神的《JavaScript设计模式与开发实践》

@ZhengXingchi
Copy link
Owner Author

ZhengXingchi commented Jul 7, 2020

@ZhengXingchi
Copy link
Owner Author

通过代理模式实现图片的预加载

   // 创建一个本体对象
    var myImage = (function () {
        // 创建标签
        var imgNode = document.createElement('img');
        // 添加到页面
        document.body.appendChild(imgNode);
        return {
            // 设置图片的src
            setSrc: function (src) {
                // 更改src
                imgNode.src = src;
            }
        }
    })();

    // 创建代理对象
    var proxyImage = (function () {
        // 创建一个新的img标签
        var img = new Image;
        // img 加载完成事件
        img.onload = function () {
            // 调用 myImage 替换src方法
            myImage.setSrc(this.src);
        }
        return {
            // 代理设置地址
            setSrc: function (src) {
                // 预加载 loading
                myImage.setSrc('file:// /C:/Users/svenzeng/Desktop/loading.gif');
                // 赋值正常图片地址
                img.src = src;
            }
        }
    })();

    proxyImage.setSrc('http:// image.qq.com/music/photo/k/000GGDys0yA0Nk.jpg');

@ZhengXingchi
Copy link
Owner Author

ZhengXingchi commented Jul 7, 2020

如何判断图片(img)是否已经加载成功--基于react

参考如何判断图片(img)是否已经加载成功--基于react
为此写了一个useImage

import React, { useState, useEffect, useCallback, useRef } from 'react';
import img2 from '@imgs/img2.jpg';  //临时用的正式上线改掉
import _ from 'lodash'
exports.useImage = (list) => {
  const [initList, setInitList] = useState(list);
    const temp=useRef(undefined)
    useEffect(()=>{
        temp.current=_.cloneDeep(initList)
        for(let i=0;i<initList.length;i++){
            temp.current[i].img=initList[i].img
              initList[i].img=img2
            
              setInitList([...initList])
            }
          
        for(let i=0;i<initList.length;i++){
          var img=new Image()
          img.src=temp.current[i].img
          img.onload=()=>{
            initList[i].img=temp.current[i].img
            console.log(initList)
            setInitList([...initList])
          }
        }
      },[])
      return [initList]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant