简单jquery组件开发

写这篇文章主要是对自己以前学习jquery插件的总结。现在组件化开发,以vuejs 、 reactjs 、angular 为代表的库或框架让web组件化开发逐渐推广起来。下面是我用jquery写的一款简易的提示框组件。虽然没有遵守mvc写法,但也是很实用。

效果:

简单jquery组件开发_第1张图片

有时用户执行某个操作时,需要弹出提示框让用户确定执行某个回调函数,这样就有效的避免用户因操作失误执行不该执行的操作。

代码

/**
 * Created by helti on 2017/2/16 0016.
 */

!(function(window,$,undefined){

    var htmls={
        'popbg':'
'
, 'pwraper':'
'
, 'popheader':'
'
, 'popdes':'

'
, 'palert':'
'
, 'pconfim':'
'
}; var winpop=function(opt,callback){ var defaults={ headercon:'', popdes:'' } this.options= $.extend({},defaults,opt); this.$body=$('body'); //背景 this.$popbg=$(htmls.popbg); //pop父容器 this.$wraper=$(htmls.pwraper); if(callback !='undefined'){ if(typeof callback == 'function'){ this.callback=callback; } }else{ throw new Error ('callback need function') } }; winpop.prototype={ /* alert 或者 confim */ createdom:function(ele){ var $popheaer=$(htmls.popheader).text(this.options.headercon); var $contenthtml=$(htmls.popdes).text(this.options.popdes); // $palert=$(htmls.palert); this.$wraper.append($popheaer).append($contenthtml).append(ele); this.$body.append(this.$popbg).append(this.$wraper); // this.callback(); // console.log(this.callback); }, okclick:function(){ //确认按钮执行回调函数 this.callback(); }, eventclick:function(){ var that=this; that.$wraper.find("#btn-ok").on("click",function(){ that.remove(); that.okclick(); }) //只通过事件委托绑定一次,如果用on绑定,因为doument无法删除,导致事件一直存在 /* $(document).one("click","#btn-ok",function(){ that.remove(); that.okclick(); });*/ that.$wraper.find(".btn-ok").on("click",function(){ that.remove(); that.okclick(); }) /* $(document).one("click",".btn-ok",function(){ that.remove(); that.okclick() });*/ that.$wraper.find(".btn-cancel").on("click",function(){ that.remove(); }) }, alertpop:function(){ var $palert=$(htmls.palert); this.createdom($palert); this.eventclick(); }, confimpop:function(){ var $pconfim=$(htmls.pconfim); this.createdom($pconfim); this.eventclick(); }, remove:function(){ this.$wraper.empty().remove(); this.$popbg.empty().remove(); } }; window.winpop=winpop; }(window,jQuery));

总结:

我们都知道动态生成的dom元素,要给它绑定事件时,必须给予事件委托,通常我们委托给document.

//这里不应该用on
$(document).one("click","#btn-ok",function(){
                  that.remove();
                  that.okclick();

              });

但是我们委托给document时会出现一个问题,就是但你再次触发按钮时,原来绑定的事件不会销毁。因为document不能删除。那么用one呢?我们只让它执行一次。大家可以试下。

最终我使用了

that.$wraper.find(".btn-cancel").on("click",function(){
                  that.remove();

              })

这样就避免了事件不被销毁。从而累计事件的bug.

github源码

你可能感兴趣的:(Jquery)