简体   繁体   中英

knockoutjs - computed observables inside observable array

i have a ViewModel which is an observable array of objects that hold contacts' information that i am going to output using foreach . I need to have a computed observables that are dependent on firstName and lastName of each contact:

var contacts = ko.observableArray([
    {
        firstName: ko.observable("Jim"),
        lastName:  ko.observable("Carrey"),
        fullName:  ko.computed(function(){
            return this.firstName() + " " + this.lastName();
        }, this),
        image:     ko.observable("images/jim.jpg"),
        phones:    ko.observableArray([
            {type: ko.observable("Mobile"), number: ko.observable("(555) 121-2121")},
            {type: ko.observable("Home"), number: ko.observable("(555) 123-4567")}
        ])
    },
    ...//other objects of the same structure
]);
ko.applyBindings(contacts);

but i get this error Uncaught TypeError: Object #<HTMLDocument> has no method 'firstName' . Can someone explain why my reference to this.firstName() fails? Thanks.

The problem is that this in your contact definitions doesn't refer to the contacts themselves; it refers to the global object. Use a function (either a "classical" constructor or simply a function that creates an object literal and returns it) to create the contacts so that it can set their context properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM