简体   繁体   中英

Knockout.js: Select dropdown issue, always sets the “selected item” to the first option even when provided using “initial data”

jsFiddle: http://jsfiddle.net/wenbert/W2qLz/2/

Even though I have provided the "initial data" for the selected_skill array, the $data becomes the first item in the select box.

var initialData = [
    {
    id: '1',
    name: "Batman",
    isDelete: false,
    selected_skill: {              <--- This part right here.
        id: '2',
        name: "Boxing",
        isDeleted: false
    },
    skills: [
        {
        id: '1',
        name: "Karate",
        isDeleted: false},
    {
        id: '2',
        name: "Boxing",
        isDeleted: false
    },
    {
        id: '6',
        name: "Sonar",
        isDeleted: false}
    ]},
{
    id: '2',
    name: "Hulk",
    isDelete: false,
    skills: [
        {
        id: '3',
        name: "MMA",
        isDeleted: false},
    {
        id: '4',
        name: "Rage",
        isDeleted: false},
    {
        id: '5',
        name: "Extra Strength",
        isDeleted: false}
    ]},
    ];

See the $data part in the screenshot below

在此处输入图片说明

I have the initial_data provided but when everything is "loaded", $data is automatically updated based on the first option for the select box.

How do I set the "selected option" this way?

In the screenshot, the selected_skill should have been:

selected_skill: {
    id: '2',
    name: "Boxing",
    isDeleted: false
}

jsFiddle: http://jsfiddle.net/wenbert/W2qLz/2/

UPDATE:

The initialData in my real app is loaded using $.getJSON() . I do it with something like this:

$.getJSON(appUrl+"/getstuff/hero.json", 
    function(data){
        ko.applyBindings(new Hero(data));
    }
);

I can see that the result from the Firebug Console says that it is "Boxing" - I get Object { id="2", nameL: "Boxing", isDelete: false } . But then when everything has been rendered, the selected_skill is becomes the first option.

I hope this is making sense. If not, I would be glad to answer clarifications through the comments.

FINAL UPDATE

I used:

return item.id() === data.selected_skill.id 

instead of

return data.selected_skill && skill.id === data.selected_skill.id; 

then it worked.

I have marked the correct answer.

The issue is that the selected_skill object is a different object that the one in skills array rather than a reference to the same object.

In JavaScript,

var a = { name: "Bob" };
var b = { name: "Bob" };
var c = a;

alert(a === b);  //false - different objects
alert(a === c);  //true - reference to the same object

You would need to run some logic to match the selected object with one from the list. Maybe something like: http://jsfiddle.net/rniemeyer/W2qLz/3/

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