最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom events - Javascript dispatchEvent - Stack Overflow

programmeradmin2浏览0评论

I'm using Flash a lot and my classes uses EventDispatcher class which allows me to define custom events of a class. How can I do this in JavaScript.

I would like to do something like this:

var MyClass = function() {
};
MyClass.prototype = {
  test : function() {
    dispatchEvent('ON_TEST');
  }
};

var mc = new MyClass();
mc.addEventListener('ON_TEST', handler);
function handler() { alert('working...') }

How is this possible with JavaScript?

I'm using Flash a lot and my classes uses EventDispatcher class which allows me to define custom events of a class. How can I do this in JavaScript.

I would like to do something like this:

var MyClass = function() {
};
MyClass.prototype = {
  test : function() {
    dispatchEvent('ON_TEST');
  }
};

var mc = new MyClass();
mc.addEventListener('ON_TEST', handler);
function handler() { alert('working...') }

How is this possible with JavaScript?

Share Improve this question edited Feb 16, 2022 at 19:46 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Feb 13, 2010 at 0:00 xpepermintxpepermint 36.2k30 gold badges110 silver badges168 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 20

Gotta roll your own. Here's just one way.

var MyClass = function() {
    this._events = {};
};
MyClass.prototype = {
  addListener: function(eventName, callback) {
      var events = this._events,
          callbacks = events[eventName] = events[eventName] || [];
      callbacks.push(callback);
  },
  raiseEvent: function(eventName, args) {
      var callbacks = this._events[eventName];
      for (var i = 0, l = callbacks.length; i < l; i++) {
          callbacks[i].apply(null, args);
      }
  },
  test : function() {
    this.raiseEvent('ON_TEST', [1,2,3]); // whatever args to pass to listeners
  }
};

You should probably also add a 'removeListener', which would have to find the callback in the array and remove it from the array (or possibly, remove all listeners for an entire event if no callback given).

发布评论

评论列表(0)

  1. 暂无评论