createWrapper
优质
小牛编辑
135浏览
2023-12-01
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; }; }
Name | Type(s) | Description |
---|---|---|
initializer | Function | An initialization function called on objects created by this factory. |
returns | Function | 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']