码迷,mamicode.com
首页 > Web开发 > 详细

js自定义事件

时间:2017-01-21 00:26:48      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:alert   lis   rem   log   for   nbsp   ret   cti   efi   

var Event = {
    _listeners: {},
    // 添加
    addEvent: function (type, fn) {
        if(typeof this._listeners[type] === ‘undefined‘) {
            this._listeners[type] = [];
        }
        if(typeof fn === ‘function‘) {
            this._listeners[type].push(fn);
        }
        return this;
    },
    // 触发
    fireEvent: function (type) {
        var arrayEvent = this._listeners[type];
        if(arrayEvent instanceof Array) {
            for(var i = 0, length = arrayEvent.length; i < length; i+=1) {
                if(typeof arrayEvent[i] === ‘function‘) {
                    arrayEvent[i]({ type: type });
                }
            }
        }
        return this;
    },
    // 移除事件
    removeEvent: function (type, fn) {
        var arrayEvent = this._listeners[type];
        if(typeof type === ‘string‘ && arrayEvent instanceof Array) {
            if (typeof fn === ‘function‘) {
                for(var i = 0, length = arrayEvent.length; i < length; i+=1) {
                    if(arrayEvent[i] == fn) {
                        this._listeners[i].splice(i, 1);
                        break;
                    }
                }
            }
        } else {
            delete this._listeners[type];
        }
        return this;
    }
};

var myEvent = Event.addEvent(‘alert‘, function () {
    alert(‘我是二宝的妈‘);
});
Event.fireEvent(‘alert‘);
console.log(myEvent);

function removeEventAlert () {
    Event.removeEvent(‘alert‘, function () {
        alert(‘我是二宝的妈‘);
    });
    console.log(myEvent);
}

 

js自定义事件

标签:alert   lis   rem   log   for   nbsp   ret   cti   efi   

原文地址:http://www.cnblogs.com/lqcdsns/p/6329609.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!