Javascript原生插件开发
文章 1778 0 0 0
发布时间:2018年11月15日

概述

js原生插件开发基本雏形:

function(window,document){
    var MaskShare = function(){
    };
    MaskShare.prototype = {};
    window.MaskShare = MaskShare;
}(window,document));

举例:

点击某个元素,弹出一个遮罩层,点击遮罩层将遮罩层去掉。

因此可以分析出,至少需要一个参数,也就是我们需要知道点击谁弹出弹出层,另外我们还需要配置一些默认参数。

(function(window,document){
    var MaskShare = function(targetDom,options){
        // 判断是用函数创建的还是用new创建的。这样我们就可以通过MaskShare("dom") 或 new MaskShare("dom")来使用这个插件了
        if(!(this instanceof MaskShare))return new MaskShare(targetDom,options);
        // 参数合并
        this.options = this.extend({
            // 这个参数以后可能会更改所以暴露出去
            imgSrc:"../static/img/coupon-mask1.png"
        },options);
        // 判断传进来的是DOM还是字符串
        if((typeof targetDom)==="string"){
            this.targetDom = document.querySelector(targetDom);
        }else{
            this.targetDom = targetDom;
        }
        var boxDom = document.createElement("div");
        var imgDom = document.createElement("img");
        // 设置默认样式 注意将z-index值设置大一些,防止其他元素层级比遮罩层高
        boxDom.style.cssText = "display: none;position: absolute;left: 0;top: 0;width: 100%;height:100%;background-color: rgba(0,0,0,0.8);z-index:9999;";
        imgDom.style.cssText = "margin-top:20px;width: 100%;";
        // 追加或重设其样式
        if(this.options.boxDomStyle){
            this.setStyle(boxDom,this.options.boxDomStyle);
        }
        if(this.options.imgDomStyle){
            this.setStyle(imgDom,this.options.imgDomStyle);
        }
        imgDom.src = this.options.imgSrc;
        boxDom.appendChild(imgDom);
        this.boxDom = boxDom;
        // 初始化
        this.init();
    };
    MaskShare.prototype = {
        init:function(){
            this.event();
        },
        extend:function(obj,obj2){
            for(var k in obj2){
                obj[k] = obj2[k];
            }
            return obj;
        },
        setStyle:function(dom,objStyle){
            for(var k in objStyle){
                dom.style[k] = objStyle[k];
            }
        },
        event:function(){
            var _this = this;
            this.targetDom.addEventListener("click",function(){
                document.body.appendChild(_this.boxDom);
                _this.boxDom.style.display = "block";
                // 打开遮罩层的回调
                _this.options.open&&_this.options.open();
            },false);
            this.boxDom.addEventListener("click",function(){
                this.style.display = "none";
                // 关闭遮罩层的回调
                _this.options.close&&_this.options.close();
            },false);
        }
    };
    // 暴露方法
    window.MaskShare = MaskShare;
}(window,document));

调用:

MaskShare(".immediately",{
    imgSrc:"../static/img/loading_icon.gif",
    boxDomStyle:{
        opacity:".9"
    },
    imgDomStyle:{
        opacity:".8"
    },
    open:function(){
        console.log("show");
    },
    close:function(){
        console.log("close");
    }
});

js原生插件开发几种写法:

1.面向对象方式:调用的时候使用new创建对象

var Auto=Auto||{};
(function(){
    var plugin=function(options){
        this.options=this.extend({xxxxx},options);
        //暴露一些api
        plugin.prototype={
            init:function(){
            },
            extend:function(){
            }
        }
        Auto.Plu=Plugin;
})();
var p=new Auto.Plu(xxxx);

var Auto;
(function(Auto){
    var plugin=(function(){
        function plugin(options){
            this.name='xiaosan';
            this.age=11;
        };
        //暴露一些api
        plugin.prototype.show=function(str){
            alert(str);
        };
        plugin.prototype.set=function(name){
            this.name=name;
            alert(this.name);
        }
        return plugin;
    })();
    Auto.Plu=plugin;
})(Auto||(Auto={}));
var plugin=new Auto.Plu(xxx);
plugin.show('111');

var RongIMLib;
(function (RongIMLib) {
    var UserDataProvider = (function () {
        function UserDataProvider(options) {
            this.opersistName = 'RongIMLib';
            this.keyManager = 'RongUserDataKeyManager';
            this._host = "";
            this.prefix = "rong";
            this.oPersist = document.createElement("div");
            this.oPersist.style.display = "none";
            this.oPersist.style.behavior = "url('#default#userData')";
            document.body.appendChild(this.oPersist);
            this.oPersist.load(this.opersistName);
        }
        UserDataProvider.prototype.setItem = function (key, value) {
            key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key);
            this.oPersist.setAttribute(key, value);
            var keyNames = this.getItem(this.keyManager);
            keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key);
            this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames);
            this.oPersist.save(this.opersistName);
        };
        UserDataProvider.prototype.getItem = function (key) {
            key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key);
            return key ? this.oPersist.getAttribute(key) : key;
        };
        UserDataProvider.prototype.removeItem = function (key) {
            key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key);
            this.oPersist.removeAttribute(key);
            this.oPersist.save(this.opersistName);
            var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [];
            for (var i = 0, len = keyNameArray.length; i < len; i++) {
                if (keyNameArray[i] == key) {
                    keyNameArray.splice(i, 1);
                }
            }
            this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(','));
            this.oPersist.save(this.opersistName);
        };
        UserDataProvider.prototype.getItemKey = function (composedStr) {
            var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this;
            if (keyNameArray.length) {
                for (var i = 0, len = keyNameArray.length; i < len; i++) {
                    if (keyNameArray[i] && keyNameArray[i].indexOf(composedStr) > -1) {
                        item = keyNameArray[i];
                        break;
                    }
                }
            }
            return item;
        };
        UserDataProvider.prototype.clearItem = function () {
            var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this;
            keyNames && (keyNameArray = keyNames.split(','));
            if (keyNameArray.length) {
                for (var i = 0, len = keyNameArray.length; i < len; i++) {
                    keyNameArray[i] && me.removeItem(keyNameArray[i]);
                }
                me.removeItem(me.keyManager);
            }
        };
        UserDataProvider.prototype.onOutOfQuota = function () {
            return 10  1024  1024;
        };
        return UserDataProvider;
    }());
    RongIMLib.UserDataProvider = UserDataProvider;
})(RongIMLib || (RongIMLib = {}));
var provider = new RongIMLib.UserDataProvider(optionsxxx);

2.闭包方式:调用是不用使用new

var Auto=Auto||{};
(function(){
    var plugin=(function(){
        var _options={
            default_word:'ddd'
        };
        function _firstFunc(str){
            alert(str);
        };
        function _secondFunc(str){
            alert(str);
        };
        return {//暴露的一些api
            firstFunc:_firstFunc,
            secondFunc:_secondFunc
        };
    })();
    Auto.Plu=plugin;
})();
Auto.Plu.firstFunc('xx');

变种:

var Auto=Auto||{};
(function(){
    var _options={
        default_word:'ddd'
    };
    function test(){
        alert(11)
    };
    //暴露一些api
    var _plugin={
        firstFunc:function(str=_options.default_word){
            alert(str);
            return this;
        },
        secondFunc:function(){
            alert('second');
            return this;
        }
    }
    Auto.Plu=_plugin;
})();
Auto.Plu.firstFunc('11').secondFunc();
评论专区