首页 > Web开发 > 详细

js自定义事件

时间:2017-01-21 00:25:35      阅读:338      评论:0      收藏:0      [点我收藏+]

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自定义事件

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!