js Event Model and Custom Event Instance Analysis
- 2021-11-24 02:43:16
- OfStack
JavaScript 1 is the simplest event model, which requires event binding and triggering, as well as event deletion.
var eventModel = {
list: {},
bind: function () {
var args = [].slice.call(arguments),
type = args[0],
handlers = args.slice(1);
if (typeof type === 'string' && handlers.length > 0) {
for (var i = 0; i < handlers.length; i++) {
if (typeof handlers[i] === 'function') {
if (!this.list[type]) {
this.list[type] = [];
}
this.list[type].push(handlers[i]);
}
}
}
},
unbind: function () {
var type = arguments[0],
handlers = Array.prototype.slice.call(arguments, 1);
if (typeof type === 'string') {
if (handlers.length === 0) {
this.list[type] = [];
} else {
for (var i = 0; i < handlers.length; i++) {
if (typeof handlers[i] === 'function' && handlers[i] === this.list[type][i]) {
this.list[type].splice(i, 1);
}
}
}
}
},
trigger: function () {
var arguments = [].slice.call(arguments),
type = arguments[0],
args = arguments[1] instanceof Array && !arguments[2] ? arguments[1] : arguments.slice(1),
handlers = this.list[type];
for (var i = 0; i < handlers.length; i++) {
handlers[i].apply(this, args.splice(0, handlers[i].length));
}
}
};
It mainly implements bind (binding event), unbind (deleting event) and trigger (triggering event). For the same 1 event name, multiple event handlers can be bound; And trigger in turn according to the binding order.
args. splice (0, handlers [i]. length)
Event binding and triggering:
eventModel.bind('myevent1', function (a) {
console.log(a); // 1
}, function(b) {
console.log(b); // 2
}, function(c, d) {
console.log(c + ' + ' + d); // a + b
});
eventModel.bind('myevent1', function (e) {
console.log(e); // 50
});
eventModel.trigger('myevent1', 1,2,'a','b', 50);
Event deletion:
<button id="bind">bind</button>
<button id="unbind">unbind</button>
var fnX = function () {
console.log('fnX');
}
var fnY = function () {
console.log('fnY');
}
eventModel.bind('myevent2', fnX, fnY);
document.getElementById('unbind').onclick = function () {
eventModel.unbind('myevent2', fnX); // Delete fnX After that, there is only one left fnY
};
document.getElementById('bind').onclick = function () {
eventModel.trigger('myevent2'); // Output fnX fnY
// In the click unbind After, only output fnY
};