【问题标题】:When will be the extender function will get called什么时候会调用扩展函数
【发布时间】:2014-05-28 07:40:29
【问题描述】:

我是淘汰 js 的新手。我想为一个 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

问候, 斯里尼瓦斯

【问题讨论】:

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


    【解决方案1】:

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

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

    所以将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.

    【讨论】:

    • 简单有效的谢谢
    • 我们能否将多个值传递给同一个扩展器函数,就像我想将两个名称传递给 logChange() 函数一样
    • 你可以传入一个对象作为扩展器的参数:ko.observable(first).extend({logChange: {name1: "Sri", name2: "Sri2" }});,在你的扩展器中你可以使用option.name1option.name2jsfiddle.net/TMgm5访问属性
    猜你喜欢
    • 1970-01-01
    • 2012-04-07
    • 2016-05-20
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多