How to use calculated method inside foreach in knockout.js

I play with knockout a bit and I am stuck with something. I made an example that you create a first name, a last name, and then create ko.computed to create fullName. This works fine, but let me have an observable array with lots of objects containing first and last names. How to use a computed function to create a fully qualified name? If I create something like:

function vm() {
....


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

I cannot use it because it is a viewmodel method, and inside the knockout, foreach bindings will look for local methods (in this case, self.names () methods)

Also, you cannot use $ root.fullName, because then the knockout will not get the correct value.

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

+4
1

, vm sth. :

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

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

, undefinedundefined http://jsfiddle.net/mtfv6q6a/1/, firstName ()

, :

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

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

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

+3

All Articles