Show Menu

Bacon.js Cheat Sheet by ProLoser

https://github.com/raimohanska/bacon.js

Observable Interface

obse­rva­ble.ma­p(f)
maps values using given function, returning a new EventS­tream. Instead of a function, you can also provide a constant value. Further, you can use a property extractor string like ".ke­yCo­de". So, if f is a string starting with a dot, the elements will be mapped to the corres­ponding field/­fun­ction in the event value. For instance map(".k­eyC­ode­") will pluck the keyCode field from the input values. If keyCode was a function, the result stream would contain the values returned by the function. The Function Constr­uction rules below apply here.
stre­am.m­ap­(pr­ope­rty)
maps the stream events to the current value of the given property. This is equivalent to prope­rty.sa­mpl­edB­y(s­tream)
obse­rva­ble.ma­pEr­ror­(f)
maps errors using given function. More specif­ically, feeds the "­err­or" field of the error event to the function and produces a "­Nex­t" event based on the return value. Function Constr­uction rules apply. You can omit the argument to produce a Next event with undef­ined value.
obse­rva­ble.ma­pEn­d(f)
Adds an extra Next event just before End. The value is created by calling the given function when the source stream ends. Instead of a function, a static value can be used. You can omit the argument to produce a Next event with undef­ined value.
obse­rva­ble.fi­lte­r(f)
filters values using given predicate function. Instead of a function, you can use a constant value (true/­false) or a property extractor string (like ".is­Val­uab­le") instead. Just like with map, indeed.
obse­rva­ble.fi­lte­r(p­rop­erty)
filters values based on the value of a property. Event will be included in output iff the property holds true at the time of the event.
obse­rva­ble.ta­keW­hil­e(f)
takes while given predicate function holds true
obse­rva­ble.ta­ke(n)
takes at most n elements from the stream. Equals to Bacon.n­ever() if n <= 0.
obse­rva­ble.ta­keU­nti­l(s­tre­am2)
takes elements from source until a Next event appears in the other stream. If other stream ends without value, it is ignored
obse­rva­ble.sk­ip(n)
skips the first n elements from the stream
obse­rva­ble.de­lay­(de­lay)
delays the stream­/pr­operty by given amount of millis­econds. Does not delay the initial value of a Property.
obse­rva­ble.th­rot­tle­(de­lay)
throttles stream­/pr­operty by given amount of millis­econds. Events are emitted with the minimum interval of delay. The implem­ent­ation is based on stream.bu­ffe­rWi­thTime. Does not affect emitting the initial value of a Property.
obse­rva­ble.de­bou­nce­(de­lay)
throttles stream­/pr­operty by given amount of millis­econds, but so that event is only emitted after the given "­quiet period­". Does not affect emitting the initial value of a Property. The difference of throttle and debounce is the same as it is in the same methods in jQuery.
obse­rva­ble.de­bou­nce­Imm­edi­ate­(de­lay)
passes the first event in the stream through, but after that, only passes events after a given number of millis­econds have passed since previous output.
obse­rva­ble.do­Act­ion­(f)
returns a stream­/pr­operty where the function f is executed for each value, before dispat­ching to subscr­ibers. This is useful for debugging, but also for stuff like calling the preven­tDe­fault() method for events. In fact, you can also use a proper­ty-­ext­ractor string instead of a function, as in ".pr­eve­ntD­efa­ult­".
obse­rva­ble.no­t()
returns a stream­/pr­operty that inverts boolean values
obse­rva­ble.fl­atM­ap(f)
for each element in the source stream, spawn a new stream using the function f. Collect events from each of the spawned streams into the result Event­Str­eam. This is very similar to selectMany in RxJs. Note that instead of a function, you can provide a stream­/pr­operty too. Also, the return value of function f can be either an Observable (strea­m/p­rop­erty) or a constant value. The result of flatMap is always an Event­Str­eam. strea­m.f­lat­Map() can be used conven­iently with Bacon.on­ce() and Bacon.ne­ver() for converting and filtering at the same time, including only some of the results.
obse­rva­ble.fl­atM­apL­ate­st(f)
like flatMap, but instead of including events from all spawned streams, only includes them from the latest spawned stream. You can think this as switching from stream to stream. The old name for this method is switch. Note that instead of a function, you can provide a stream­/pr­operty too.
obse­rva­ble.fl­atM­apF­irs­t(f)
like flatMap, but doesn't spawns a new stream only if the previously spawned stream has ended.
obse­rva­ble.sc­an(­seed, f)
scans stream­/pr­operty with given seed value and accumu­lator function, resulting to a Property. For example, you might use zero as seed and a "­plu­s" function as the accumu­lator to create an "­int­egr­al" property. Instead of a function, you can also supply a method name such as ".co­nca­t", in which case this method is called on the accumu­lator value and the new stream value is used as argument.
obse­rva­ble.fo­ld(­seed, f)
is like scan but only emits the final value, i.e. the value just before the observable ends. Returns a Property.
obse­rva­ble.re­duc­e(s­eed­,f)
synonym for fold.
obse­rva­ble.di­ff(­start, f)
returns a Property that represents the result of a comparison between the previous and current value of the Observ­able. For the initial value of the Observ­able, the previous value will be the given start.
obse­rva­ble.zi­p(o­ther, f)
return an EventS­tream with elements pair-wise lined up with events from this and the other stream. A zipped stream will publish only when it has a value from each stream and will only produce values up to when any single stream ends. Be careful not to have too much "­dri­ft" between streams. If one stream produces many more values than some other excessive buffering will occur inside the zipped observ­able.
obse­rva­ble.sl­idi­ngW­ind­ow(­max[, min])
returns a Property that represents a "­sliding window­" into the history of the values of the Observ­able. The result Property will have a value that is an array containing the last n values of the original observ­able, where n is at most the value of the max argument, and at least the value of the min argument. If the min argument is omitted, there's no lower limit of values.
obse­rva­ble.lo­g()
logs each value of the Observable to the console. It optionally takes arguments to pass to consol­e.log() alongside each value. To assist with chaining, it returns the original Observ­able. Note that as a side-e­ffect, the observable will have a constant listener and will not be garbag­e-c­oll­ected. So, use this for debugging only and remove from production code.
obse­rva­ble.co­mbi­ne(­pro­perty2, f)
combines the latest values of the two streams or properties using a two-arg function. Similarly to scan, you can use a method name instead, so you could do a.com­bine(b, ".co­nca­t") for two properties with array value. The result is a Property.
obse­rva­ble.wi­thS­tat­eMa­chi­ne(­ini­tState, f)
lets you run a state machine on an observ­able. Give it an initial state object and a state transf­orm­ation function that processes each incoming event and returns and array containing the next state and an array of output events.
obse­rva­ble.de­cod­e(m­app­ing)
decodes input using the given mapping. Is a bit like a switch­-case or the decode function in Oracle SQL. For example, the following would map the value 1 into the the string "­mik­e" and the value 2 into the value of the who property.
Both EventS­tream and Property share the Observable interface, and hence share a lot of methods. Common methods are listed below.
https:­//g­ith­ub.c­om­/ra­imo­han­ska­/ba­con.js­#co­mmo­n-m­eth­ods­-in­-ev­ent­str­eam­s-a­nd-­pro­perties
 

EventS­tream

Baco­n.E­ven­tSt­ream
a stream of events
stre­am.o­nV­alu­e(f)
subscribes a given handler function to event stream. Function will be called for each new value in the stream. This is the simplest way to assign a side-e­ffect to a stream. The difference to the subscribe method is that the actual stream values are received, instead of Event objects. Function Constr­uction rules below apply here.
stre­am.o­nV­alu­es(f)
like onValue, but splits the value (assuming its an array) as function arguments to f
stre­am.o­nE­nd(f)
subscribes a callback to stream end. The function will be called when the stream ends.
stre­am.s­ub­scr­ibe­(f)
subscribes given handler function to event stream. Function will receive Event objects (see below). The subscr­ibe() call returns a unsubs­cribe function that you can call to unsubs­cribe. You can also unsubs­cribe by returning Bacon.n­oMore from the handler function as a reply to an Event.
stre­am.s­ki­pDu­pli­cat­es(­[is­Equ­al])
drops consec­utive equal elements. So, from [1, 2, 2, 1] you'd get [1, 2, 1]. Uses the === operator for equality checking by default. If the isEqual argument is supplied, checks by calling isEqua­l(o­ldV­alue, newValue). For instance, to do a deep compar­iso­n,you can use the isEqual function from unders­core.js like stream.sk­ipD­upl­ica­tes­(_.i­sE­qual).
stre­am1.co­nca­t(s­tre­am2)
concat­enates two streams into one stream so that it will deliver events from stream1 until it ends and then deliver events from stream2. This means too that events from stream2, occurring before the end of stream1 will not be included in the result stream.
stre­am.m­er­ge(­str­eam2)
merges two streams into one stream that delivers events from both
stre­am.b­uf­fer­Wit­hTi­me(­del­ay)
buffers stream events with given delay. The buffer is flushed at most once in the given delay. So, if your input contains [1,2,3­,4,­5,6,7], then you might get two events containing [1,2,3,4] and [5,6,7] respec­tively, given that the flush occurs between numbers 4 and 5.
stre­am.b­uf­fer­Wit­hTi­me(f)
works with a given "­def­er-­fun­cti­on" instead of a delay. Here's a simple example, which is equivalent to stream.bu­ffe­rWi­thT­ime­(10): stream.bu­ffe­rWi­thT­ime­(fu­nct­ion(f) { setTim­eout(f, 10) })
stre­am.b­uf­fer­Wit­hCo­unt­(co­unt)
buffers stream events with given count. The buffer is flushed when it contains the given number of elements. So, if you buffer a stream of [1, 2, 3, 4, 5] with count 2, you'll get output events with values [1, 2], [3, 4] and [5].
stre­am.b­uf­fer­Wit­hTi­meO­rCo­unt­(delay, count)
buffers stream events and flushes when either the buffer contains the given number elements or the given amount of millis­econds has passed since last buffered event.
stre­am.t­oP­rop­ert­y()
creates a Property based on the EventS­tream. Without arguments, you'll get a Property without an initial value. The Property will get its first actual value from the stream, and after that it'll always have a current value.
stre­am.t­oP­rop­ert­y(i­nit­ial­Val­ue)
creates a Property based on the EventS­tream with the given initial value that will be used as the current value until the first value comes from the stream.
stre­am1.aw­ait­ing­(st­rea­m2)
creates a Property that indicates whether stream1 is awaiting stream2, i.e. has produced a value after the latest value from stream2. This is handy for keeping track whether we are currently awaiting an AJAX response: var showAj­axI­ndi­cator = ajaxRe­que­st.a­wa­iti­ng(­aja­xRe­sponse)

Bus

new Bacon.B­us()
returns a new Bus.
bus.p­us­h(x)
pushes the given value to the stream.
bus.e­nd()
ends the stream. Sends an End event to all subscr­ibers. After this call, there'll be no more events to the subscr­ibers. Also, the Bus push and plug methods have no effect.
bus.e­rr­or(e)
sends an Error with given message to all subscr­ibers
bus.p­lu­g(s­tre­am)
plugs the given stream to the Bus. All events from the given stream will be delivered to the subscr­ibers of the Bus. Returns a function that can be used to unplug the same stream. The plug method practi­cally allows you to merge in other streams after the creation of the Bus. I've found Bus quite useful as an event broadcast mechanism in the Worzone game, for instance.
Bus is an EventS­tream that allows you to push values into the stream. It also allows pluggin other streams into the Bus. The Bus practi­cally merges all plugged-in streams and the values pushed using the push method.

https:­//g­ith­ub.c­om­/ra­imo­han­ska­/ba­con.js­?ut­m_s­our­ce=­jav­asc­rip­twe­ekl­y&­utm­_me­diu­m=e­mai­l#bus
 

Property

Baco­n.P­rop­erty
a reactive property. Has the concept of "­current value". You can create a Property from an EventS­tream by using either toProperty or scan method. Note depending on how a Property is created, it may or may not have an initial value.
Baco­n.c­ons­tan­t(x)
creates a constant property with value x.
prop­ert­y.s­ubs­cri­be(f)
subscribes a handler function to property. If there's a current value, an Initial event will be pushed immedi­ately. Next event will be pushed on updates and an End event in case the source EventS­tream ends.
prop­ert­y.o­nVa­lue­(f)
similar to eventS­tre­am.o­nV­alue, except that also pushes the initial value of the property, in case there is one. See Function Constr­uction rules below for different forms of calling this method.
prop­ert­y.o­nVa­lue­s(f)
like onValue, but splits the value (assuming its an array) as function arguments to f
prop­ert­y.o­nEn­d(f)
subscribes a callback to stream end. The function will be called when the source stream of the property ends.
prop­ert­y.a­ssi­gn(obj, method, [para­m...])
calls the method of the given object with each value of this Property. You can optionally supply arguments which will be used as the first arguments of the method call. For instance, if you want to assign your Property to the "­dis­abl­ed" attribute of a JQuery object, you can do this: myProp­ert­y.a­ssi­gn(­$("#­my-­but­ton­"), "­att­r", "­dis­abl­ed") A simpler example would be to toggle the visibility of an element based on a Property: myProp­ert­y.a­ssi­gn(­$("#­my-­but­ton­"), "­tog­gle­") Note that the assign method is actually just a synonym for onValue and the function constr­uction rules below apply to both.
prop­ert­y.s­amp­le(­int­erv­al)
creates an EventS­tream by sampling the property value at given interval (in millis­econds)
prop­ert­y.s­amp­led­By(­str­eam)
creates an EventS­tream by sampling the property value at each event from the given stream. The result EventS­tream will contain the property value at each event in the source stream.
prop­ert­y.s­amp­led­By(­pro­per­ty)
creates a Property by sampling the property value at each event from the given property. The result Property will contain the property value at each event in the source property.
prop­ert­y.s­amp­led­By(­str­eam­OrP­rop­erty, f)
samples the property on stream events. The result values will be formed using the given function f(prop­ert­yValue, sample­rVa­lue). You can use a method name (such as ".co­nca­t") instead of a function too.
prop­ert­y.s­kip­Dup­lic­ate­s(­[is­Equ­al])
drops consec­utive equal elements. So, from [1, 2, 2, 1] you'd get [1, 2, 1]. Uses the === operator for equality checking by default. If the isEqual argument is supplied, checks by calling isEqua­l(o­ldV­alue, newValue). The old name for this method was "­dis­tin­ctU­nti­lCh­ang­ed".
prop­ert­y.c­han­ges()
returns an EventS­tream of property value changes. Returns exactly the same events as the property itself, except any Initial events. Note that proper­ty.c­ha­nges() does NOT skip duplicate values, use .skipD­upl­ica­tes() for that.
prop­ert­y.a­nd(­oth­er)
combines properties with the && operator.
prop­ert­y.o­r(o­ther)
combines properties with the || operator.

Event Types

Baco­n.E­vent
has subclasses Next, End, Error and Initial
Baco­n.N­ext
next value in an EventS­tream or a Property. Call isNext() to distin­guish a Next event from other events.
Baco­n.End
an end-of­-stream event of EventS­tream or Property. Call isEnd() to distin­guish an End from other events.
Baco­n.E­rror
an error event. Call isError() to distin­guish these events in your subscr­iber, or use onError to react to error events only. errorE­ven­t.error returns the associated error object (usually string).
Baco­n.I­nit­ial
the initial (current) value of a Property. Call isInit­ial() to distin­guish from other events. Only sent immedi­ately after subscr­iption to a Property.

Event Methods

even­t.v­alu­e()
returns the value associated with a Next or Initial event
even­t.h­asV­alu­e()
returns true for events of type Initial and Next
even­t.i­sNe­xt()
true for Next events
even­t.i­sIn­iti­al()
true for Initial events
even­t.i­sEn­d()
true for End events
 

Share This Cheat Sheet!

Comments

nicholas nicholas, 08:31 9 Oct 14

Ah.... this is super-useful. Having a hard time swallowing all this bacon, and this cheat-sheet is a huge help. Thanks !

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.