Bacon.js – Bus

Bacon.jsBacon.js bus is an excellent way to publish and subscribe to event streams through one unified channel. Bus helps a developer to decouple application and makes code much cleaner.

Bacon.js Bus example

This example outputs status of each validator to html page. It shows simple example of publish/subscribe with Bacon.js.

First we need some scripts – JQuery, Bacon.js and Bacon.UI.js.

This the actual Javascript code. I’m going to walk you through it.

First we define keys that are used to indicate what value is moving in the Bus. Publisher adds a key to message and subscriber listens using the key.

We’re initializing new Bacon.Bus() which is used as Bus. Were defining new dynamic property ofType for bus. The property is used to filter correct messages to who ever is listening.

Then we create form validators. Beginning is the same than in previous Bacon.js post. After that we publish name, age and button event stream values to the bus. A Message is delivered constantly while user is interacting.

After that we subscribe to name and age by using our keys NAME_MESSAGE and AGE_MESSAGE. They’re handed over as a parameter to our dynamic property ofType. We also use merge which allows a user to combine two streams into one. Then we just assing value to markup.

Final step is to subscribe to button validation which tells us if whole form is valid or not. This is also written to out the markup.

Here is static HTML that we’re using in this Bacon.js example.

Bacon Bus is very easy publish/subscribe mechanism. It can be used from full blown application bus to simple form messaging.

This entry was posted in bacon.js, Functional Reactive Programming, Other, Programming and tagged , , . Bookmark the permalink.

2 Responses to Bacon.js – Bus

  1. Nice read!

    Some comments:

    - Bus.plug can be used to plug-in inputs to the bus. So, you might simplify attachStreamValue to bus.plug(eventStream.map(function(value){ return {message:message, value:value}}))
    - It might be said too, that in this simple example, a Bus is not required. It may, however become useful when coordinating the interaction of several independent components.
    - Functions createOfTypeFor and “and” are unused

    Keep up the good work, Jari!

  2. Jari Timonen says:

    Thanks Paanis for teh comments. How can I miss empty code block! And yes, it’s supposed to be a simple examle :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">