Pietro Coelho
Pietro Coelho

Reputation: 2072

How to use computed method inside foreach in knockout.js

I'm playing with knockout a little bit, and I'm stuck with something. I did the example that you create the first name, the last name and then create a ko.computed to make the fullName. That works ok, but let's say I have an observable array with a lot of objects containing first names and last names. How to use the computed function to create the full name? If i create something like:

function vm() {
....


self.fullName = ko.computed(function() {
  return self.names().firstName + "" + self.names().lastName;
}

I can't use it because this is a viewmodel method, and inside a foreach binding knockout will look for local methods (in this case, methods of self.names())

Also can't use $root.fullName because then knockout will not retrieve the correct value.

Fiddle: http://jsfiddle.net/mtfv6q6a/

Upvotes: 4

Views: 3900

Answers (1)

john Smith
john Smith

Reputation: 17906

you can call it by assiging a variable to your vm sth. like :

    appModel = new vm();
    ko.applyBindings(appModel);

and

    <h3 data-bind="text: appModel.fullName()"></h3>

this works, but would always return undefinedundefined http://jsfiddle.net/mtfv6q6a/1/ because firstName is not a property of names()

you rather need some simple function like:

self.returnFullName = function(item) {
    return item.firstName + " " + item.lastName;
};

and call it like

<h3 data-bind='text: appModel.returnFullName($data); '></h3>

http://jsfiddle.net/mtfv6q6a/2/

Upvotes: 3

Related Questions