Search code examples
javascriptparametersknockout.jsundefinedrevealing-module-pattern

Knockout.js: Function parameter undefined


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?


Solution

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