// Smart Observable
ko.smartObservable = function (initialValue, functions) {
var _temp = initialValue;
var _value = ko.observable(initialValue);
var result = ko.computed({
read: function () { return _value(); },
write: function (newValue) {
var shouldUpdate = true;
_temp = newValue;
if (functions) {
for (var i = 0; i < functions.length; i++) {
if (shouldUpdate && typeof (functions[i]) == "function")
shouldUpdate = functions[i](newValue, this.parent);
if (!shouldUpdate) break;
}
}
if (shouldUpdate) {
if (_temp !== _value()) _value(_temp);
}
else {
_value.valueHasMutated();
_temp = _value();
}
}
});
return result;
};
//model from the KnockoutJS tutorial
function AppViewModel() {
this.firstName = ko.smartObservable("Bert",[validateName,confirmChange]);
this.lastName = ko.observable("Bertington");
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
function validateName(value){
if (value.length==0){
alert("Name cannot be empty");
return false;
}
return true;
}
function confirmChange(value){
return confirm("Do you want to proceed with change?");
}
<!-- This is a *view* - HTML markup that defines the appearance of your UI -->
Enter an new value in the First Name field and get alert if string is empty or confirmation request otherwise.
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<p>Full name: <strong data-bind="text: fullName"></strong></p>
External resources loaded into this fiddle: