1

In experimenting with Bacon.js, I've come across the following unexpected behavior:

    var email = $("#email")
                            .asEventStream("keyup")
                            .map(function(event) {
                                return $(event.target).val();
                            })
                            .log();

    var validEmail = email.map(validateEmail).log();

    // submit.doAction('.preventDefault'); isn't working for some reason
    $('form').on('submit', function (event) { event.preventDefault() });

    var submit = $('form').asEventStream('submit');

    // postFormData is never called
    Bacon.when([email, validEmail, submit], postFormData);  

Each of the streams emits values appropriately, but the join pattern is never matched.

Fiddle

pdoherty926
  • 9,895
  • 4
  • 37
  • 68

1 Answers1

2

You never do anything with the result of Bacon.when, so lazy evaluation causes postFormData never to be called.

As a rule of thumb, something that causes side effects, like posting the data to server, should be done in an onValue handler. Combining the different EventStreams should be done using pure functions.

I updated your fiddle by adding a .log at the end.

OlliM
  • 7,023
  • 1
  • 36
  • 47
  • OK - this makes sense. [The docs](https://github.com/baconjs/bacon.js/#join-patterns-as-a-chemical-machine) could do a better job of explaining what you just have. (There's no assignment of the result of `when` and the matching functions (i.e. `make_water`) would appear to have side effects.) You should consider submitting a PR! – pdoherty926 Oct 27 '14 at 11:58
  • This is one of the major pitfalls in Bacon.js that many people run into. – OlliM Oct 27 '14 at 13:23
  • As a side note, you don't need `Bacon.when` for this sort of code, simpler `combine`, `combineWith` and `combineTemplate` would do. – OlliM Oct 27 '14 at 13:29
  • 1
    If you want an example of form field handling with bacon, you can check out this [fiddle](http://jsfiddle.net/bFL4D/4/) from a presentation I gave at work about frp and bacon: http://ollimahlamaki.fi/baconjs-presentation/ – OlliM Oct 27 '14 at 13:30
  • Yeah, I ended up using `combineAsArray`. I'll definitely check out your presentation. Thanks for your feedback! – pdoherty926 Oct 27 '14 at 14:01