Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript event binding, triggering and deletion sample code
JavaScript The simplest event model 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 (deletion event) and trigger (trigger event). For the same event name, multiple event processing functions can be bound; they will be triggered sequentially in the order of binding.
args.splice(0, handlers[i].length) Parameters passed when triggered
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); //删除 fnX 后,只剩下 fnY }; document.getElementById('bind').onclick = function () { eventModel.trigger('myevent2'); //输出 fnX fnY //在点击unbind后,只输出 fnY };
The above is the detailed content of Detailed explanation of JavaScript event binding, triggering and deletion sample code. For more information, please follow other related articles on the PHP Chinese website!