在Knockout.JS中设置选择列表值 [英] Setting select list value in Knockout.JS

查看:145
本文介绍了在Knockout.JS中设置选择列表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用从jQuery GET请求中检索的JSON数据填充输入表(文本框和选择列表).对于该示例,我预先设置了一些数据变量,而不是发出get请求.文本框输入已正确填充数据,但选择列表将不会填充.

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.

无论如何,这是带有代码的小提琴.

推荐答案

选择列表不会填充的原因是对象相等.它们通过选项绑定绑定到availableEmployees可观察数组,而值绑定绑定到Employee,但是当您设置每个任务的employee属性时,会将其设置为具有相同属性和值的新对象,在javascript中不相等.我要做的实际上是在可用雇员列表中搜索匹配的雇员(我的示例在循环搜索中很糟糕,只是为了向我展示我的意思),然后将雇员设置为该实际对象,而不是即将出现的对象从任务的信息.检查一下:

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]
}];

这是因为在javascript中:

This is because in javascript:

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

JSFiddle

这篇关于在Knockout.JS中设置选择列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆