Search code examples
frpbacon.js

Use value of property from a different stream


Here's some simplified code. I press one button and it sets some config. Then when a user submits a form it needs to read the latest value of the config. I'm trying to be all FRP about it and avoid setting a normal variable.

var currentConfig = $('#authenticateCont #btnFormType')
        .asEventStream('click')
        .map(function (e) {
          ...
        });

$('#authenticateCont form')
        .asEventStream('submit')
         .combine(currentConfig, function(r, c) {
            return {
                response: r,
                config: c
            };
        })
        .onValue(function(e){
          ...
        });

This works except for the fact that when the config changes it results in the handler for the button click firing as if the form has been submitted. Obviously I don't want this.

It needs to be that when the form is submitted, it reads the latest value from the config. I need something like a 'combineLeft' operation that doesn't store the most recent submit event.

Come on.... how can something this simple be so tricky? Press a button, read a value!


Solution

  • I need something like a 'combineLeft' operation

    Yes, there is something like that: property.sampledBy(stream). It gets the current value from the config property whenever you click the submit button:

    var submit = $('#authenticateCont form').asEventStream('submit');
    currentConfig.sampledBy(submit, function(c, e) {
        return {event: e, config: c};
    })
    .onValue(function(e) { … });