乐趣区

关于javascript:我是如何编写一个js插件的

编写插件的目标
  • 更好的复用
  • 不便保护
  • 反对配置

插件 1.0

;(function (global) {
    // 上传配置
    var config = {
        getTokenUrl: "//xxx.xxx.com/api/Active/qintoken?bucket=wnlother", // 获取 token 接口地址
        qiniuUpUrl: "//xxx.qiniup.com/putb64/-1", // 上传的七牛服务器地址
        imgUrlDomain: 'https://xxx.xxx.com/' // 图片域名
    };
    // 定义上传办法
    function uploadQN(img, resolve) {var xhr = new XMLHttpRequest();
        xhr.open('GET', config.getTokenUrl, true);
        xhr.onreadystatechange = function() {
            // readyState == 4 阐明申请已实现
            if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) {
                // 从服务器取得数据 
                var res = JSON.parse(xhr.responseText);
                var xhr2 = new XMLHttpRequest();
                xhr2.open('POST', config.qiniuUpUrl, true);
                xhr2.setRequestHeader('Content-Type', 'application/octet-stream');
                xhr2.setRequestHeader('Authorization', 'UpToken' + res.token);
                xhr2.send(img.substring(23));
                xhr2.onreadystatechange = function() {if (xhr2.readyState === 4) {var resData = JSON.parse(xhr2.responseText);
                        console.log(resData.key);
                        var remoteImg = config.imgUrlDomain + resData.key;
                        resolve(remoteImg);
                    }
                };
            }
        };
        xhr.send();};

    // 兼容 CommonJs 标准
    if (typeof module !== "undefined" && module.exports) {module.exports = uploadQN;}
    // 兼容 AMD/CMD 标准
    if (typeof define === "function")
        define(function () {return uploadQN;});
    // 注册全局变量,兼容间接应用 script 标签引入插件
    global.uploadQN = uploadQN;
})(window);
// 调用办法
uploadQN(imgdata, (res) => {//do something});

特点:

  • 即插即用
  • 不反对配置

插件 2.0

;(function (global) {
    // 定义上传办法
    function UploadQN(img, options) {
        var config = {
            getTokenUrl: "//xxx.xxx.com/api/Active/qintoken?bucket=wnlother", // 获取 token 接口地址
            qiniuUpUrl: "//xxx.qiniup.com/putb64/-1", // 上传的七牛服务器地址
            imgUrlDomain: 'https://xxx.xxx.com/', // 图片域名
            success: function(res) {}};
        if (!(this instanceof UploadQN)) {console.log(0);
            return new UploadQN(img, options);
        }
        // options = options || config;
        // 合并参数
        for (var k in options) {if (options.hasOwnProperty (k)) {config [k] = options [k];
            }
        }
        console.log(config);
        // 1. 获取 token
        var xhr = new XMLHttpRequest();
        xhr.open('GET', config.getTokenUrl, true);
        xhr.onreadystatechange = function() {
            // readyState == 4 阐明申请已实现
            if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) {
                // 从服务器取得数据 
                var res = JSON.parse(xhr.responseText);
                // 2. 上传七牛
                var xhr2 = new XMLHttpRequest();
                xhr2.open('POST', config.qiniuUpUrl, true);
                xhr2.setRequestHeader('Content-Type', 'application/octet-stream');
                xhr2.setRequestHeader('Authorization', 'UpToken' + res.token);
                xhr2.send(img.substring(23));
                xhr2.onreadystatechange = function() {if (xhr2.readyState === 4) {var resData = JSON.parse(xhr2.responseText);
                        console.log(resData.key);
                        var remoteImg = config.imgUrlDomain + resData.key;
                        // 3. 执行回调
                        config.success && config.success(remoteImg);
                    }
                };
            }
        };
        xhr.send();};

    // 兼容 CommonJs 标准
    if (typeof module !== "undefined" && module.exports) {module.exports = UploadQN;}
    // 兼容 AMD/CMD 标准
    if (typeof define === "function")
        define(function () {return UploadQN;});
    // 注册全局变量,兼容间接应用 script 标签引入插件
    global.UploadQN = UploadQN;
})(window);
// 调用办法
UploadQN(imgdata, {
    imgUrlDomain: 'https://other.image.cq-wnl.com/',
    success: (res) => {console.log(res);
    }
});
或
var loader = new UploadQN(imgdata, {
    imgUrlDomain: 'https://other.image.cq-wnl.com/',
    success: (res) => {console.log(res);
    }
});

特点:

  • 反对实例化
  • 反对配置
  • 没有 api,不反对链式调用

插件 3.0

/* eslint-disable */
;(function (global) {
    // 定义上传办法
    function UploadQN(img, options) {
        this.img = img;
        this.config = {
            getTokenUrl: "//xxx.xxx.com/api/Active/qintoken?bucket=wnlother", // 获取 token 接口地址
            qiniuUpUrl: "//xxx.qiniup.com/putb64/-1", // 上传的七牛服务器地址
            imgUrlDomain: 'https://xxx.xxx.com/' // 图片域名
        };
        this.resultImg = '';
        if (!(this instanceof UploadQN)) {console.log(0);
            return new UploadQN(img, options);
        }
        // options = options || this.config;
        // 合并参数
        for (var k in options) {if (options.hasOwnProperty (k)) {this.config [k] = options [k];
            }
        }
        console.log(this.config);
        this.init();};

    UploadQN.prototype = {init: function() {this.getToken();
        },
        getToken: function() {
            var that = this;
            var xhr = new XMLHttpRequest();
            xhr.open('GET', that.config.getTokenUrl, true);
            xhr.onreadystatechange = function() {
                // readyState == 4 阐明申请已实现
                if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) {
                    // 从服务器取得数据 
                    var res = JSON.parse(xhr.responseText);
                    that.upload(res);
                }
            };
            xhr.send();},
        upload: function(res) {
            var that = this;
            var xhr2 = new XMLHttpRequest();
            xhr2.open('POST', that.config.qiniuUpUrl, true);
            xhr2.setRequestHeader('Content-Type', 'application/octet-stream');
            xhr2.setRequestHeader('Authorization', 'UpToken' + res.token);
            xhr2.send(that.img.substring(23));
            xhr2.onreadystatechange = function() {if (xhr2.readyState === 4) {var resData = JSON.parse(xhr2.responseText);
                    console.log(resData.key);
                    var remoteImg = that.config.imgUrlDomain + resData.key;
                    that.resultImg = remoteImg;
                    // 3. 执行回调
                    // that.success();
                    // that.config.success && that.config.success(remoteImg);
                }
            };
        },
        success: function(cb) {cb(this.resultImg);
            return this;
        }
    };

    // 兼容 CommonJs 标准
    if (typeof module !== "undefined" && module.exports) {module.exports = UploadQN;}
    // 兼容 AMD/CMD 标准
    if (typeof define === "function")
        define(function () {return UploadQN;});
    // 注册全局变量,兼容间接应用 script 标签引入插件
    global.UploadQN = UploadQN;
})(window);
退出移动版