Skip to content

Instantly share code, notes, and snippets.

@aaronpowell
Created September 13, 2011 05:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronpowell/1213159 to your computer and use it in GitHub Desktop.
Save aaronpowell/1213159 to your computer and use it in GitHub Desktop.
Validated observables in KnockousJS
ko.validatedObservable = function (initialValue, validationFunction) {
var latestValue = initialValue;
function observable() {
if (arguments.length > 0) {
// Write
// Ignore writes if the value hasn't changed
if (((!observable['equalityComparer']) || !observable['equalityComparer'](latestValue, arguments[0]))) {
if (validationFunction.call(null, arguments[0])) {
latestValue = arguments[0];
observable.notifySubscribers(latestValue);
} else {
console.log('invalid');
}
}
return this; // Permits chained assignments
}
else {
// Read
ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
return latestValue;
}
}
ko.subscribable.call(observable);
observable.valueHasMutated = function () {
observable.notifySubscribers(latestValue);
};
ko.utils.extend(observable, ko.observable['fn']);
ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
return observable;
};
var viewModel = {
numbersOnly: new ko.validatedObservable(1, function(x) { return !x || /\d+/g.test(x); }),
positive: new ko.validatedObservable(1, fuction(x) { return x && x > 0; }),
helloWorld: new ko.validatedObservable('hello world', function(x) { return x === 'hello world'; })
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment