2

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/

4

1 回答 1

3

计算的 observable 在您创建它们时会立即进行评估。在创建时, 的值self.name()是未定义的。所以,你match不能取消未定义。

一种选择是初始化您的名称,例如:

this.name = ko.observable(name || "");
于 2012-12-01T20:45:39.050 回答