Created
May 3, 2013 20:23
-
-
Save kaplas/5513726 to your computer and use it in GitHub Desktop.
valueAndValidFrom, a helper method for creating a pair of value and validity streams from a single RxJS Observable stream. Rocks the world, at least ours.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function notEmpty(val) { | |
return !_.isEmpty(val); | |
} | |
function valueAndValidFrom(observable, validator) { | |
validator = validator || notEmpty; | |
return { | |
valueS: observable.filter(validator), | |
validS: observable.map(validator) | |
}; | |
} | |
// Usage example 1 with the default validator | |
// ------------------------------------------ | |
var streetAddress = valueAndValidFrom( | |
$('#user-details-street-address') | |
.changeAsObservable() | |
.map(byEventTargetValue) | |
); | |
// Subscribe to a value from that stream (triggers only on *valid* values) | |
streetAddress.valueS.subscribe( fn ); | |
// Subscribe to true/false value about the validity of the stream (triggers on all changes) | |
streetAddress.validS.subscribe( fn ); | |
// Usage example 2 with a custom validator (validating date picker values) | |
// ----------------------------------------------------------------------- | |
function validateTravelTime(obj) { | |
return obj.start < obj.end; | |
} | |
var when = valueAndValidFrom( combinedMappedStreamBasedOn( | |
{ | |
start: startDateS.map(byEventTargetValue), | |
end: endDateS.map(byEventTargetValue) | |
} | |
), validateTravelTime); | |
// Usage example 3, validate the combined result of multiple input streams | |
// ----------------------------------------------------------------------- | |
function allValuesAreTrue(object) { | |
var values = _.values(object); | |
var and = function (a, b) { return (a && b); }; | |
return _.reduce(values, and); | |
} | |
var everythingIsValidS = combinedMappedStreamBasedOn({ | |
0: selectedCountry.validS, | |
1: when.validS, | |
2: reason.validS, | |
3: fullname.validS, | |
4: streetAddress.validS, | |
5: city.validS | |
}).map(allValuesAreTrue); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment