简体   繁体   English

编写自定义.on()/。bind()JavaScript的最佳方式

[英]Most performant way to write custom .on()/.bind() JavaScript

I write lots of little libraries and modules and usually these libraries and modules have have some events associated with them. 我写了很多小的库和模块,通常这些库和模块都有一些与之相关的事件。 Until now I've been writing these like (shortened down a lot): 到现在为止,我一直在写这些(缩短了很多):

Library.prototype.on = function(event, callback){
  self = this;
  self.events[event] = callback;
}

then a user would do something such as: 然后用户会做以下事情:

Library.on('foo',function(){
  console.log('bar');
});

Is there a better more performant way to do this though or is this a standard way of implementing this? 有没有更好的更高效的方法来做到这一点,或者这是实现这一目标的标准方法? I want a simple API that i can drop into any JS project to support this behavior. 我想要一个简单的API,我可以放入任何JS项目来支持这种行为。

var EventEmitter = {
    constructor: function _constructor() {
        this._events = [];
        return this;
    },
    on: function _on(ev, handler) {
        if (!this._events[ev]) {
            this._events[ev] = [];
        }
        this._events[ev].push(handler);
    },
    removeListener: function _removeListener(ev, handler) {
        if (!this._events[ev]) return;
        this._events[ev].splice(this._events[ev].indexOf(handler), 1);
    },
    removeAll: function _removeAll(ev) {
        delete this._events[ev];
    },
    emit: function _emit(ev, data) {
        if (!this._events[ev]) return;
        this._events[ev].forEach(invokeHandler);

        function invokeHandler(handler) {
            handler(data);
        }
    }
};

I have a small EventEmitter I use when I need quick and dirty custom events. 当我需要快速和脏的自定义事件时,我有一个小的EventEmitter

The only difference between mine and your implementation is that mine allows multiple callbacks per event. 我和你的实现之间的唯一区别是我的每个事件允许多个回调。

For anything serious I use an event library like EventEmitter2 对于任何严肃的事情,我使用像EventEmitter2这样的事件库

You are looking for Observer Pattern for JavaScript. 您正在寻找JavaScript的观察者模式

Spine and Backbone have some nice implementations for observers. SpineBackbone为观察者提供了一些很好的实现。

But a new nice pattern is the Promises pattern that are documented at CommonJS 但一个新的好模式是CommonJS记录的Promises模式

jQuery 1.7 have implemented and is deeply using the promise pattern. jQuery 1.7已经实现并且正在深度使用promise模式。

My favorite implementation from Promises pattern is the Q from @kriskowal 我从承诺模式最喜欢的实施是Q从@kriskowal

I hope, that this sources help you in your quest. 我希望,这些资源可以帮助您完成任务。

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

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