-
-
Save bs1180/c12f2a1a74e06bbcac48 to your computer and use it in GitHub Desktop.
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