I am newbie to knockout js. I want to implement dynamic validations for one observable. For that i want to use the extender function. But it is not calling. I have created the jsfiddle. My doubt is when it will be called.
The code is
// Here's my data model
var ViewModel = function(first, last) {
this.firstName = ko.observable(first).extend({logChange: "Sri" });
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
ko.extenders.logChange = function(target, option) {
alert("log change function")
target.subscribe(function(newValue) {
alert("subscribe function: "+option + ": " + newValue);
});
return target;
};
};
ko.applyBindings(new ViewModel("Hello", "World")); // This makes Knockout get to work
Regards, Srinivas
Although it is explicitly not stated in the documentation but
any custom extender definition has to come before the first time you use it.
So move the ko.extenders.logChange
part outside of your ViewModel
function:
ko.extenders.logChange = function(target, option) {
alert("log change function")
target.subscribe(function(newValue) {
alert("subscribe function: "+option + ": " + newValue);
});
return target;
};
var ViewModel = function(first, last) {
this.firstName = ko.observable(first).extend({logChange: "Sri" });
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName
// depends on firstName and lastName, because these get called when
// evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
Demo JSFiddle.