根据jquery自定义事件写一个事件订阅派发demo

1.未绑定dom对象的观察者模式demo

  var scope = {
            on:function(name,callback){
                this.arr = this.arr || [];
                    this.arr[name] = {
                        callback: callback
                    }

            },
            trigger:function(name){
                if(this.arr[name])this.arr[name].callback();
            }
        };
        scope.on('hello',function(){
            console.log('hello');
        });
        scope.trigger('hello');

实现比较简单。这样的实现方式有一个缺点就是不同的用户来定义的事件都存放在一个数组里,可能会产生覆盖,用户之间的事件没有隔离。不实用呀。

1.绑定dom对象的观察者模式demo

 var scope = {
        on:function(dom,name,callback){
            this.arr = this.arr || [];
            this.arr[dom] = this. arr[dom] || [];
            this.arr[dom].push({
                name:name,
                callback:callback
            })

        },
        trigger:function(dom,name){
            if(this.arr[dom]){
                var len = this.arr[dom].length;
                for(var i = 0;i < len;i++){
                    if(this.arr[dom][i].name == name){
                        this.arr[dom][i].callback();
                    }
                }
            }
        }
    };

    scope.on('id','he',function(){
        console.log('id  he');
    })
    scope.on('id','hu',function(){
        console.log('id  hu');
    })
    scope.trigger('id','he');
    scope.trigger('id','hu');
    scope.trigger('ss','he');//什么也不输出因为没有注册这个事件

这是jquery的自定义事件的实现原理。jquery还把各个模块之间的交互也通过事件订阅和触发的方式来相互通知,交互。有非常不错的隔离性,和模块化气质。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值