Knockout.js: Function parameter undefined

ぃ、小莉子 提交于 2019-12-11 00:59:54

问题


I have a very simple example that is not working.

jsfiddle: http://jsfiddle.net/ThomasDeutsch/8hzhp/3/

// My Model
function Customer(id, name, lastname) {
    this.Id = ko.observable(id);
    this.Name = ko.observable(name);
    this.LastName = ko.observable(lastname);
}

// My ViewModel
ViewModel = (function () {
    var getName = ko.computed(function (x) {
        return x.Name();
    });

    return {
        getName: getName(new Customer(1, "Thomas", "D"))
    };
})();

ko.applyBindings(ViewModel);​

problem: parameter (x) is undefined

goal: return the Name-Property of the called Object - i want to use the x as a property so that i can call this function with any Object with a observable Name property

Code explanation: This is done using the revealing-module-pattern with knockout.js. The Name-property is a ko.observable() - so the () is needed.

question: Why is x undefined?


回答1:


Let me ask you. Where do you think x is defined?

You are calling getName and passing a Customer, but getName doesn't expect a parameter.

If you rewrite your function like this it will work:

var getName = function(x) { return ko.computed( function() {
    return x.Name();
})};



回答2:


You're trying to change the value of the observable "getName", but since it's a computed one, that's undefined behavior until you specify how this should be handled.

I think the best solution would be to introduce another observable that stores the customer.

var ViewModel = (function() {
    // Observable for the customer
    var customer = ko.observable(new Customer(1, "Thomas", "D"));

    // The computed observable, using the other one
    var getName = ko.computed(function() {
        return customer().Name();
    });

    // If you only need to access the name, its sufficient
    // to export only that observable. However, this is still
    // read-only.
    return {
        getName: getName
    };
})();

If you want to make it writable, you can define a setter for the computed observable:

var getName = ko.computed({
    read: function() {
        return customer().Name();
    },
    write: function(n) {
        customer().Name(n);
    }
});

(not an example that makes the most sense, but that is because you don't really need a computed observable here)



来源:https://stackoverflow.com/questions/10873214/knockout-js-function-parameter-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!