淘汰赛JS - 从绑定JSON数组中的单个项目到一个元素 [英] Knockout Js - Binding a single item from a json array to an element

查看:140
本文介绍了淘汰赛JS - 从绑定JSON数组中的单个项目到一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following view model which contains an array of elements

   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属性ID只有单数组元素一顿名称。

I want to bind this view model to a input, but i want to bind only the Single array element meal name that has the id value as the data-id attribute of the input.

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

在这个例子中,我会绑定ID = 1的数组元素,文本将显示为标准(三明治),但我仍然需要充分结合和变更跟踪(观测)和所有其他的好东西在淘汰赛。

In this example i would bind the array element with id = 1, and the text would appear as "Standard (Sandwich)", but i still need the full binding and change tracking (observables) and all the other good stuff in Knockout.

如何拿起数据-ID,并用它在结合code到合适的餐绑定到输入?

How to pick up the data-id and use it in the binding code to bind the appropriate meal to the input?

在此先感谢

推荐答案

建议解决方案:

   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());

在View:

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

这篇关于淘汰赛JS - 从绑定JSON数组中的单个项目到一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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