【问题标题】:Knockout Js - Binding a single item from a json array to an elementKnockout Js - 将 json 数组中的单个项目绑定到元素
【发布时间】:2012-02-24 16:11:12
【问题描述】:

我有以下包含元素数组的视图模型

   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 值作为输入的 data-id 属性的单数组元素餐名。

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

在本例中,我将绑定 id = 1 的数组元素,文本将显示为“标准(三明治)”,但我仍然需要完整的绑定和更改跟踪(可观察)以及所有其他好东西淘汰赛。

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

提前致谢

【问题讨论】:

    标签: javascript jquery json binding knockout.js


    【解决方案1】:

    建议的解决方案:

       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>
    

    【讨论】:

    • 它在一个方向上工作,但我仍然没有得到双向绑定。我希望价格显示在输入中,然后当我更改它时,我希望绑定在视图模型中自动更新它?
    • 看起来 getMealById 函数缺少结束符 ')'?
    • 谢谢!现在已经修好了。
    猜你喜欢
    • 2018-06-04
    • 2021-12-27
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 2017-03-31
    • 2018-12-08
    • 2012-04-25
    相关资源
    最近更新 更多