Reputation: 721
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.
Upvotes: 0
Views: 742
Reputation: 15003
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.
Upvotes: 1