简体   繁体   中英

JavaScript: Dispatch event from one class and listen in another class

Can I dispatch event from one class and listen it in another class in JAVASCRIPT. Can any one help me regarding this.

function onButtonClickHandler(){ alert("Testing Add event listener"); }
test.addEventListener("buttonClick",onButtonClickHandler);

Yes:

test.addEventListener("click",onButtonClickHandler);

Javascript doesn't have classes, but you can mimic the behavior:

 var NS = {};
 NS.Class1 = function () {
        return {
            eventHandler: function () {alert('Class 1')}
        }
 }()

 NS.Class2 = function () {
         return {
            handler: null,
            action: function () {
               if(this.handler) this.handler.call(arguments) 
               else alert('default')
            }
          }
 }()

 NS.Class2.handler = NS.Class1.eventHandler
 NS.Class2.action()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM