什么时候扩展函数会被调用

时间:2014-04-14 11:07:54

标签: javascript knockout.js knockout-validation knockout-mvc

我是淘汰赛的新手。我想为一个observable实现动态验证。为此我想使用扩展器功能。但它不是在呼唤。我创建了jsfiddle。 我怀疑它什么时候会被召唤。

代码是

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

此致 SRINIVAS

1 个答案:

答案 0 :(得分:2)

虽然文档中没有明确说明,但

任何自定义扩展程序定义必须在您第一次使用之前进行。

所以将ko.extenders.logChange部分移到ViewModel函数之外:

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

演示JSFiddle