Search code examples
javascriptbacon.js

What does merge and toProperty do in bacon.js


I have just started to working with bacon.js and trying to find out how does it work. On the following code asEventStream returns an eventStream and when in captures a blur event it emits a false value as I understand. What does the merge and toProperty do I can't get it from the code.

var blur = $(window).asEventStream('blur').map(function() {
  return false;
});
var focus =  $(window).asEventStream('focus').map(function() {
  return true;
});
var focused = focus.merge(blur).toProperty(true);

Solution

  • focused is a stream that contains all of the events of the blur and focus streams. focused is also property, which means that whenever someone subscribes to it, they immediately receive the most recent value from the stream. true is specified as the default beginning value to give if no values have come through yet.

    Say that this was run next:

    focused.onValue(function(x) {
      console.log('received', x);
    });
    

    'received true' will be immediately printed to the screen. If/when the window loses focus, 'received false' will be printed. If/when the window gets focused again, 'received true' will be printed.