原生js自定义事件
2016-12-15 本文已影响0人
erichow
Array.prototype.forEach = Array.prototype.forEach || function(callback) {
var arr = this;
for (var i = 0, len = arr.length; i < len; i++) {
callback(arr[i], i);
}
};
Object.create = Object.create || function(proto) {
function F() {}
F.prototype = proto;
return new F;
}
function Emitter() {
this._events = {};
}
Emitter.prototype.on = function(evtype, fn) {
this._events[evtype] = this._events[evtype] || [];
if (this._events[evtype].indexOf(fn) !== -1) return;
this._events[evtype].push(fn);
}
Emitter.prototype.off = function(evtype, fn) {
if (evtype in this._events === false) return;
fn && this._events[evtype].splice(this._events[evtype].indexOf(fn), 1);
!fn && delete this._events[evtype];
}
Emitter.prototype.emit = function(evtype, detail) {
var self = this;
if (!(evtype in this._events)) return;
this._events[evtype].forEach(function(fn, i) {
fn.apply(self, detail);
});
}
Emitter.eventify = function(Klass) {
Klass.prototype = Object.create(Klass.prototype);
for (var attr in Emitter.prototype) {
Klass.prototype[attr] = Emitter.prototype[attr]
}
return Klass;
}