JS event model and custom events

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.