简体   繁体   English

是否可以将事件处理程序添加到JavaScript函数/类?

[英]Is it possible to add event handlers to JavaScript functions/classes?

I am trying to register for events on a JavaScript function/class, and am trying to get it as close as possible to my C# class below. 我正在尝试注册JavaScript函数/类上的事件,并试图使其尽可能接近下面的C#类。 Is this possible in any way? 这有可能吗?

C# C#

public class MyClass
{
    public event EventHandler evtMyEvent;

    private void RaiseEvent()
    {
       if(evtMyEvent != null)
           evtMyEvent(this, new EventArgs());
    }
}

MyClass mc = new MyClass();
mc.evtMyEvent += (s,e) => { //Do Something };

JS JS

function MyClass()
{
    // Add an event handler...

    this.raiseEvent = function(){
        // raise the event
    }
}

var mc = new MyClass();
//register for the event

It's perfectly possible and you can study one of the many libraries that deal with events to check out their implementation. 这是完全有可能的,您可以研究处理事件的众多库之一,以检查其实现。

Here is a very simplistic draft that doesn't handle unlistening, event types, arguments, scopes, bubbling etc: 这是一个非常简单的草稿,它不处理取消监听,事件类型,参数,作用域,冒泡等问题:

function EventHandler(target) {  
  var listeners = [];

  this.add = function(handler) {
    listeners.push(handler);
  };

  this.fire = function() {
    for (var i=0; i<listeners.length; i++) {
      listeners[i].call(target);
    }
  };
}


function MyClass()
{
  this.name = 'myclass';

  // Add a private event handler...
  var eventHandler = new EventHandler(this);

  this.listen = function(f) {
    eventHandler.add(f);
  };
  this.raiseEvent = function(){
    eventHandler.fire();
  };
}

var mc = new MyClass();


mc.listen(function(){ console.log(this.name); });
mc.raiseEvent();

DEMO: http://jsbin.com/UCAseDi/1/edit 演示: http : //jsbin.com/UCAseDi/1/edit

Obviously changes to this draft are easy to make. 显然,对该草案进行更改很容易。 If you have trouble with either of them, let me know and i will try my best to help you. 如果您在使用它们中的任何一个时遇到问题,请告诉我,我会尽力帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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