Setting select list value in Knockout.JS

2019-09-13 05:31发布

问题:

I'm trying to populate a table of inputs (textboxes and select list) with JSON data retrieved from a jQuery GET request. For the example I pre-set a variable with some data rather than making a get request. The textbox inputs are correctly populating with data, but the select lists will not populate.

Here is an example of the data that knockout receives and places in the table

var returnedData = [{
    "taskID": "1",
    "taskName": "test task",
    "taskDetails": "details",
    "employee": {
        "employeeID": "1",
        "employeeName": "John"
    }
}, {
    "taskID": "2",
    "taskName": "another test",
    "taskDetails": "some more details",
    "employee": {
        "employeeID": "2",
        "employeeName": "Jane"
    }
}];

On the official knockout tutorials, they use a textarea (I included it in the fiddle) to show how the data is formatted as it is being posted back to the server. The pre-loaded data is in the exact same format.

Anyway, here is a fiddle with the code.

回答1:

The reason that the select lists won't populate is object equality. They're bound to availableEmployees observable array with the options binding and the value binding is to Employee, but when you're setting the employee property of each task, you're setting it to a new object with the same properties and values, which is not equal in javascript. What I'd do is actually search (my example has a terrible for loop search, just to show you what I mean) for the matching employee in your list of available employees, and set the employee to that actual object, not the object coming in from the task's info. Check this out:

var returnedData = [{         
    "taskID": "2",
    "taskName": "test task",
    "taskDetails": "details",
    "employee": self.availableEmployees()[1]
}, {
    "taskID": "5",
    "taskName": "another test",
    "taskDetails": "some more details",
    "employee": self.availableEmployees()[2]
}];

This is because in javascript:

var a = { foo: 1, bar: 'baz'};
var b = { foo: 1, bar: 'baz'};
console.log(a == b); // false

JSFiddle