Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Bacon.js - Bus

DZone's Guide to

Bacon.js - Bus

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

Bacon.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.

<html>
<head>
    <title>Bacon.js example</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script type="text/javascript" src="https://raw.github.com/raimohanska/bacon.js/master/dist/Bacon.min.js"></script>
    <script type="text/javascript" src="https://raw.github.com/raimohanska/Bacon.UI.js/master/Bacon.UI.js"></script>

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

<script type="text/javascript">
        var BUTTON_MESSAGE = "button";
        var NAME_MESSAGE = "name";
        var AGE_MESSAGE = "age";
        var bus = new Bacon.Bus();
        $(function () {
            bus.ofType = function (type) {
                return bus.filter(function (message) {
                    return message.message == type;
                })
            }

            createFormValidators();

            bus.ofType(NAME_MESSAGE)
                .merge(bus.ofType(AGE_MESSAGE))
                .onValue(function(value){
                     $("#fields")
                      .append(value.message + "=" + value.value + "
");
                 })

            bus.ofType(BUTTON_MESSAGE).onValue(function(value){
                $("#validations").append(value.value + "
")
            })
        })

        function createFormValidators() {
            var nameEntered = Bacon.UI.textFieldValue($("#name input")).map(nonEmpty);
            var ageEntered = Bacon.UI.textFieldValue($("#age input")).map(nonEmpty);
            var buttonEnabled = nameEntered.and(ageEntered);
            buttonEnabled.not().assign($("#submitButton button"), "attr", "disabled");
            attachStreamValue(NAME_MESSAGE, nameEntered);
            attachStreamValue(AGE_MESSAGE, ageEntered);
            attachStreamValue(BUTTON_MESSAGE, buttonEnabled);
        }

        function nonEmpty(s) {return s.length > 0}

        function attachStreamValue(message, eventStream){
            eventStream.onValue(function(value){
                bus.push({message:message, value:value});
            })

        }
    </script>

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.

</head>
<body>
<h1>Bacon.js POW!</h1>
<div id="name">
    Name: <input type="text">
</div>
<div id="age">
    Age: <input type="text">
</div>
<div id="submitButton">
    <button>Submit</button>
</div>
<div style="position:relative; float:left;">
    <h4>Combined Validation result:</h4>
    <span id="validations"></span>
</div>

<div style="position:relative; float:left;margin-left:5em">
    <h4>Field validation result:</h4>
    <span id="fields"></span>
</div>
</body>
</html>

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

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}