I have an observable array containing objects (dynamically created) that have themselves observable attributes. So far so god, but when I try to add a computed observable to the dynamically created object, the observables of the object resolve to undefined.
// Object whose model has an observable array and an instance of the dynamically generated objects
function SecretSanta(params) {
...
ko.applyBindings(new this.Model(this));
};
SecretSanta.prototype = {
...
Model: function(secretSanta) {
var self = this;
this.secretSanta = secretSanta;
this.newSanta = new Santa();
this.santas = ko.observableArray();
this.addSanta = function() {
self.santas.unshift(new Santa(self.newSanta.getName(), self.newSanta.getEmail()));
self.newSanta.clear();
}
this.removeSanta = function(santa) {
self.santas.splice(self.santas.indexOf(santa), 1);
};
this.santasCount = ko.computed(function() {
return self.santas().length;
});
this.valid = ko.computed(function() {
return self.santasCount() >= self.secretSanta.VALID_SANTAS;
});
}
};
// Dynamically generated objects
function Santa(name, email) {
var self = this;
this.name = ko.observable(name);
this.email = ko.observable(email);
this.valid = ko.computed(function () {
return self.name().match(/\w{3,}/);
});
}
In the last line of code the console is complaining that self.name() is undefined; if i get rid of the computed initialization and set this.valid to the function inside, it works fine (but the bindings do not get update).
Can any one point out what i am doing wrong?. Thanks a lot in advance.
I provide a link to the complete code http://jsfiddle.net/jeAtT/5/