简体   繁体   English

自定义对象上的 addEventListener

[英]addEventListener on custom object

I've created an object that has several methods.我创建了一个具有多种方法的对象。 Some of these methods are asynchronous and thus I want to use events to be able to perform actions when the methods are done.其中一些方法是异步的,因此我想使用事件来在方法完成时执行操作。 To do this I tried to add the addEventListener to the object.为此,我尝试将 addEventListener 添加到对象中。

jsfiddle小提琴手

var iSubmit = {
    addEventListener: document.addEventListener || document.attachEvent,
    dispatchEvent: document.dispatchEvent,
    fireEvent: document.fireEvent,   


    //the method below is added for completeness, but is not causing the problem.

    test: function(memo) {
        var name = "test";
        var event;
        if (document.createEvent) {
            event = document.createEvent("HTMLEvents");
            event.initEvent(name, true, true);
        } else {
            event = document.createEventObject();
            event.eventType = name;
        }
        event.eventName = name;
        event.memo = memo || { };

        if (document.createEvent) {
            try {
                document.dispatchEvent(event);
            } catch (ex) {
                iAlert.debug(ex, 'iPushError');
            }
        } else {
            document.fireEvent("on" + event.eventType, event);
        }
    }
}

iSubmit.addEventListener("test", function(e) { console.log(e); }, false);


//This call is added to have a complete test. The errors are already triggered with the line before this one.

iSubmit.test();

This will return an error: Failed to add eventlisterens: TypeError: 'addEventListener' called on an object that does not implement interface EventTarget."这将返回一个错误: Failed to add eventlisterens: TypeError: 'addEventListener' called on an object that does not implement interface EventTarget."

Now this code will be used in a phonegap app and when I do, it is working on android/ios.现在这段代码将用于 phonegap 应用程序,当我这样做时,它可以在 android/ios 上运行。 During testing, however, it would be nice if I could get it to work in at least a single browser.然而,在测试过程中,如果我能让它至少在一个浏览器中工作,那就太好了。

PS> I know I could enable bubbling and then listen to the document root, but I would like to have just a little bit OOP where each object can work on its own. PS> 我知道我可以启用冒泡,然后听取文档根目录,但我希望有一点 OOP,每个对象都可以独立工作。

addEventListener is intended for DOM Elements that implements certain event-related interfaces. addEventListener适用于实现某些事件相关接口的 DOM 元素。 If you want an event system on pure JavaScript objects, you are looking for a custom event system.如果你想要一个基于纯 JavaScript 对象的事件系统,你正在寻找一个自定义事件系统。 An example would be Backbone.Events in Backbone.js.一个例子是Backbone.Events中的 Backbone.Events。 The basic idea is using an object as a hash to keep track of registered callbacks.基本思想是使用对象作为哈希来跟踪注册的回调。

Personally I use this: emitter .我个人使用这个:发射器

It's a fairly simple and elegant solution - with sweet short method names like on() , off() and emit() .这是一个相当简单和优雅的解决方案 - 使用简短的方法名称,如on()off()emit() you can either create new instances with new Emitter() , or use Emitter(obj) to mix event capabilities into existing objects.您可以使用new Emitter()创建新实例,或者使用Emitter(obj)将事件功能混合到现有对象中。 Note this library is written for use with a CommonJS module system, but you can use it anywhere else by removing the module.exports = ... line.请注意,此库是为与 CommonJS 模块系统一起使用而编写的,但您可以通过删除module.exports = ...行在其他任何地方使用它。

If you want to listen a javascript object you have three ways:如果你想听一个 javascript 对象,你有三种方法:

About sup/pub pattern:关于 sup/pub 模式:

You need to publish events.您需要发布事件。

About native implementations:关于本机实现:

  • Object get/set operators is enough to listen add, remove, change, get events. Object get/set operators足以监听添加、删除、更改、获取事件。 Operators have good support .运营商有很好的支持 Problems only in IE8-.问题仅在 IE8- 中。 But if you want to use get/set in IE8 use Object.defineProperty but on DOM objects or use Object.defineProperty sham .但是如果你想在 IE8 中使用 get/set 使用Object.defineProperty但在 DOM 对象上或者使用 Object.defineProperty sham
  • Object.prototype.watch has the good ES5 polyfill . Object.prototype.watch具有良好的ES5填充工具
  • Proxy API needs ES Harmony support. Proxy API需要 ES Harmony 支持。

Object.observe example Object.observe 示例

var o = {};
Object.observe(o, function (changes) {
  changes.forEach(function (change) {
    // change.object contains changed object version
    console.log('property:', change.name, 'type:', change.type);
  });
});
o.x = 1     // property: x type: add
o.x = 2     // property: x type: update
delete o.x  // property: x type: delete

If you don't need true event features(such as bubbling, stopPropagation), then you can implement your own events.如果您不需要真正的事件功能(例如冒泡、停止传播),那么您可以实现自己的事件。 addEventListener is just an API of the DOM, so you don't really need it for your own objects outside the DOM. addEventListener 只是 DOM 的一个 API,因此对于 DOM 之外的自己的对象,您实际上并不需要它。 If you want to create an evented pattern around an object, here's a good way to do it that does not require any extra browser APIs and should be very backwards-compatible.如果你想围绕一个对象创建一个事件模式,这是一个不需要任何额外浏览器 API 并且应该非常向后兼容的好方法。

Let's say you have an object where you want a bunch of events to be triggered when the dispatch method is called:假设您有一个对象,您希望在调用 dispatch 方法时在其中触发一系列事件:

var OurDispatcher, dispatcher;

OurDispatcher = (function() {
  function OurDispatcher() {
    this.dispatchHandlers = [];
  }

  OurDispatcher.prototype.on = function(eventName, handler) {
    switch (eventName) {
      case "dispatch":
        return this.dispatchHandlers.push(handler);
      case "somethingElse":
        return alert('write something for this event :)');
    }
  };

  OurDispatcher.prototype.dispatch = function() {
    var handler, i, len, ref;
    ref = this.dispatchHandlers;
    for (i = 0, len = ref.length; i < len; i++) {
      handler = ref[i];
      setTimeout(handler, 0);
    }
  };

  return OurDispatcher;

})();

dispatcher = new OurDispatcher();

dispatcher.on("dispatch", function() {
  return document.body.innerHTML += "DISPATCHED</br>";
});

dispatcher.on("dispatch", function() {
  return document.body.innerHTML += "DISPATCHED AGAIN</br>";
});

dispatcher.dispatch();

It really doesn't have to be more complicated than that, for the most part.在大多数情况下,它真的不必比这更复杂。 This way you have some decent control over your events and you don't need to worry about backward-compatibility or external libraries because everything there is widely supported.这样你就可以很好地控制你的事件,而且你不需要担心向后兼容性或外部库,因为那里的一切都得到了广泛的支持。 Technically, you could even do without setTimeout and handle your callbacks without any APIs.从技术上讲,您甚至可以不用 setTimeout 并在没有任何 API 的情况下处理您的回调。 Anything else like stopPropagation() would have to be handled yourself.其他任何像 stopPropagation() 之类的东西都必须自己处理。

https://jsfiddle.net/ozsywxer/ https://jsfiddle.net/ozsywxer/

There are, of course, polyfills for CustomEvent, but unless I need advanced event features, I prefer to wrap my own eventing system into a "class" and extending other classes/functions with it.当然,CustomEvent 有 polyfills,但除非我需要高级事件功能,否则我更喜欢将我自己的事件系统包装到一个“类”中,并用它扩展其他类/函数。

Here's the CoffeeScript version, which is what the JavaScript is derived from: https://jsfiddle.net/vmkkbbxq/1/这是 CoffeeScript 版本,它是 JavaScript 的派生源: https : //jsfiddle.net/vmkkbbxq/1/

^^ A bit easier to understand. ^^ 比较容易理解。

There are two problems.有两个问题。

First, the iSubmit.addEventListener() method is actually a method on the EventTarget DOM interface:首先, iSubmit.addEventListener()方法其实是EventTarget DOM接口上的一个方法:

These are inteded for use only on DOM elements.这些仅用于 DOM 元素。 By adding it to the iSubmit object as a method, you're calling it on an object that is not an EventTarget .通过将它作为方法添加到iSubmit对象,您是在一个不是EventTarget的对象上调用它。 This is why Chrome throws an Uncaught TypeError: Illegal invocation JavaScript error.这就是 Chrome 抛出Uncaught TypeError: Illegal invocation JavaScript 错误的原因。

The first problem is critical, but if you could use EventTarget#addEventListener() your code would not work because the event is being added to iSubmit but dispatched from document .第一个问题很关键,但如果您可以使用EventTarget#addEventListener()您的代码将无法工作,因为该事件被添加到iSubmit但从document分派。 Generally, the same object's methods need to be used when attaching event listeners and dispatching events (unless you're using bubbling events, which is a different story - Note: bubbling is not restricted to JavaScript or DOM related events, for example ).一般情况下,同一对象的方法需要安装事件侦听器,并分派事件(除非你使用冒泡事件,这是时要使用不同的故事-注:冒泡并不限于JavaScript或DOM相关事件, 例如)。

Using custom events with your own objects is very normal.将自定义事件与您自己的对象一起使用是很正常的。 As Evan Yu mentioned , there are libraries for this.正如Evan Yu 提到的,有一些图书馆可以做到这一点。 Here are a couple:这里有几个:

I have used js-signals and like it quite a bit.我使用过js-signals并且非常喜欢它。 I have never used Wolfy87/EventEmitter , but it has a nice look to it.我从未使用过Wolfy87/EventEmitter ,但它看起来很不错。

Your example might look something like the following if you used js-signals如果您使用js-signals您的示例可能如下所示

jsFiddle js小提琴

var iSubmit = {
    finished: new signals.Signal(),
    test: function test(memo) {
        this.finished.dispatch(memo || {});
    }
};

iSubmit.finished.add(function(data) {
    console.log('finished:', data);
});

iSubmit.test('this is the finished data');


// alternatively
iSubmit.finished.dispatch('this is dispatched directly from the signal');

Just speculation;只是猜测; I haven't tried it myself.我自己没试过。 But you can create a dummy element and fire/listen to events on the dummy element.但是您可以创建一个虚拟元素并触发/监听虚拟元素上的事件。 Also, I prefer going without libraries.另外,我更喜欢没有图书馆。

function myObject(){
    //create "dummy" element
    var dummy = document.createElement('dummy');
    //method for listening for events
    this.on = function(event, func){dummy.addEventListener(event, func);};
    //you need a way to fire events
    this.fireEvent = function(event, obj){
      dummy.dispatchEvent(new CustomEvent(event, {detail: obj}));
    }
}
//now you can use the methods in the object constructor
var obj = new myObject();
obj.on("custom", function(e){console.log(e.detail.result)});
obj.fireEvent("custom", {result: "hello world!!!"});

If you are in a Node.js environment then you can use Node's EventEmitter class :如果您在 Node.js 环境中,那么您可以使用Node 的 EventEmitter 类

CustomObject.js自定义对象.js

const EventEmitter = require('events');

class CustomObject extends EventEmitter {
  constructor() {
    super();
  }

  doSomething() {
    const event = {message: 'Hello World!'};
    this.emit('myEventName', event);
  }
}

module.exports = CustomObject;

Usage:用法:

const CustomObject = require('./CustomObject');

// 1. Create a new instance
const myObject = new CustomObject();

// 2. Subscribe to events with ID "myEventName"
myObject.on('myEventName', function(event) {
  console.log('Received event', event);
});

// 3. Trigger the event emitter
myObject.doSomething();

If you want to use Node's EventEmitter outside of a Node.js environment, then you can use webpack (preferably v2.2 or later) to get a bundle of your CustomClass together with an EventEmitter polyfill (built by webpack).如果你想在 Node.js 环境之外使用 Node 的 EventEmitter,那么你可以使用webpack (最好是 v2.2 或更高版本)来获取你的CustomClass和 EventEmitter polyfill(由 webpack 构建)的包。

Here is how it works (assuming that you installed webpack globally using npm install -g webpack ):这是它的工作原理(假设您使用npm install -g webpack全局npm install -g webpack ):

  1. Run webpack CustomObject.js bundle.js --output-library=CustomObject运行webpack CustomObject.js bundle.js --output-library=CustomObject
  2. Include bundle.js in your HTML page (it will expose window.CustomObject )在你的 HTML 页面中包含bundle.js (它会暴露window.CustomObject
  3. There's no step three!没有第三步!

index.html索引.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
    <script src="bundle.js"></script>
  </head>
  <body>
    <script>
      // 1. Create a new instance
      const myObject = new window.CustomObject();

      // 2. Subscribe to events with ID "myEventName"
      myObject.on('myEventName', function(event) {
        console.log('Received event', event);
      });

      // 3. Trigger the event emitter
      myObject.doSomething();
    </script>
  </body>
</html>

Here's a simple event emitter:这是一个简单的事件发射器:

class EventEmitter {
    on(name, callback) {
        var callbacks = this[name];
        if (!callbacks) this[name] = [callback];
        else callbacks.push(callback);
    }

    dispatch(name, event) {
        var callbacks = this[name];
        if (callbacks) callbacks.forEach(callback => callback(event));
    }
}

Usage:用法:

var emitter = new EventEmitter();

emitter.on('test', event => {
    console.log(event);
});

emitter.dispatch('test', 'hello world');

I have been able to achieve this by wrapping an element in javascript class.我已经能够通过在 javascript 类中包装一个元素来实现这一点。 Important point is that the element does not have to exist in dom.重要的一点是元素不必存在于dom中。 Also, the element tag name can be anything such as the custom class name.此外,元素标记名称可以是任何内容,例如自定义类名称。

''' '''

class MyClass
{   
    
    constructor(options ) 
    {     
    
  
        this.el =  document.createElement("MyClass");//dummy element to manage events.    
        this.el.obj= this; //So that it is accessible via event.target.obj
      
    }

    addEventListener()
    {
 
        this.el.addEventListener(arguments[0],arguments[1]);

    }
    
 

     raiseEvent()
         {
//call this function or write code below when the event needs to be raised.

            var event = new Event('dataFound');
            event.data = messageData;
            this.el.dispatchEvent(event);
        }
}


let obj = new MyClass();
obj.addEventListener('dataFound',onDataFound);

function onDataFound()
{ 
console.log('onDataFound Handler called');
}

''' '''

This article explains creating custom events: http://www.sitepoint.com/javascript-custom-events/本文介绍了创建自定义事件: http : //www.sitepoint.com/javascript-custom-events/

here is an example:这是一个例子:

create the event -创建事件 -

var event = new CustomEvent(
    "newMessage",
    {
        detail: {
            message: "Hello World!",
            time: new Date(),
        },
        bubbles: true,
        cancelable: true
    }
);

assign the event to something -将事件分配给某事 -

document.getElementById("msgbox").dispatchEvent(event);

subscribe to the event -订阅事件 -

document.addEventListener("newMessage", newMessageHandler, false);

Usage: jsfiddle用法: jsfiddle

This is a naive approach but might work for some applications:这是一种天真的方法,但可能适用于某些应用程序:

CustomEventTarget.prototype = {

    'constructor': CustomEventTarget,

    on:   function( ev, el ) { this.eventTarget.addEventListener( ev, el ) },
    off:  function( ev, el ) { this.eventTarget.removeEventListener( ev, el ) },
    emit: function( ev ) { this.eventTarget.dispatchEvent( ev ) }

}

function CustomEventTarget() { this.eventTarget = new EventTarget }

I think you can use Object $Deferred and promises.我认为您可以使用 Object $Deferred 和 promises。 It'll let you do something like this:它会让你做这样的事情:

Stacked: bind multiple handlers anywhere in the application to the same promise event. Stacked:将应用程序中任意位置的多个处理程序绑定到同一个 promise 事件。

  var request = $.ajax(url);
  request.done(function () {
  console.log('Request completed');
});

// Somewhere else in the application // 应用程序中的其他地方

   request.done(function (retrievedData) {
     $('#contentPlaceholder').html(retrievedData);
   });

Parallel tasks: ask multiple promises to return a promise which alerts of their mutual completion.并行任务:要求多个 Promise 返回一个警告它们相互完成的 Promise。

$.when(taskOne, taskTwo).done(function () {
  console.log('taskOne and taskTwo are finished');
});

Sequential tasks: execute tasks in sequential order.顺序任务:按顺序执行任务。

 var step1, step2, url;

 url = 'http://fiddle.jshell.net';

 step1 = $.ajax(url);

 step2 = step1.then(
   function (data) {
       var def = new $.Deferred();

       setTimeout(function () {
           console.log('Request completed');
           def.resolve();
       },2000);

     return def.promise();

 },
   function (err) {
       console.log('Step1 failed: Ajax request');
   }
 );
 step2.done(function () {
     console.log('Sequence completed')
     setTimeout("console.log('end')",1000);
 });

Source here: http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt2-practical-use来源: http : //blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt2-practical-use

Here is how you do this with Node.js style syntax in the browser.以下是在浏览器中使用 Node.js 样式语法执行此操作的方法。

The Events class: Events类:

  • stores callbacks in a hash associated with event keys将回调存储在与事件键关联的哈希中
  • triggers the callbacks with the provided parameters使用提供的参数触发回调

To add the behavior to your own custom classes just extend the Events object (example below).要将行为添加到您自己的自定义类,只需扩展 Events 对象(下面的示例)。

class Events {
  constructor () {
    this._callbacks = {}
  }

  on (key, callback) {
    // create an empty array for the event key
    if (this._callbacks[key] === undefined) { this._callbacks[key] = [] }
    // save the callback in the array for the event key
    this._callbacks[key].push(callback)
  }

  emit (key, ...params) {
    // if the key exists
    if (this._callbacks[key] !== undefined) {
      // iterate through the callbacks for the event key
      for (let i=0; i<this._callbacks[key].length; i++) {
        // trigger the callbacks with all provided params
        this._callbacks[key][i](...params)
      }
    }
  }
}


// EXAMPLE USAGE

class Thing extends Events {
  constructor () {
    super()
    setInterval(() => {
      this.emit('hello', 'world')
    }, 1000)
  }
}

const thing = new Thing()

thing.on('hello', (data) => {
  console.log(`hello ${data}`)
})

Here is a link a github gist with this code: https://gist.github.com/alextaujenis/0dc81cf4d56513657f685a22bf74893d这是带有此代码的 github gist 链接: https : //gist.github.com/alextaujenis/0dc81cf4d56513657f685a22bf74893d

For anyone that's looking for an easy answer that works.对于任何正在寻找有效的简单答案的人。 I visited this document , only to learn that most browser doesn't support it.我访问了这个文档,才知道大多数浏览器都不支持它。 But at the bottom of the page, there was a link to this GitHub page that basically does what the Object.watch() and Object.unwatch() would have done, and it works for me!但是在页面底部,有一个指向这个 GitHub 页面的链接,它基本上完成了 Object.watch() 和 Object.unwatch() 会做的事情,它对我有用!

Here's how you can watch for changes您可以通过以下方式观察变化

/*
 * object.watch polyfill
 *
 * 2012-04-03
 *
 * By Eli Grey, http://eligrey.com
 * Public Domain.
 * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
 * https://gist.github.com/eligrey/384583
 */

// object.watch
if (!Object.prototype.watch) {
    Object.defineProperty(Object.prototype, "watch", {
          enumerable: false
        , configurable: true
        , writable: false
        , value: function (prop, handler) {
            var
              oldval = this[prop]
            , newval = oldval
            , getter = function () {
                return newval;
            }
            , setter = function (val) {
                oldval = newval;
                return newval = handler.call(this, prop, oldval, val);
            }
            ;

            if (delete this[prop]) { // can't watch constants
                Object.defineProperty(this, prop, {
                      get: getter
                    , set: setter
                    , enumerable: true
                    , configurable: true
                });
            }
        }
    });
}

// object.unwatch
if (!Object.prototype.unwatch) {
    Object.defineProperty(Object.prototype, "unwatch", {
          enumerable: false
        , configurable: true
        , writable: false
        , value: function (prop) {
            var val = this[prop];
            delete this[prop]; // remove accessors
            this[prop] = val;
        }
    });
}

And this should be your code:这应该是你的代码:

var object = {
    value: null,
    changeValue: function(newValue) {
        this.value = newValue;
    },
    onChange: function(callback) {
        this.watch('value', function(obj, oldVal, newVal) {
            // obj will return the object that received a change
            // oldVal is the old value from the object
            // newVal is the new value from the object

            callback();
            console.log("Object "+obj+"'s value got updated from '"+oldValue+"' to '"+newValue+"'");
            // object.changeValue("hello world");
            // returns "Object object.value's value got updated from 'null' to 'hello world'";

            // and if you want the function to stop checking for
            // changes you can always unwatch it with:
            this.unwatch('value');

            // you can retrieve information such as old value, new value
            // and the object with the .watch() method, learn more here:
            // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch
        })
    }
};

or as short as:或短如:

var object = { user: null };

// add a watch to 'user' value from object
object.watch('user', function() {
    // object user value changed
});

Use the createElement to create a dummy element.使用createElement创建一个虚拟元素。

typescript打字稿

class Person {
    name: string
    el: HTMLElement // event listener
    constructor(name: string) {
        this.name = name
        this.el = document.createElement("Person"); // dummy element to manage events
        (this.el as any).object = this // set dummy attribute. (Optional) So that it is accessible via `event.target.object`
    }

    AddEventListener(type: string, listener: any) {
        this.el.addEventListener(type, listener)
    }

    DispatchEvent(type: string, data: any = null) {
        const event = new Event(type);
        (event as any).data = data //dummy attribute (Optional)
        this.el.dispatchEvent(event)
    }
}

const carson = new Person("Carson")
carson.AddEventListener("Say", (e: Event) => {
    const person = (e.target as any).object as Person // get dummy attribute
    const data = (e as any).data // get dummy attribute
    if (data !== undefined && data.stopImmediatePropagation === true) {
        e.stopImmediatePropagation()
    }
    console.log(`${person.name}`, data)
})
carson.AddEventListener("Say", () => {
    console.log("Say2")
})

carson.DispatchEvent("Say")
// Output:
// Carson undefined
// Say2
carson.DispatchEvent("Say", "hello world!")
// Carson hello world!
// Say2
carson.DispatchEvent("Say", {stopImmediatePropagation: true})
// Carson {stopImmediatePropagation: true}

Runnable Example可运行示例

 <script> class Person { constructor(name) { this.name = name this.el = document.createElement("Person") // dummy element to manage events this.el.object = this // set dummy attribute. (Optional) So that it is accessible via `event.target.object` } AddEventListener(type, listener) { this.el.addEventListener(type, listener) } DispatchEvent(type, data) { const event = new Event(type) event.data = data // set dummy attribute this.el.dispatchEvent(event) } } const carson = new Person("Carson") carson.AddEventListener("Say", (e) => { const person = e.target.object // get dummy attribute const data = e.data // get dummy attribute if (data.== undefined && data.stopImmediatePropagation === true) { e.stopImmediatePropagation() } console.log(`${person,name}`. data) }) carson,AddEventListener("Say". (e) => { console.log("Say2") }) carson.DispatchEvent("Say") carson,DispatchEvent("Say". "hello world,") carson:DispatchEvent("Say", {stopImmediatePropagation: true}) </script>

With ES6 class , object & callbacks you can create your own custom event system with the following code:使用ES6 classobject和回调,您可以使用以下代码创建自己的自定义事件系统:

class ClassWithEvent {

    //Register a new event for the class
    RegisterEvent(event,Handler){
        var eventName = `event_on${event}`;
        if(this.hasOwnProperty(eventName) == false){ 
            this[eventName] = []; 
        }

        this[eventName].push(Handler);
    }

    //private unregister the event
    #unregisterEvent(event){
        var eventName = `event_on${event}`;
        delete this[eventName];
    }

    //raise event
    #dispatchEvent(name, event) {
        var eventName = `event_on${name}`;

        if (this.hasOwnProperty(eventName)) 
            this[eventName].forEach(callback => callback(event));
    }

    //public method
    sayhello(name){
        this.#dispatchEvent("beforehello",{'name':name,'method':'sayhello'});
        alert(`Hello ${name}`);
        this.#dispatchEvent("afterhello",{'name':name,'method':'sayhello'});
    }
}//EOC

Once defined you can call it as:定义后,您可以将其称为:

var ev = new ClassWithEvent();
ev.RegisterEvent("beforehello",(x)=> console.log(`Event:before ${x.name} ${x.method} oh`));
ev.RegisterEvent("afterhello",(x)=> console.log(`Event:after ${x.name} ${x.method} oh`));
ev.RegisterEvent("beforehello",(x)=> console.log(`Event2:before ${x.name} ${x.method} oh`));
ev.sayhello("vinod");

So in the code above we have registered 3 events handlers which will be invoked by #dispatchEvent() when we call the sayhello() method.所以在上面的代码中,我们注册了 3 个事件处理程序,当我们调用sayhello()方法时,这些事件处理程序将由#dispatchEvent()调用。

The instance of the class will look something like this:该类的实例将如下所示:

在此处输入图像描述

We can see in the image above the onbeforehello event has two handlers and it will be invoke in the sequence it is defined.我们可以在上图中看到onbeforehello事件有两个处理程序,它将按照定义的顺序调用。


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

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