Created
September 13, 2011 05:07
-
-
Save aaronpowell/1213159 to your computer and use it in GitHub Desktop.
Validated observables in KnockousJS
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
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; | |
}; |
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
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