范围内回调的最佳做法 [英] Best practices for callbacks within a scope

查看:98
本文介绍了范围内回调的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,在构造函数中,您使用lambda函数订阅事件:

  function Something(){
this.on('message',function(){...});
}
util.inherits(Something,events.EventEmitter);

这个功能很好,但扩展不好。方法使用继承更好:

  function Something(){
this.on('message',this._onMessage );
}
util.inherits(Something,events.EventEmitter);

Something.prototype._onMessage = function(){...};

保持这些事件处理函数的最佳做法是什么?

解决方案

如果我正确地理解了这个问题,那么我认为这取决于你愿意做多少改变。 / p>

您的第二个例子打开子类(或实际上是任何类)的选项来覆盖处理程序的代码,这不一定是一件好事。



第一个例子阻止了重写,但是在构造函数内部存在匿名函数(有时包含大量代码)。然而,这个代码可以被提取到另一个私有函数(不在原型上,只是模块文件中的常规函数​​)。



open-close principal 处理这种问题。


Typically, in "constructor" you subscribe to events with lambda-functions:

function Something(){
   this.on('message', function(){ ... });
}
util.inherits(Something, events.EventEmitter);

This works well but extends bad. Methods play better with inheritance:

function Something(){
   this.on('message', this._onMessage);
}
util.inherits(Something, events.EventEmitter);

Something.prototype._onMessage = function(){ ... };

What are the best practices to keep these event handler functions?

解决方案

if i understood the question correctly then i think that it depends on how much open for changes you are willing to be.

your second example opens the option for subclasses (or, actually, any class) to override the handler's code, which isn't necessarily a good thing.

the first example prevents overriding but at the cost of having anonymous functions (sometimes containing a lot of code) inside your constructor. however, this code can be extracted to another private function (not on the prototype, just a regular function inside the module's file).

the open-close principal deals with this kind of questions.

这篇关于范围内回调的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆