Knockout Js - 将一个项目从json数组绑定到一个元素

时间:2012-02-01 23:29:45

标签: javascript jquery json binding knockout.js

我有以下视图模型,其中包含元素数组

   function ReservationsViewModel() {
        var self = this;


        self.availableMeals = [
            { mealName: "Standard (sandwich)", price: 0, id = 1 },
            { mealName: "Premium (lobster)", price: 34.95, id = 2 },
            { mealName: "Ultimate (whole zebra)", price: 290, id = 3 }
        ];  
  }

我想将此视图模型绑定到输入,但我想仅绑定具有id值的Single数组元素名称作为输入的data-id属性。

<input type="text" id="firstElementMealName" data-id="1" data-bind="value: ??"></input>

在这个例子中,我将绑定数组元素id = 1,文本将显示为“标准(三明治)”,但我仍然需要完整的绑定和更改跟踪(observables)和所有其他好的东西敲除。

如何获取data-id并在绑定代码中使用它来将适当的膳食绑定到输入?

提前致谢

1 个答案:

答案 0 :(得分:16)

建议的解决方案:

   function ReservationsViewModel() {
        var self = this;


        self.availableMeals = ko.observableArray([
            { mealName: "Standard (sandwich)", price: 0, id = 1 },
            { mealName: "Premium (lobster)", price: 34.95, id = 2 },
            { mealName: "Ultimate (whole zebra)", price: 290, id = 3 }
        ]);

        self.getMealById = function(id) {
            ko.utils.filterArray(self.availableMeals(), function(item) {
                return item.id == id;
            });
        };
  }

在视图中:

<input type="text" id="firstElementMealName" data-bind="value: getMealById(1)"></input>

编辑:这是一个双向解决方案:

function ReservationsViewModel() {
        var self = this;


    self.availableMeals = ko.observable({            
        id_1: { mealName: "Standard (sandwich)", price: ko.observable(0) },
        id_2: { mealName: "Premium (lobster)", price: ko.observable(34.95) },
        id_3: { mealName: "Ultimate (whole zebra)", price: ko.observable(290) }
        });
  }

ko.applyBindings(new ReservationsViewModel());

在视图中:

<input type="text" id="firstElementMealName" data-bind="value: availableMeals().id_2.price()"></input>