Type of stream elements
Combines Properties, EventStreams and constant values using a template
object. For instance, assuming you've got streams or properties named
password
, username
, firstname
and lastname
, you can do
var password, username, firstname, lastname; // <- properties or streams
var loginInfo = Bacon.combineTemplate({
magicNumber: 3,
userid: username,
passwd: password,
name: { first: firstname, last: lastname }})
.. and your new loginInfo property will combine values from all these streams using that template, whenever any of the streams/properties get a new value. For instance, it could yield a value such as
{ magicNumber: 3,
userid: "juha",
passwd: "easy",
name : { first: "juha", last: "paananen" }}
In addition to combining data from streams, you can include constant values in your templates.
Note that all Bacon.combine* methods produce a Property instead of an EventStream.
If you need the result as an EventStream
you might want to use property.changes()
Bacon.combineWith(function(v1,v2) { .. }, stream1, stream2).changes()
Delay function used by bufferWithTime
and bufferWithTimeOrCount
. Your implementation should
call the given void function to cause a buffer flush.
Join pattern type, allowing up to 6 sources per pattern.
Join pattern consisting of a single EventStream and a mapping function.
Join pattern consisting of a 2 Observables and a combinator function. At least one of the Observables must be an EventStream.
Join pattern consisting of a 3 Observables and a combinator function. At least one of the Observables must be an EventStream.
Join pattern consisting of a 4 Observables and a combinator function. At least one of the Observables must be an EventStream.
Join pattern consisting of a 5 Observables and a combinator function. At least one of the Observables must be an EventStream.
Join pattern consisting of a 6 Observables and a combinator function. At least one of the Observables must be an EventStream.
A polled function used by fromPoll
Return type for various Sink functions. Indicates whether or not the sink
desires more input from its source. See Bacon.fromBinder
for example.
an "unsubscribe" function returned by subscribe et al. You can cancel your subscription by calling this function.
Update pattern type, allowing up to 6 sources per pattern.
Update pattern consisting of a single EventStream and a accumulator function.
Update pattern consisting of 2 Observables and an accumulrator function. At least one of the Observables must be an EventStream.
Update pattern consisting of 3 Observables and an accumulrator function. At least one of the Observables must be an EventStream.
Update pattern consisting of 4 Observables and an accumulrator function. At least one of the Observables must be an EventStream.
Update pattern consisting of 5 Observables and an accumulrator function. At least one of the Observables must be an EventStream.
Update pattern consisting of 6 Observables and an accumulrator function. At least one of the Observables must be an EventStream.
Reply for "more data, please".
Reply for "no more data, please".
Bacon.js version as string
Combines Properties, EventStreams and constant values so that the result Property will have an array of the latest values from all sources as its value. The inputs may contain both Properties and EventStreams.
property = Bacon.constant(1)
stream = Bacon.once(2)
constant = 3
Bacon.combineAsArray(property, stream, constant)
# produces the value [1,2,3]
streams and properties to combine
Combines given n Properties and
EventStreams using the given n-ary function f(v1, v2 ...)
.
To calculate the current sum of three numeric Properties, you can do
function sum3(x,y,z) { return x + y + z }
Bacon.combineWith(sum3, p1, p2, p3)
Concatenates given array of EventStreams or Properties. Works by subscribing to the first source, and listeing to that until it ends. Then repeatedly subscribes to the next source, until all sources have ended.
See concat
Creates a constant property with value x
.
Creates an EventStream that delivers the given
series of values (given as array) to the first subscriber. The stream ends after these
values have been delivered. You can also send Bacon.Error
events, or
any combination of pure values and error events like this:
`Bacon.fromArray([1, new Bacon.Error()])
Array of values or events to repeat
If none of the other factory methods above apply, you may of course roll your own EventStream by using fromBinder
.
Bacon.fromBinder(subscribe)
The parameter subscribe
is a function that accepts a sink
which is a function that your subscribe
function can "push" events to.
For example:
var stream = Bacon.fromBinder(function(sink) {
sink("first value")
sink([new Bacon.Next("2nd"), new Bacon.Next("3rd")])
sink(new Bacon.Error("oops, an error"))
sink(new Bacon.End())
return function() {
// unsub functionality here, this one's a no-op
}
})
stream.log()
As shown in the example, you can push
"first value"
Event
object including Bacon.Error
(wraps an error) and Bacon.End
(indicates
stream end).Other examples can be found on JSFiddle and the Bacon.js blog.
The subscribe
function must return a function. Let's call that function
unsubscribe
. The returned function can be used by the subscriber (directly or indirectly) to
unsubscribe from the EventStream. It should release all resources that the subscribe function reserved.
The sink
function may return Bacon.noMore
(as well as Bacon.more
or any other value). If it returns Bacon.noMore
, no further events will be consumed
by the subscriber. The subscribe
function may choose to clean up all resources at this point (e.g.,
by calling unsubscribe
). This is usually not necessary, because further calls to sink
are ignored,
but doing so can increase performance in rare cases.
The EventStream will wrap your subscribe
function so that it will
only be called when the first stream listener is added, and the unsubscribe
function is called only after the last listener has been removed.
The subscribe-unsubscribe cycle may of course be repeated indefinitely,
so prepare for multiple calls to the subscribe function.
Type of stream elements
Creates an EventStream from a function that accepts a callback. The function is supposed to call its callback just once. For example:
Bacon.fromCallback(callback => callback("bacon"))
This would create a stream that outputs a single value "Bacon!" and ends after that. The use of setTimeout causes the value to be delayed by 1 second.
You can also give any number of arguments to fromCallback
, which will be
passed to the function. These arguments can be simple variables, Bacon
EventStreams or Properties. For example the following will output "Bacon rules":
bacon = Bacon.constant('bacon')
Bacon.fromCallback(function(a, b, callback) {
callback(a + ' ' + b);
}, bacon, 'rules').log();
Creates an EventStream from an ES Observable. Input can be any ES Observable implementation including RxJS and Kefir.
creates an EventStream from events
on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using on
/off
methods.
You can also pass an optional function that transforms the emitted
events' parameters.
The simple form:
Bacon.fromEvent(document.body, "click").onValue(function() { alert("Bacon!") })
Using a binder function:
Bacon.fromEvent(
window,
function(binder, listener) {
binder("scroll", listener, {passive: true})
}
).onValue(function() {
console.log(window.scrollY)
})
Type of stream elements
Behaves the same way as Bacon.fromCallback
,
except that it expects the callback to be called in the Node.js convention:
callback(error, data)
, where error is null if everything is fine. For example:
var Bacon = require('baconjs').Bacon,
fs = require('fs');
var read = Bacon.fromNodeCallback(fs.readFile, 'input.txt');
read.onError(function(error) { console.log("Reading failed: " + error); });
read.onValue(function(value) { console.log("Read contents: " + value); });
Polls given function with given interval.
Function should return Events: either Bacon.Next
or Bacon.End
. Polling occurs only
when there are subscribers to the stream. Polling ends permanently when
f
returns Bacon.End
.
Type of stream elements
poll interval in milliseconds
function to be polled
Creates an EventStream from a Promise object such as JQuery Ajax.
This stream will contain a single value or an error, followed immediately by stream end.
You can use the optional abort flag (i.e. ´fromPromise(p, true)´ to have the abort
method of the given promise be called when all subscribers have been removed from the created stream.
You can also pass an optional function that transforms the promise value into Events. The default is to transform the value into [new Bacon.Next(value), new Bacon.End()]
.
Check out this example.
should we call the abort
method of the Promise on unsubscribe. This is a nonstandard feature you should probably ignore.
Returns true if the given event is a Value, i.e. a Next or an Initial value of an Observable.
Repeats the single element indefinitely with the given interval (in milliseconds)
Type of stream elements
Repeat delay in milliseconds
The single value to repeat
Returns true if the given event is an Error event of an Observable.
Returns true if the given object is an Event.
Creates a single-element stream that emits given value after given delay and ends.
Type of stream elements
delay in milliseconds
value to be emitted
Merges given array of EventStreams or Properties, by collecting the values from all of the sources into a single EventStream.
See also merge
.
Creates an EventStream that immediately ends.
Type of stream elements
A shorthand for combining multiple sources (streams, properties, constants) as array and assigning the side-effect function f for the values. The following example would log the number 3.
function f(a, b) { console.log(a + b) }
Bacon.onValues(Bacon.constant(1), Bacon.constant(2), f)
Creates an EventStream that delivers the given
single value for the first subscriber. The stream will end immediately
after this value. You can also send an Bacon.Error
event instead of a
value: Bacon.once(new Bacon.Error("fail"))
.
Type of stream elements
the value or event to emit
Calls generator function which is expected to return an observable. The returned EventStream contains values and errors from the spawned observable. When the spawned observable ends, the generator is called again to spawn a new observable.
This is repeated until the generator returns a falsy value
(such as undefined
or false
).
The generator function is called with one argument — iteration number starting from 0
.
Here's an example:
Bacon.repeat(function(i) {
if (i < 3) {
return Bacon.once(i);
} else {
return false;
}
}).log()
The example will produce values 0, 1 and 2.
Type of stream elements
Repeats given elements indefinitely
with given interval in milliseconds. For example, repeatedly(10, [1,2,3])
would lead to 1,2,3,1,2,3...
to be repeated indefinitely.
Type of stream elements
between values, in milliseconds
array of values to repeat
Used to retry the call when there is an Error
event in the stream produced by the source
function.
var triggeringStream, ajaxCall // <- ajaxCall gives Errors on network or server errors
ajaxResult = triggeringStream.flatMap(function(url) {
return Bacon.retry({
source: function(attemptNumber) { return ajaxCall(url) },
retries: 5,
isRetryable: function (error) { return error.httpStatusCode !== 404; },
delay: function(context) { return 100; } // Just use the same delay always
})
})
(click for details)
Creates a stream containing given values (given as array). Delivered with given interval in milliseconds.
Type of stream elements
between elements, in milliseconds
Creates a stream that ends after given amount of milliseconds, without emitting any values.
Type of stream elements
duration of silence in milliseconds
Adds your function as a "spy" that will get notified on all new Observables. This will allow a visualization/analytics tool to spy on all Bacon activity.
Bacon.try
is a helper for creating an EventStream of a single value, or a single Error event in case the given
function throws an exception.
For example, you can use Bacon.try
to handle JSON parse errors:
var jsonStream = Bacon
.once('{"this is invalid json"')
.flatMap(Bacon.try(JSON.parse))
jsonStream.onError(function(err) {
console.error("Failed to parse JSON", err)
})
Creates a Property from an initial value and updates the value based on multiple inputs.
The inputs are defined similarly to Bacon.when
, like this:
var result = Bacon.update(
initial,
[x,y,z, (previous,x,y,z) => { ... }],
[x,y, (previous,x,y) => { ... }])
As input, each function above will get the previous value of the result
Property, along with values from the listed Observables.
The value returned by the function will be used as the next value of result
.
Just like in Bacon.when
, only EventStreams will trigger an update, while Properties will be just sampled.
So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream.
Here's a simple gaming example:
let scoreMultiplier = Bacon.constant(1)
let hitUfo = Bacon.interval(1000)
let hitMotherShip = Bacon.later(10000)
let score = Bacon.update(
0,
[hitUfo, scoreMultiplier, (score, _, multiplier) => score + 100 * multiplier ],
[hitMotherShip, (score, _) => score + 2000 ]
)
In the example, the score
property is updated when either hitUfo
or hitMotherShip
occur. The scoreMultiplier
Property is sampled to take multiplier into account when hitUfo
occurs.
The when
method provides a generalization of the zip
function. While zip
synchronizes events from multiple streams pairwse, the join patterns used in when
allow
the implementation of more advanced synchronization patterns.
Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick.
Bacon.when(
[tick, keyEvent, function(_, k) { handleKeyEvent(k); return handleTick(); }],
[tick, handleTick])
Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick.
Join patterns are indeed a generalization of zip, and for EventStreams, zip is equivalent to a single-rule join pattern. The following observables have the same output, assuming that all sources are EventStreams.
Bacon.zipWith(a,b,c, combine)
Bacon.when([a,b,c], combine)
Note that Bacon.when
does not trigger updates for events from Properties though;
if you use a Property in your pattern, its value will be just sampled when all the
other sources (EventStreams) have a value. This is useful when you need a value of a Property
in your calculations. If you want your pattern to fire for a Property too, you can
convert it into an EventStream using property.changes()
or property.toEventStream()
result type
Join patterns
Zips the array of EventStreams / Properties in to a new EventStream that will have an array of values from each source as its value. Zipping means that events from each source are combined pairwise so that the 1st event from each source is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source.
Be careful not to have too much "drift" between streams. If one stream produces many more values than some other excessive buffering will occur inside the zipped observable.
Example:
x = Bacon.fromArray([1,2,3])
y = Bacon.fromArray([10, 20, 30])
z = Bacon.fromArray([100, 200, 300])
Bacon.zipAsArray(x, y, z)
# produces values [1, 10, 100], [2, 20, 200] and [3, 30, 300]
Like zipAsArray
but uses the given n-ary
function to combine the n values from n sources, instead of returning them in an Array.
JQuery/Zepto integration support
Creates an EventStream from events on a jQuery or Zepto.js object. You can pass optional arguments to add a jQuery live selector and/or a function that processes the jQuery event and its parameters, if given, like this:
$("#my-div").asEventStream("click", ".more-specific-selector")
$("#my-div").asEventStream("click", ".more-specific-selector", function(event, args) { return args[0] })
$("#my-div").asEventStream("click", function(event, args) { return args[0] })
Note: you need to install the asEventStream
method on JQuery by calling
init() as in Bacon.$.init($)
.
Installs the asEventStream to the given jQuery/Zepto object (the $
object).
Generated using TypeDoc
Binder function used in fromBinder