Milo Basics - Messenger

An introduction to milo messenger

by Jason Green

HTML

<script src="https://rawgit.com/milojs/milo/master/dist/milo.min.js"></script>

<!-- Milo is messenger crazy, everything has a messenger, components, 
     their facets, models, and even milo itself (milo.mail).
     So it's obviously important that we get a handle on them. -->

<!-- Most of the tutorial will be in JavaScript, but lets setup two component
     so we can explore messenger with components and facets. -->

<div ml-bind="[events]:comp">COMPONENT</div>
<input ml-bind="[data]:input" />

JavaScript

milo(function() {
    var mail = milo.mail
        , scope = milo.binder()
        , comp = scope.comp
        , input = scope.input;
    // The easiest way to get to know messenger is to take a look at milo's
    // global messenger, milo.mail. The milo.mail messenger uses the window
    // to give us a wrapper for the native 'window.postMessage', but can also
    // pass any custom messages, so let's have a look at that.
    
    // Messenger has methods for managing listeners, on and off are for 
    // adding and removing single subscribers.
    mail.on('mymessage', example1);
    mail.off('mymessage', example1);
    
    // You can also put multiple messages in a string, or an array
    mail.on('msg1 msg2 msg3', example1);
    
    // We also have onMessages, and offMessages for multiple subscribers.
    mail.onMessages({
        'message1': example1,
        'message2': example2,
        'message3': example1
    });
    mail.offMessages({
        'message1': example1,
        'message2': example2
    });
    
    // We can also pass a regular expression, instead of a string, as
    // the message.
    milo.mail.on(/.*/, example3);
    
    // We can get all the subscribers for any given message using getSubscribers.
    // Notice the only one left for 'message1' is the regex 'catch-all'.
    console.log('LOG 1: ', mail.getSubscribers('message1'));
    
    // If you look at the logs, we still have one subscriber registered.
    // Lets trigger that using the messenger postMessage method.
    mail.postMessage('message1');
    
    // We can pass any data we like along with the message.
    mail.postMessage('message1', {name: 'Jason', age: 30});
    
    // We also have a method for turning off all messages.
    mail.offAll();

    // More importantly, we have messengers on components and their facets.
    // Component messengers work much the same as milo.mail, but with the
    // context set as the component itself
    comp.on('begin', function(msg, data) {...