简体   繁体   中英

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.

要访问该阵列,您必须打开它:

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

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());

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