1

TL;DR

How can I reset emailProfile/aliasProfile when email/alias is cleared after having a value?

Slightly longer version

I have a form that has inputs for email and alias. Neither is mandatory. But, if you fill in the alias field, it might require the email as well, if the alias is reserved.

So far so good, I have the pipe setup from an empty form, up until checking if an alias is reserved and whether the given email matches up. This works correctly and reliably.

Where my setup falters, is when after filling in a correct e-mail I clear the email. The status of emailProfile remains status quo (last server response).

What I want to achieve, is to clear emailProfile when email has no value (or actually when validEmail is false), but in all other cases return the last server response.

The direct (and only) way to tackle the problem I can think of, would be to drop the filter and return null from the lookup function when validation fails, but there has to be a better way, right?

// Functions that can be assumed to work as they should (they do):
// form.findInput, validAlias,validEmail, compose, 
// fetchProfilesByAlias, fetchProfileByEmail

var alias = Bacon.fromEventTarget(form.findInput("alias"), "change").
    merge(
        Bacon.fromEventTarget(form.findInput("alias"), "keyup")
    ).
    map(".target").
    map(".value").
    skipDuplicates().
    toProperty(form.findInput("alias").value);

var email = Bacon.fromEventTarget(form.findInput("email"), "change").
    merge(
        Bacon.fromEventTarget(form.findInput("email"), "keyup")
    ).
    map(".target").
    map(".value").
    skipDuplicates().
    toProperty(form.findInput("email").value);

var aliasProfiles = alias.
    debounce(600).
    filter(validAlias).
    flatMapLatest(compose(Bacon.fromPromise.bind(Bacon), fetchProfilesByAlias)).
    toProperty(null);

var emailProfile = email.
    debounce(600).
    filter(validEmail).
    flatMapLatest(compose(Bacon.fromPromise.bind(Bacon), fetchProfileByEmail)).
    toProperty(null);
nikc.org
  • 16,462
  • 6
  • 50
  • 83

1 Answers1

2

This is the most straightforward way I can think of.

var emailProfile = email.
  debounce(600).
  flatMapLatest(function(email) {
    if (validEmail(email)) {
      return Bacon.fromPromise(fetchProfileByEmail(email))
    } else {
      return null
    }
  }).
  toProperty(null)

Pretty much the same that you already discovered, except the if is not in the lookup function :)

raimohanska
  • 3,265
  • 17
  • 28
  • Thanks. This is essentially what I did, with some minor, mostly cosmetic differences in the implementation. Maybe I'm not so clueless as I thought I am. I'm very new to Bacon.js, but it smells delicious. – nikc.org Aug 20 '14 at 13:07