Pregunta

Soy novato en knockout js.Quiero implementar validaciones dinámicas para un observable.Para eso quiero usar la función extensor.Pero no es una llamada.he creado el jsfiddle.Mi duda es cuando se convocará.

El código es

// 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

Saludos, Srinivas

¿Fue útil?

Solución

Aunque no se indica explícitamente en la documentación, pero

cualquier definición de extensor personalizado debe aparecer antes de la primera vez que la utilice.

Así que mueve el ko.extenders.logChange parte fuera de tu ViewModel función:

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);
};

Manifestación JSFiddle.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top