Tim Ferrell
Tim Ferrell

Reputation: 1366

Knockout.js - ObservableArray not returning values

In knockout, this works and binds correctly:

self.currentCustomer = ko.observable(new Customer("a","b","c","d","e","f","g","h"));

However, the below does not.

// Random list of customers
self.customers = ko.observableArray([
    new Customer("a","b","c","d","e","f","g","h")
]);


self.currentCustomer = ko.observable(self.customers[0]);

I cannot figure out why this is not working. This pattern in working correctly in other parts of my application.

Upvotes: 1

Views: 285

Answers (2)

Rups
Rups

Reputation: 639

Just to add to that, the View is as below:

<p>Customer Name <input data-bind="value: currentCustomer().name" /></p>

The model is as below:

function AppViewModel() {
   // Random list of customers
self.customers = ko.observableArray([
    new Customer("ABC Corp.")
]);


self.currentCustomer = ko.observable(self.customers()[0]); // This is the correction.

}


function Customer(_name)
{
    this.name = ko.observable(_name);
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());

Upvotes: 0

Michael Best
Michael Best

Reputation: 16688

To access the array, you must unwrap it:

self.currentCustomer = ko.observable(self.customers()[0]);

Upvotes: 3

Related Questions