JavaScript is one of the simplest event models, requiring event binding and triggering, and perhaps an event deletion.
1 varEventmodel = {2 list: {},3 4Bindfunction () {5 varargs =[].slice.apply (arguments),6Type = Args[0],7handlers = Args.slice (1);8 9 if(typeofType = = = ' String ' && handlers.length > 0) {Ten for(vari = 0; i < handlers.length; i++) { One if(typeofHandlers[i] = = = ' function ') { A if(! This. List[type]) { - This. list[type] = []; - } the This. List[type].push (Handlers[i]); - } - } - } + }, - +Triggerfunction () { A vararguments =[].slice.apply (arguments), atType = Arguments[0], -args = Arguments[1]instanceofArray &&!arguments[2]? ARGUMENTS[1]: Arguments.slice (1), -Handlers = This. List[type]; - - for(vari = 0; i < handlers.length; i++) { -Handlers[i].apply ( This, Args.splice (0, Handlers[i].length)); in } - } to};
The main implementation of BIND (BIND event) and trigger (trigger event). Multiple event handlers can be bound to the same event name, and are triggered sequentially in the order in which they are bound.
Args.splice (0, handlers[i].length) when triggering a parameter
Use:
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 (' MyEvent2 ',function(x) {console.log (x);},function(y) {console.log (y);}); Eventmodel.bind (' Myevent1 ',function(e) {console.log (e); // -}); Eventmodel.trigger (' Myevent1 ', and, ' A ', ' B ', 50;
JS event model and custom events