Knockout.js - 处理由外键连接的表中的数据

时间:2014-12-08 21:23:31

标签: knockout.js

作为Knockout.js的初学者,我在处理由外键连接的表中的数据时遇到问题。

假设我们有这么简单的代码:

function AppViewModel() {
    var self = this;

    self.users = ko.observableArray([
        {id: 0, name: "Willi", surname: "Jederman", meal: {id: 1, name: "Orange", price: 25.00}},
        {id: 1, name: "Hans", surname: "Kloss", meal: {id: 2, name: "Carrot", price: 300.00}}
    ]);

    self.meals = ko.observableArray([
        {id: 0, name: "Apple", price: 10.00},
        {id: 1, name: "Orange", price: 25.00},
        {id: 2, name: "Carrot", price: 300.00}
    ]);

    self.addUser = function() {
        self.users.push({id: null, name: "", surname: "", meal: {id: 0, name: "Apple", price: 10.00}});
    };    

    self.removeUser = function(user) {
        self.users.remove(user);
    };
}

ko.applyBindings(new AppViewModel());

数据:

{id: 0, name: "Willi", surname: "Jederman", meal: {id: 1, name: "Orange", price: 25.00}}

取自两个表 - 服务器将“users”和“meal”表中的行作为一个json返回 - 这些表由“users”表中的外键“meal_id”连接。

我也可以将此数据提取为:

{id: 0, name: "Willi", surname: "Jederman", meal_id: 1}

现在我想展示一个包含这些数据的简单表格:

name | surname | meal name | meal price

其中'meal name'是一个选项,其中的选项取自'self.meals'并且当前用户'meal.id'被选中。

我有'餐价'的问题 - 它会自动更改'饭名'选择更改,但我不知道该怎么做。

我的'饭名'选择如下:

(在data-bind =“foreach:users”中:)

<select data-bind="options: $root.meals,
                   optionsValue: 'id',
                   optionsText: 'name',
                   value: meal.id"></select>

我不知道我应该给“餐价”约束什么?我知道,它应该从'data-bind =“text:'...

开始

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您需要像这样的用户课程

function User(user, root) {

    this.id = ko.observable(user.id);
    this.name = ko.observable(user.name);
    this.surname = ko.observable(user.surname);
    this.mealId = ko.observable(user.mealId);

    this.root = root;

    this.currentMeal = ko.computed(function () {
        var mealId = this.mealId();
        return ko.utils.arrayFirst(this.root.meals, function(item) {
            return item.id === mealId;
        });
    }, this);
}

注意currentMeal计算,从根模型数据中找到它的id

使用root参数

连接您的模型
function AppViewModel() {

    this.meals = [
        { id: 0, name: "Apple", price: 10.00 },
        { id: 1, name: "Orange", price: 25.00 },
        { id: 2, name: "Carrot", price: 300.00 }
    ];

    this.users = ko.observableArray([
        new User({id: 0, name: "Willi", surname: "Jederman", mealId: 1}, this),
        new User({id: 1, name: "Hans", surname: "Kloss", mealId: 2}, this)
    ]);

    this.addUser = function() {
        this.users.push(new User({id: null, name: "", surname: "", mealId: 0}), this);
    };    

    this.removeUser = function(user) {
        this.users.remove(user);
    };
}

请参阅fiddle