返回介绍

createWrapper

发布于 2019-05-31 13:12:51 字数 2508 浏览 1049 评论 0 收藏 0

Defines a wrapper for custom StreamLikeSequences. This is useful if you want a way to handle a stream of events as a sequence, but you can't use Lazy's existing interface (i.e., you're wrapping an object from a library with its own custom events).

This method defines a factory: that is, it produces a function that can be used to wrap objects and return a Sequence. Hopefully the example will make this clear.

Signature

Lazy.createWrapper = function(initializer) { /*...*/ }
Lazy.createWrapper = function createWrapper(initializer) {
  var ctor = function() {
this.listeners = [];
  };

  ctor.prototype = Object.create(StreamLikeSequence.prototype);

  ctor.prototype.each = function(listener) {
this.listeners.push(listener);
  };

  ctor.prototype.emit = function(data) {
var listeners = this.listeners;

for (var len = listeners.length, i = len - 1; i >= 0; --i) {
  if (listeners[i](data) === false) {
    listeners.splice(i, 1);
  }
}
  };

  return function() {
var sequence = new ctor();
initializer.apply(sequence, arguments);
return sequence;
  };
}
NameType(s)Description
initializerFunction

An initialization function called on objects created by this factory. this will be bound to the created object, which is an instance of StreamLikeSequence. Use emit to generate data for the sequence.

returnsFunction

A function that creates a new StreamLikeSequence, initializes it using the specified function, and returns it.

Examples

var factory = Lazy.createWrapper(function(eventSource) {
  var sequence = this;

  eventSource.handleEvent(function(data) {
sequence.emit(data);
  });
});

var eventEmitter = {
  triggerEvent: function(data) {
eventEmitter.eventHandler(data);
  },
  handleEvent: function(handler) {
eventEmitter.eventHandler = handler;
  },
  eventHandler: function() {}
};

var events = [];

factory(eventEmitter).each(function(e) {
  events.push(e);
});

eventEmitter.triggerEvent('foo');
eventEmitter.triggerEvent('bar');

events // => ['foo', 'bar']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文