我是如何編寫一個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
});

特色:api

  • 即插即用
  • 不支持配置
插件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);
相關文章
相關標籤/搜索